static inline void put_sample7(DCAContext *c, int64_t sample, int bits, int scale_factor) { sample = (sample << 15) / ((int64_t) lossy_quant[bits + 3] * scale_factor_quant7[scale_factor]); put_bits(&c->pb, bits, quantize((int) sample, bits)); }
void ff_h263_encode_picture_header(MpegEncContext * s, int picture_number) { int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref; int best_clock_code=1; int best_divisor=60; int best_error= INT_MAX; if(s->h263_plus){ for(i=0; i<2; i++){ int div, error; div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den); div= av_clip(div, 1, 127); error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div); if(error < best_error){ best_error= error; best_divisor= div; best_clock_code= i; } } } s->custom_pcf= best_clock_code!=1 || best_divisor!=60; coded_frame_rate= 1800000; coded_frame_rate_base= (1000+best_clock_code)*best_divisor; avpriv_align_put_bits(&s->pb); /* Update the pointer to last GOB */ s->ptr_lastgob = put_bits_ptr(&s->pb); put_bits(&s->pb, 22, 0x20); /* PSC */ temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp (coded_frame_rate_base * (int64_t)s->avctx->time_base.den); put_sbits(&s->pb, 8, temp_ref); /* TemporalReference */ put_bits(&s->pb, 1, 1); /* marker */ put_bits(&s->pb, 1, 0); /* h263 id */ put_bits(&s->pb, 1, 0); /* split screen off */ put_bits(&s->pb, 1, 0); /* camera off */ put_bits(&s->pb, 1, 0); /* freeze picture release off */ format = ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format), s->width, s->height); if (!s->h263_plus) { /* H.263v1 */ put_bits(&s->pb, 3, format); put_bits(&s->pb, 1, (s->pict_type == AV_PICTURE_TYPE_P)); /* By now UMV IS DISABLED ON H.263v1, since the restrictions of H.263v1 UMV implies to check the predicted MV after calculation of the current MB to see if we're on the limits */ put_bits(&s->pb, 1, 0); /* Unrestricted Motion Vector: off */ put_bits(&s->pb, 1, 0); /* SAC: off */ put_bits(&s->pb, 1, s->obmc); /* Advanced Prediction */ put_bits(&s->pb, 1, 0); /* only I/P frames, no PB frame */ put_bits(&s->pb, 5, s->qscale); put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */ } else { int ufep=1; /* H.263v2 */ /* H.263 Plus PTYPE */ put_bits(&s->pb, 3, 7); put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */ if (format == 8) put_bits(&s->pb,3,6); /* Custom Source Format */ else put_bits(&s->pb, 3, format); put_bits(&s->pb,1, s->custom_pcf); put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */ put_bits(&s->pb,1,0); /* SAC: off */ put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */ put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */ put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */ put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */ put_bits(&s->pb,1,0); /* Reference Picture Selection: off */ put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */ put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */ put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */ put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */ put_bits(&s->pb,3,0); /* Reserved */ put_bits(&s->pb, 3, s->pict_type == AV_PICTURE_TYPE_P); put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */ put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */ put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */ put_bits(&s->pb,2,0); /* Reserved */ put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */ /* This should be here if PLUSPTYPE */ put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */ if (format == 8) { /* Custom Picture Format (CPFMT) */ s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio); put_bits(&s->pb,4,s->aspect_ratio_info); put_bits(&s->pb,9,(s->width >> 2) - 1); put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */ put_bits(&s->pb,9,(s->height >> 2)); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){ put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num); put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den); } } if(s->custom_pcf){ if(ufep){ put_bits(&s->pb, 1, best_clock_code); put_bits(&s->pb, 7, best_divisor); } put_sbits(&s->pb, 2, temp_ref>>8); } /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */ if (s->umvplus) // put_bits(&s->pb,1,1); /* Limited according tables of Annex D */ //FIXME check actual requested range put_bits(&s->pb,2,1); /* unlimited */ if(s->h263_slice_structured) put_bits(&s->pb,2,0); /* no weird submodes */ put_bits(&s->pb, 5, s->qscale); }
int ff_wmv2_encode_picture_header(MpegEncContext * s, int picture_number) { Wmv2Context * const w= (Wmv2Context*)s; put_bits(&s->pb, 1, s->pict_type - 1); if(s->pict_type == FF_I_TYPE){ put_bits(&s->pb, 7, 0); } put_bits(&s->pb, 5, s->qscale); s->dc_table_index = 1; s->mv_table_index = 1; /* only if P frame */ s->per_mb_rl_table = 0; s->mspel= 0; w->per_mb_abt=0; w->abt_type=0; w->j_type=0; assert(s->flipflop_rounding); if (s->pict_type == FF_I_TYPE) { assert(s->no_rounding==1); if(w->j_type_bit) put_bits(&s->pb, 1, w->j_type); if(w->per_mb_rl_bit) put_bits(&s->pb, 1, s->per_mb_rl_table); if(!s->per_mb_rl_table){ ff_msmpeg4_code012(&s->pb, s->rl_chroma_table_index); ff_msmpeg4_code012(&s->pb, s->rl_table_index); } put_bits(&s->pb, 1, s->dc_table_index); s->inter_intra_pred= 0; }else{ int cbp_index; put_bits(&s->pb, 2, SKIP_TYPE_NONE); ff_msmpeg4_code012(&s->pb, cbp_index=0); if(s->qscale <= 10){ int map[3]= {0,2,1}; w->cbp_table_index= map[cbp_index]; }else if(s->qscale <= 20){ int map[3]= {1,0,2}; w->cbp_table_index= map[cbp_index]; }else{ int map[3]= {2,1,0}; w->cbp_table_index= map[cbp_index]; } if(w->mspel_bit) put_bits(&s->pb, 1, s->mspel); if(w->abt_flag){ put_bits(&s->pb, 1, w->per_mb_abt^1); if(!w->per_mb_abt){ ff_msmpeg4_code012(&s->pb, w->abt_type); } } if(w->per_mb_rl_bit) put_bits(&s->pb, 1, s->per_mb_rl_table); if(!s->per_mb_rl_table){ ff_msmpeg4_code012(&s->pb, s->rl_table_index); s->rl_chroma_table_index = s->rl_table_index; } put_bits(&s->pb, 1, s->dc_table_index); put_bits(&s->pb, 1, s->mv_table_index); s->inter_intra_pred= 0;//(s->width*s->height < 320*240 && s->bit_rate<=II_BITRATE); } s->esc3_level_length= 0; s->esc3_run_length= 0; return 0; }
static void flv_write_codec_header(AVFormatContext* s, AVCodecParameters* par) { int64_t data_size; AVIOContext *pb = s->pb; FLVContext *flv = s->priv_data; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int64_t pos; avio_w8(pb, par->codec_type == AVMEDIA_TYPE_VIDEO ? FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO); avio_wb24(pb, 0); // size patched later avio_wb24(pb, 0); // ts avio_w8(pb, 0); // ts ext avio_wb24(pb, 0); // streamid pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_AAC) { avio_w8(pb, get_audio_flags(s, par)); avio_w8(pb, 0); // AAC sequence header if (!par->extradata_size && (flv->flags & FLV_AAC_SEQ_HEADER_DETECT)) { PutBitContext pbc; int samplerate_index; int channels = flv->audio_par->channels - (flv->audio_par->channels == 8 ? 1 : 0); uint8_t data[2]; for (samplerate_index = 0; samplerate_index < 16; samplerate_index++) if (flv->audio_par->sample_rate == mpeg4audio_sample_rates[samplerate_index]) break; init_put_bits(&pbc, data, sizeof(data)); put_bits(&pbc, 5, flv->audio_par->profile + 1); //profile put_bits(&pbc, 4, samplerate_index); //sample rate index put_bits(&pbc, 4, channels); put_bits(&pbc, 1, 0); //frame length - 1024 samples put_bits(&pbc, 1, 0); //does not depend on core coder put_bits(&pbc, 1, 0); //is not extension flush_put_bits(&pbc); avio_w8(pb, data[0]); avio_w8(pb, data[1]); av_log(s, AV_LOG_WARNING, "AAC sequence header: %02x %02x.\n", data[0], data[1]); } avio_write(pb, par->extradata, par->extradata_size); } else { avio_w8(pb, par->codec_tag | FLV_FRAME_KEY); // flags avio_w8(pb, 0); // AVC sequence header avio_wb24(pb, 0); // composition time ff_isom_write_avcc(pb, par->extradata, par->extradata_size); } data_size = avio_tell(pb) - pos; avio_seek(pb, -data_size - 10, SEEK_CUR); avio_wb24(pb, data_size); avio_skip(pb, data_size + 10 - 3); avio_wb32(pb, data_size + 11); // previous tag size } }
static int encode_block(WMACodecContext *s, float (*src_coefs)[BLOCK_MAX_SIZE], int total_gain) { int v, bsize, ch, coef_nb_bits, parse_exponents; float mdct_norm; int nb_coefs[MAX_CHANNELS]; static const int fixed_exp[25] = { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 }; // FIXME remove duplication relative to decoder if (s->use_variable_block_len) { assert(0); // FIXME not implemented } else { /* fixed block len */ s->next_block_len_bits = s->frame_len_bits; s->prev_block_len_bits = s->frame_len_bits; s->block_len_bits = s->frame_len_bits; } s->block_len = 1 << s->block_len_bits; // assert((s->block_pos + s->block_len) <= s->frame_len); bsize = s->frame_len_bits - s->block_len_bits; // FIXME factor v = s->coefs_end[bsize] - s->coefs_start; for (ch = 0; ch < s->avctx->channels; ch++) nb_coefs[ch] = v; { int n4 = s->block_len / 2; mdct_norm = 1.0 / (float) n4; if (s->version == 1) mdct_norm *= sqrt(n4); } if (s->avctx->channels == 2) put_bits(&s->pb, 1, !!s->ms_stereo); for (ch = 0; ch < s->avctx->channels; ch++) { // FIXME only set channel_coded when needed, instead of always s->channel_coded[ch] = 1; if (s->channel_coded[ch]) init_exp(s, ch, fixed_exp); } for (ch = 0; ch < s->avctx->channels; ch++) { if (s->channel_coded[ch]) { WMACoef *coefs1; float *coefs, *exponents, mult; int i, n; coefs1 = s->coefs1[ch]; exponents = s->exponents[ch]; mult = pow(10, total_gain * 0.05) / s->max_exponent[ch]; mult *= mdct_norm; coefs = src_coefs[ch]; if (s->use_noise_coding && 0) { assert(0); // FIXME not implemented } else { coefs += s->coefs_start; n = nb_coefs[ch]; for (i = 0; i < n; i++) { double t = *coefs++ / (exponents[i] * mult); if (t < -32768 || t > 32767) return -1; coefs1[i] = lrint(t); } } } } v = 0; for (ch = 0; ch < s->avctx->channels; ch++) { int a = s->channel_coded[ch]; put_bits(&s->pb, 1, a); v |= a; } if (!v) return 1; for (v = total_gain - 1; v >= 127; v -= 127) put_bits(&s->pb, 7, 127); put_bits(&s->pb, 7, v); coef_nb_bits = ff_wma_total_gain_to_bits(total_gain); if (s->use_noise_coding) { for (ch = 0; ch < s->avctx->channels; ch++) { if (s->channel_coded[ch]) { int i, n; n = s->exponent_high_sizes[bsize]; for (i = 0; i < n; i++) { put_bits(&s->pb, 1, s->high_band_coded[ch][i] = 0); if (0) nb_coefs[ch] -= s->exponent_high_bands[bsize][i]; } } } } parse_exponents = 1; if (s->block_len_bits != s->frame_len_bits) put_bits(&s->pb, 1, parse_exponents); if (parse_exponents) { for (ch = 0; ch < s->avctx->channels; ch++) { if (s->channel_coded[ch]) { if (s->use_exp_vlc) { encode_exp_vlc(s, ch, fixed_exp); } else { assert(0); // FIXME not implemented // encode_exp_lsp(s, ch); } } } } else assert(0); // FIXME not implemented for (ch = 0; ch < s->avctx->channels; ch++) { if (s->channel_coded[ch]) { int run, tindex; WMACoef *ptr, *eptr; tindex = (ch == 1 && s->ms_stereo); ptr = &s->coefs1[ch][0]; eptr = ptr + nb_coefs[ch]; run = 0; for (; ptr < eptr; ptr++) { if (*ptr) { int level = *ptr; int abs_level = FFABS(level); int code = 0; if (abs_level <= s->coef_vlcs[tindex]->max_level) if (run < s->coef_vlcs[tindex]->levels[abs_level - 1]) code = run + s->int_table[tindex][abs_level - 1]; assert(code < s->coef_vlcs[tindex]->n); put_bits(&s->pb, s->coef_vlcs[tindex]->huffbits[code], s->coef_vlcs[tindex]->huffcodes[code]); if (code == 0) { if (1 << coef_nb_bits <= abs_level) return -1; put_bits(&s->pb, coef_nb_bits, abs_level); put_bits(&s->pb, s->frame_len_bits, run); } // FIXME the sign is flipped somewhere put_bits(&s->pb, 1, level < 0); run = 0; } else run++; } if (run) put_bits(&s->pb, s->coef_vlcs[tindex]->huffbits[1], s->coef_vlcs[tindex]->huffcodes[1]); } if (s->version == 1 && s->avctx->channels >= 2) avpriv_align_put_bits(&s->pb); } return 0; }
static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce, int win, int group_len, const float lambda) { BandCodingPath path[120][12]; int w, swb, cb, start, size; int i, j; const int max_sfb = sce->ics.max_sfb; const int run_bits = sce->ics.num_windows == 1 ? 5 : 3; const int run_esc = (1 << run_bits) - 1; int idx, ppos, count; int stackrun[120], stackcb[120], stack_len; float next_minbits = INFINITY; int next_mincb = 0; abs_pow34_v(s->scoefs, sce->coeffs, 1024); start = win*128; for (cb = 0; cb < 12; cb++) { path[0][cb].cost = run_bits+4; path[0][cb].prev_idx = -1; path[0][cb].run = 0; } for (swb = 0; swb < max_sfb; swb++) { size = sce->ics.swb_sizes[swb]; if (sce->zeroes[win*16 + swb]) { float cost_stay_here = path[swb][0].cost; float cost_get_here = next_minbits + run_bits + 4; if ( run_value_bits[sce->ics.num_windows == 8][path[swb][0].run] != run_value_bits[sce->ics.num_windows == 8][path[swb][0].run+1]) cost_stay_here += run_bits; if (cost_get_here < cost_stay_here) { path[swb+1][0].prev_idx = next_mincb; path[swb+1][0].cost = cost_get_here; path[swb+1][0].run = 1; } else { path[swb+1][0].prev_idx = 0; path[swb+1][0].cost = cost_stay_here; path[swb+1][0].run = path[swb][0].run + 1; } next_minbits = path[swb+1][0].cost; next_mincb = 0; for (cb = 1; cb < 12; cb++) { path[swb+1][cb].cost = 61450; path[swb+1][cb].prev_idx = -1; path[swb+1][cb].run = 0; } } else { float minbits = next_minbits; int mincb = next_mincb; int startcb = sce->band_type[win*16+swb]; next_minbits = INFINITY; next_mincb = 0; for (cb = 0; cb < startcb; cb++) { path[swb+1][cb].cost = 61450; path[swb+1][cb].prev_idx = -1; path[swb+1][cb].run = 0; } for (cb = startcb; cb < 12; cb++) { float cost_stay_here, cost_get_here; float bits = 0.0f; for (w = 0; w < group_len; w++) { bits += quantize_band_cost(s, sce->coeffs + start + w*128, s->scoefs + start + w*128, size, sce->sf_idx[(win+w)*16+swb], cb, 0, INFINITY, NULL); } cost_stay_here = path[swb][cb].cost + bits; cost_get_here = minbits + bits + run_bits + 4; if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run] != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1]) cost_stay_here += run_bits; if (cost_get_here < cost_stay_here) { path[swb+1][cb].prev_idx = mincb; path[swb+1][cb].cost = cost_get_here; path[swb+1][cb].run = 1; } else { path[swb+1][cb].prev_idx = cb; path[swb+1][cb].cost = cost_stay_here; path[swb+1][cb].run = path[swb][cb].run + 1; } if (path[swb+1][cb].cost < next_minbits) { next_minbits = path[swb+1][cb].cost; next_mincb = cb; } } } start += sce->ics.swb_sizes[swb]; } //convert resulting path from backward-linked list stack_len = 0; idx = 0; for (cb = 1; cb < 12; cb++) if (path[max_sfb][cb].cost < path[max_sfb][idx].cost) idx = cb; ppos = max_sfb; while (ppos > 0) { assert(idx >= 0); cb = idx; stackrun[stack_len] = path[ppos][cb].run; stackcb [stack_len] = cb; idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx; ppos -= path[ppos][cb].run; stack_len++; } //perform actual band info encoding start = 0; for (i = stack_len - 1; i >= 0; i--) { put_bits(&s->pb, 4, stackcb[i]); count = stackrun[i]; memset(sce->zeroes + win*16 + start, !stackcb[i], count); //XXX: memset when band_type is also uint8_t for (j = 0; j < count; j++) { sce->band_type[win*16 + start] = stackcb[i]; start++; } while (count >= run_esc) { put_bits(&s->pb, run_bits, run_esc); count -= run_esc; } put_bits(&s->pb, run_bits, count); } }
void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number) { int format; avpriv_align_put_bits(&s->pb); put_bits(&s->pb, 17, 1); put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */ put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->time_base.num) / //FIXME use timestamp s->avctx->time_base.den) & 0xff); /* TemporalReference */ if (s->width == 352 && s->height == 288) format = 2; else if (s->width == 176 && s->height == 144) format = 3; else if (s->width == 128 && s->height == 96) format = 4; else if (s->width == 320 && s->height == 240) format = 5; else if (s->width == 160 && s->height == 120) format = 6; else if (s->width <= 255 && s->height <= 255) format = 0; /* use 1 byte width & height */ else format = 1; /* use 2 bytes width & height */ put_bits(&s->pb, 3, format); /* PictureSize */ if (format == 0) { put_bits(&s->pb, 8, s->width); put_bits(&s->pb, 8, s->height); } else if (format == 1) { put_bits(&s->pb, 16, s->width); put_bits(&s->pb, 16, s->height); } put_bits(&s->pb, 2, s->pict_type == AV_PICTURE_TYPE_P); /* PictureType */ put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */ put_bits(&s->pb, 5, s->qscale); /* Quantizer */ put_bits(&s->pb, 1, 0); /* ExtraInformation */ if(s->h263_aic){ s->y_dc_scale_table= s->c_dc_scale_table= ff_aic_dc_scale_table; }else{ s->y_dc_scale_table= s->c_dc_scale_table= ff_mpeg1_dc_scale_table; } }
static int swf_write_header(AVFormatContext *s) { SWFContext *swf = s->priv_data; AVIOContext *pb = s->pb; PutBitContext p; uint8_t buf1[256]; int i, width, height, rate, rate_base; int version; swf->sound_samples = 0; swf->swf_frame_number = 0; swf->video_frame_number = 0; for(i=0;i<s->nb_streams;i++) { AVCodecContext *enc = s->streams[i]->codec; if (enc->codec_type == AVMEDIA_TYPE_AUDIO) { if (enc->codec_id == AV_CODEC_ID_MP3) { swf->audio_enc = enc; swf->audio_fifo= av_fifo_alloc(AUDIO_FIFO_SIZE); if (!swf->audio_fifo) return AVERROR(ENOMEM); } else { av_log(s, AV_LOG_ERROR, "SWF muxer only supports MP3\n"); return -1; } } else { if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_FLV1 || enc->codec_id == AV_CODEC_ID_MJPEG) { swf->video_enc = enc; } else { av_log(s, AV_LOG_ERROR, "SWF muxer only supports VP6, FLV1 and MJPEG\n"); return -1; } } } if (!swf->video_enc) { /* currently, cannot work correctly if audio only */ width = 320; height = 200; rate = 10; rate_base= 1; } else { width = swf->video_enc->width; height = swf->video_enc->height; rate = swf->video_enc->time_base.den; rate_base = swf->video_enc->time_base.num; } if (!swf->audio_enc) swf->samples_per_frame = (44100. * rate_base) / rate; else swf->samples_per_frame = (swf->audio_enc->sample_rate * rate_base) / rate; avio_write(pb, "FWS", 3); if (!strcmp("avm2", s->oformat->name)) version = 9; else if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_VP6F) version = 8; /* version 8 and above support VP6 codec */ else if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_FLV1) version = 6; /* version 6 and above support FLV1 codec */ else version = 4; /* version 4 for mpeg audio support */ avio_w8(pb, version); avio_wl32(pb, DUMMY_FILE_SIZE); /* dummy size (will be patched if not streamed) */ put_swf_rect(pb, 0, width * 20, 0, height * 20); avio_wl16(pb, (rate * 256) / rate_base); /* frame rate */ swf->duration_pos = avio_tell(pb); avio_wl16(pb, (uint16_t)(DUMMY_DURATION * (int64_t)rate / rate_base)); /* frame count */ /* avm2/swf v9 (also v8?) files require a file attribute tag */ if (version == 9) { put_swf_tag(s, TAG_FILEATTRIBUTES); avio_wl32(pb, 1<<3); /* set ActionScript v3/AVM2 flag */ put_swf_end_tag(s); } /* define a shape with the jpeg inside */ if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_MJPEG) { put_swf_tag(s, TAG_DEFINESHAPE); avio_wl16(pb, SHAPE_ID); /* ID of shape */ /* bounding rectangle */ put_swf_rect(pb, 0, width, 0, height); /* style info */ avio_w8(pb, 1); /* one fill style */ avio_w8(pb, 0x41); /* clipped bitmap fill */ avio_wl16(pb, BITMAP_ID); /* bitmap ID */ /* position of the bitmap */ put_swf_matrix(pb, (int)(1.0 * (1 << FRAC_BITS)), 0, 0, (int)(1.0 * (1 << FRAC_BITS)), 0, 0); avio_w8(pb, 0); /* no line style */ /* shape drawing */ init_put_bits(&p, buf1, sizeof(buf1)); put_bits(&p, 4, 1); /* one fill bit */ put_bits(&p, 4, 0); /* zero line bit */ put_bits(&p, 1, 0); /* not an edge */ put_bits(&p, 5, FLAG_MOVETO | FLAG_SETFILL0); put_bits(&p, 5, 1); /* nbits */ put_bits(&p, 1, 0); /* X */ put_bits(&p, 1, 0); /* Y */ put_bits(&p, 1, 1); /* set fill style 1 */ /* draw the rectangle ! */ put_swf_line_edge(&p, width, 0); put_swf_line_edge(&p, 0, height); put_swf_line_edge(&p, -width, 0); put_swf_line_edge(&p, 0, -height); /* end of shape */ put_bits(&p, 1, 0); /* not an edge */ put_bits(&p, 5, 0); flush_put_bits(&p); avio_write(pb, buf1, put_bits_ptr(&p) - p.buf); put_swf_end_tag(s); } if (swf->audio_enc && swf->audio_enc->codec_id == AV_CODEC_ID_MP3) { int v = 0; /* start sound */ put_swf_tag(s, TAG_STREAMHEAD2); switch(swf->audio_enc->sample_rate) { case 11025: v |= 1 << 2; break; case 22050: v |= 2 << 2; break; case 44100: v |= 3 << 2; break; default: /* not supported */ av_log(s, AV_LOG_ERROR, "swf does not support that sample rate, choose from (44100, 22050, 11025).\n"); return -1; } v |= 0x02; /* 16 bit playback */ if (swf->audio_enc->channels == 2) v |= 0x01; /* stereo playback */ avio_w8(s->pb, v); v |= 0x20; /* mp3 compressed */ avio_w8(s->pb, v); avio_wl16(s->pb, swf->samples_per_frame); /* avg samples per frame */ avio_wl16(s->pb, 0); put_swf_end_tag(s); } avio_flush(s->pb); return 0; }
int ff_adts_write_frame_header(ADTSContext *ctx, uint8_t *buf, int size, int pce_size) { PutBitContext pb; unsigned full_frame_size = (unsigned)ADTS_HEADER_SIZE + size + pce_size; if (full_frame_size > ADTS_MAX_FRAME_BYTES) { av_log(NULL, AV_LOG_ERROR, "ADTS frame size too large: %u (max %d)\n", full_frame_size, ADTS_MAX_FRAME_BYTES); return AVERROR_INVALIDDATA; } init_put_bits(&pb, buf, ADTS_HEADER_SIZE); /* adts_fixed_header */ put_bits(&pb, 12, 0xfff); /* syncword */ put_bits(&pb, 1, 0); /* ID */ put_bits(&pb, 2, 0); /* layer */ put_bits(&pb, 1, 1); /* protection_absent */ put_bits(&pb, 2, ctx->objecttype); /* profile_objecttype */ put_bits(&pb, 4, ctx->sample_rate_index); put_bits(&pb, 1, 0); /* private_bit */ put_bits(&pb, 3, ctx->channel_conf); /* channel_configuration */ put_bits(&pb, 1, 0); /* original_copy */ put_bits(&pb, 1, 0); /* home */ /* adts_variable_header */ put_bits(&pb, 1, 0); /* copyright_identification_bit */ put_bits(&pb, 1, 0); /* copyright_identification_start */ put_bits(&pb, 13, full_frame_size); /* aac_frame_length */ put_bits(&pb, 11, 0x7ff); /* adts_buffer_fullness */ put_bits(&pb, 2, 0); /* number_of_raw_data_blocks_in_frame */ flush_put_bits(&pb); return 0; }
static void put_swf_line_edge(PutBitContext *pb, int dx, int dy) { int nbits, mask; put_bits(pb, 1, 1); /* edge */ put_bits(pb, 1, 1); /* line select */ nbits = 2; max_nbits(&nbits, dx); max_nbits(&nbits, dy); mask = (1 << nbits) - 1; put_bits(pb, 4, nbits - 2); /* 16 bits precision */ if (dx == 0) { put_bits(pb, 1, 0); put_bits(pb, 1, 1); put_bits(pb, nbits, dy & mask); } else if (dy == 0) { put_bits(pb, 1, 0); put_bits(pb, 1, 0); put_bits(pb, nbits, dx & mask); } else { put_bits(pb, 1, 1); put_bits(pb, nbits, dx & mask); put_bits(pb, nbits, dy & mask); } }
static void put_swf_matrix(AVIOContext *pb, int a, int b, int c, int d, int tx, int ty) { PutBitContext p; uint8_t buf[256]; int nbits; init_put_bits(&p, buf, sizeof(buf)); put_bits(&p, 1, 1); /* a, d present */ nbits = 1; max_nbits(&nbits, a); max_nbits(&nbits, d); put_bits(&p, 5, nbits); /* nb bits */ put_bits(&p, nbits, a); put_bits(&p, nbits, d); put_bits(&p, 1, 1); /* b, c present */ nbits = 1; max_nbits(&nbits, c); max_nbits(&nbits, b); put_bits(&p, 5, nbits); /* nb bits */ put_bits(&p, nbits, c); put_bits(&p, nbits, b); nbits = 1; max_nbits(&nbits, tx); max_nbits(&nbits, ty); put_bits(&p, 5, nbits); /* nb bits */ put_bits(&p, nbits, tx); put_bits(&p, nbits, ty); flush_put_bits(&p); avio_write(pb, buf, put_bits_ptr(&p) - p.buf); }
/** * Encode band info for single window group bands. */ static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce, int win, int group_len, const float lambda) { BandCodingPath path[120][CB_TOT_ALL]; int w, swb, cb, start, size; int i, j; const int max_sfb = sce->ics.max_sfb; const int run_bits = sce->ics.num_windows == 1 ? 5 : 3; const int run_esc = (1 << run_bits) - 1; int idx, ppos, count; int stackrun[120], stackcb[120], stack_len; float next_minrd = INFINITY; int next_mincb = 0; abs_pow34_v(s->scoefs, sce->coeffs, 1024); start = win*128; for (cb = 0; cb < CB_TOT_ALL; cb++) { path[0][cb].cost = 0.0f; path[0][cb].prev_idx = -1; path[0][cb].run = 0; } for (swb = 0; swb < max_sfb; swb++) { size = sce->ics.swb_sizes[swb]; if (sce->zeroes[win*16 + swb]) { for (cb = 0; cb < CB_TOT_ALL; cb++) { path[swb+1][cb].prev_idx = cb; path[swb+1][cb].cost = path[swb][cb].cost; path[swb+1][cb].run = path[swb][cb].run + 1; } } else { float minrd = next_minrd; int mincb = next_mincb; next_minrd = INFINITY; next_mincb = 0; for (cb = 0; cb < CB_TOT_ALL; cb++) { float cost_stay_here, cost_get_here; float rd = 0.0f; if (cb >= 12 && sce->band_type[win*16+swb] < aac_cb_out_map[cb] || cb < aac_cb_in_map[sce->band_type[win*16+swb]] && sce->band_type[win*16+swb] > aac_cb_out_map[cb]) { path[swb+1][cb].prev_idx = -1; path[swb+1][cb].cost = INFINITY; path[swb+1][cb].run = path[swb][cb].run + 1; continue; } for (w = 0; w < group_len; w++) { FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb]; rd += quantize_band_cost(s, sce->coeffs + start + w*128, s->scoefs + start + w*128, size, sce->sf_idx[(win+w)*16+swb], aac_cb_out_map[cb], lambda / band->threshold, INFINITY, NULL); } cost_stay_here = path[swb][cb].cost + rd; cost_get_here = minrd + rd + run_bits + 4; if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run] != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1]) cost_stay_here += run_bits; if (cost_get_here < cost_stay_here) { path[swb+1][cb].prev_idx = mincb; path[swb+1][cb].cost = cost_get_here; path[swb+1][cb].run = 1; } else { path[swb+1][cb].prev_idx = cb; path[swb+1][cb].cost = cost_stay_here; path[swb+1][cb].run = path[swb][cb].run + 1; } if (path[swb+1][cb].cost < next_minrd) { next_minrd = path[swb+1][cb].cost; next_mincb = cb; } } } start += sce->ics.swb_sizes[swb]; } //convert resulting path from backward-linked list stack_len = 0; idx = 0; for (cb = 1; cb < CB_TOT_ALL; cb++) if (path[max_sfb][cb].cost < path[max_sfb][idx].cost) idx = cb; ppos = max_sfb; while (ppos > 0) { av_assert1(idx >= 0); cb = idx; stackrun[stack_len] = path[ppos][cb].run; stackcb [stack_len] = cb; idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx; ppos -= path[ppos][cb].run; stack_len++; } //perform actual band info encoding start = 0; for (i = stack_len - 1; i >= 0; i--) { cb = aac_cb_out_map[stackcb[i]]; put_bits(&s->pb, 4, cb); count = stackrun[i]; memset(sce->zeroes + win*16 + start, !cb, count); //XXX: memset when band_type is also uint8_t for (j = 0; j < count; j++) { sce->band_type[win*16 + start] = cb; start++; } while (count >= run_esc) { put_bits(&s->pb, run_bits, run_esc); count -= run_esc; } put_bits(&s->pb, run_bits, count); } }
static inline void asv2_put_bits(PutBitContext *pb, int n, int v){ put_bits(pb, n, reverse[ v << (8-n) ]); }
static void put_subframe(DCAContext *c, int32_t subband_data[8 * SUBSUBFRAMES][MAX_CHANNELS][32], int subframe) { int i, sub, ss, ch, max_value; int32_t *lfe_data = (int32_t*)(c->lfe_data + 4 * SUBSUBFRAMES * subframe); /* Subsubframes count */ put_bits(&c->pb, 2, SUBSUBFRAMES -1); /* Partial subsubframe sample count: dummy */ put_bits(&c->pb, 3, 0); /* Prediction mode: no ADPCM, in each channel and subband */ for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) put_bits(&c->pb, 1, 0); /* Prediction VQ addres: not transmitted */ /* Bit allocation index */ for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) put_bits(&c->pb, 5, QUANTIZER_BITS+3); if (SUBSUBFRAMES > 1) { /* Transition mode: none for each channel and subband */ for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) put_bits(&c->pb, 1, 0); /* codebook A4 */ } /* Determine scale_factor */ for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) { max_value = 0; for (i = 0; i < 8 * SUBSUBFRAMES; i++) max_value = FFMAX(max_value, FFABS(subband_data[i][ch][sub])); c->scale_factor[ch][sub] = find_scale_factor7(max_value, QUANTIZER_BITS); } if (c->lfe_channel) { max_value = 0; for (i = 0; i < 4 * SUBSUBFRAMES; i++) max_value = FFMAX(max_value, FFABS(lfe_data[i])); c->lfe_scale_factor = find_scale_factor7(max_value, LFE_BITS); } /* Scale factors: the same for each channel and subband, encoded according to Table D.1.2 */ for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) put_bits(&c->pb, 7, c->scale_factor[ch][sub]); /* Joint subband scale factor codebook select: not transmitted */ /* Scale factors for joint subband coding: not transmitted */ /* Stereo down-mix coefficients: not transmitted */ /* Dynamic range coefficient: not transmitted */ /* Stde information CRC check word: not transmitted */ /* VQ encoded high frequency subbands: not transmitted */ /* LFE data */ if (c->lfe_channel) { for (i = 0; i < 4 * SUBSUBFRAMES; i++) put_sample7(c, lfe_data[i], LFE_BITS, c->lfe_scale_factor); put_bits(&c->pb, 8, c->lfe_scale_factor); } /* Audio data (subsubframes) */ for (ss = 0; ss < SUBSUBFRAMES ; ss++) for (ch = 0; ch < c->prim_channels; ch++) for (sub = 0; sub < DCA_SUBBANDS; sub++) for (i = 0; i < 8; i++) put_sample7(c, subband_data[ss * 8 + i][ch][sub], QUANTIZER_BITS, c->scale_factor[ch][sub]); /* DSYNC */ put_bits(&c->pb, 16, 0xffff); }
/** * This filter creates an MPEG-4 AudioSpecificConfig from an MPEG-2/4 * ADTS header and removes the ADTS header. */ static int aac_adtstoasc_filter(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe) { GetBitContext gb; PutBitContext pb; AACADTSHeaderInfo hdr; AACBSFContext *ctx = bsfc->priv_data; init_get_bits(&gb, buf, AAC_ADTS_HEADER_SIZE*8); *poutbuf = (uint8_t*) buf; *poutbuf_size = buf_size; if (avctx->extradata) if (show_bits(&gb, 12) != 0xfff) return 0; if (avpriv_aac_parse_header(&gb, &hdr) < 0) { av_log(avctx, AV_LOG_ERROR, "Error parsing ADTS frame header!\n"); return AVERROR_INVALIDDATA; } if (!hdr.crc_absent && hdr.num_aac_frames > 1) { avpriv_report_missing_feature(avctx, "Multiple RDBs per frame with CRC"); return AVERROR_PATCHWELCOME; } buf += AAC_ADTS_HEADER_SIZE + 2*!hdr.crc_absent; buf_size -= AAC_ADTS_HEADER_SIZE + 2*!hdr.crc_absent; if (!ctx->first_frame_done) { int pce_size = 0; uint8_t pce_data[MAX_PCE_SIZE]; if (!hdr.chan_config) { init_get_bits(&gb, buf, buf_size * 8); if (get_bits(&gb, 3) != 5) { avpriv_report_missing_feature(avctx, "PCE-based channel configuration " "without PCE as first syntax " "element"); return AVERROR_PATCHWELCOME; } init_put_bits(&pb, pce_data, MAX_PCE_SIZE); pce_size = avpriv_copy_pce_data(&pb, &gb)/8; flush_put_bits(&pb); buf_size -= get_bits_count(&gb)/8; buf += get_bits_count(&gb)/8; } avctx->extradata_size = 2 + pce_size; avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE); init_put_bits(&pb, avctx->extradata, avctx->extradata_size); put_bits(&pb, 5, hdr.object_type); put_bits(&pb, 4, hdr.sampling_index); put_bits(&pb, 4, hdr.chan_config); put_bits(&pb, 1, 0); //frame length - 1024 samples put_bits(&pb, 1, 0); //does not depend on core coder put_bits(&pb, 1, 0); //is not extension flush_put_bits(&pb); if (pce_size) { memcpy(avctx->extradata + 2, pce_data, pce_size); } ctx->first_frame_done = 1; } *poutbuf = (uint8_t*) buf; *poutbuf_size = buf_size; return 0; }
static void put_frame_header(DCAContext *c) { /* SYNC */ put_bits(&c->pb, 16, 0x7ffe); put_bits(&c->pb, 16, 0x8001); /* Frame type: normal */ put_bits(&c->pb, 1, 1); /* Deficit sample count: none */ put_bits(&c->pb, 5, 31); /* CRC is not present */ put_bits(&c->pb, 1, 0); /* Number of PCM sample blocks */ put_bits(&c->pb, 7, SUBBAND_SAMPLES - 1); /* Primary frame byte size */ put_bits(&c->pb, 14, c->frame_size - 1); /* Audio channel arrangement */ put_bits(&c->pb, 6, c->channel_config); /* Core audio sampling frequency */ put_bits(&c->pb, 4, bitstream_sfreq[c->samplerate_index]); /* Transmission bit rate */ put_bits(&c->pb, 5, c->bitrate_index); /* Embedded down mix: disabled */ put_bits(&c->pb, 1, 0); /* Embedded dynamic range flag: not present */ put_bits(&c->pb, 1, 0); /* Embedded time stamp flag: not present */ put_bits(&c->pb, 1, 0); /* Auxiliary data flag: not present */ put_bits(&c->pb, 1, 0); /* HDCD source: no */ put_bits(&c->pb, 1, 0); /* Extension audio ID: N/A */ put_bits(&c->pb, 3, 0); /* Extended audio data: not present */ put_bits(&c->pb, 1, 0); /* Audio sync word insertion flag: after each sub-frame */ put_bits(&c->pb, 1, 0); /* Low frequency effects flag: not present or 64x subsampling */ put_bits(&c->pb, 2, c->lfe_channel ? 2 : 0); /* Predictor history switch flag: on */ put_bits(&c->pb, 1, 1); /* No CRC */ /* Multirate interpolator switch: non-perfect reconstruction */ put_bits(&c->pb, 1, 0); /* Encoder software revision: 7 */ put_bits(&c->pb, 4, 7); /* Copy history: 0 */ put_bits(&c->pb, 2, 0); /* Source PCM resolution: 16 bits, not DTS ES */ put_bits(&c->pb, 3, 0); /* Front sum/difference coding: no */ put_bits(&c->pb, 1, 0); /* Surrounds sum/difference coding: no */ put_bits(&c->pb, 1, 0); /* Dialog normalization: 0 dB */ put_bits(&c->pb, 4, 0); }
/** * Calculate rate distortion cost for quantizing with given codebook * * @return quantization distortion */ static av_always_inline float quantize_and_encode_band_cost_template( struct AACEncContext *s, PutBitContext *pb, const float *in, const float *scaled, int size, int scale_idx, int cb, const float lambda, const float uplim, int *bits, int BT_ZERO, int BT_UNSIGNED, int BT_PAIR, int BT_ESC) { const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512; const float Q = ff_aac_pow2sf_tab [q_idx]; const float Q34 = ff_aac_pow34sf_tab[q_idx]; const float IQ = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512]; const float CLIPPED_ESCAPE = 165140.0f*IQ; int i, j; float cost = 0; const int dim = BT_PAIR ? 2 : 4; int resbits = 0; const int range = aac_cb_range[cb]; const int maxval = aac_cb_maxval[cb]; int off; if (BT_ZERO) { for (i = 0; i < size; i++) cost += in[i]*in[i]; if (bits) *bits = 0; return cost * lambda; } if (!scaled) { abs_pow34_v(s->scoefs, in, size); scaled = s->scoefs; } quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval); if (BT_UNSIGNED) { off = 0; } else { off = maxval; } for (i = 0; i < size; i += dim) { const float *vec; int *quants = s->qcoefs + i; int curidx = 0; int curbits; float rd = 0.0f; for (j = 0; j < dim; j++) { curidx *= range; curidx += quants[j] + off; } curbits = ff_aac_spectral_bits[cb-1][curidx]; vec = &ff_aac_codebook_vectors[cb-1][curidx*dim]; if (BT_UNSIGNED) { for (j = 0; j < dim; j++) { float t = fabsf(in[i+j]); float di; if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow if (t >= CLIPPED_ESCAPE) { di = t - CLIPPED_ESCAPE; curbits += 21; } else { int c = av_clip(quant(t, Q), 0, 8191); di = t - c*cbrtf(c)*IQ; curbits += av_log2(c)*2 - 4 + 1; } } else { di = t - vec[j]*IQ; } if (vec[j] != 0.0f) curbits++; rd += di*di; } } else { for (j = 0; j < dim; j++) { float di = in[i+j] - vec[j]*IQ; rd += di*di; } } cost += rd * lambda + curbits; resbits += curbits; if (cost >= uplim) return uplim; if (pb) { put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]); if (BT_UNSIGNED) for (j = 0; j < dim; j++) if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f) put_bits(pb, 1, in[i+j] < 0.0f); if (BT_ESC) { for (j = 0; j < 2; j++) { if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) { int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191); int len = av_log2(coef); put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2); put_bits(pb, len, coef & ((1 << len) - 1)); } } } } } if (bits) *bits = resbits; return cost; }
static int aac_encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size, void *data) { AACEncContext *s = avctx->priv_data; int16_t *samples = s->samples, *samples2, *la; ChannelElement *cpe; int i, j, chans, tag, start_ch; const uint8_t *chan_map = aac_chan_configs[avctx->channels-1]; int chan_el_counter[4]; FFPsyWindowInfo windows[avctx->channels]; if (s->last_frame) return 0; if (data) { if (!s->psypp) { memcpy(s->samples + 1024 * avctx->channels, data, 1024 * avctx->channels * sizeof(s->samples[0])); } else { start_ch = 0; samples2 = s->samples + 1024 * avctx->channels; for (i = 0; i < chan_map[0]; i++) { tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; ff_psy_preprocess(s->psypp, (uint16_t*)data + start_ch, samples2 + start_ch, start_ch, chans); start_ch += chans; } } } if (!avctx->frame_number) { memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return 0; } start_ch = 0; for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; samples2 = samples + start_ch; la = samples2 + 1024 * avctx->channels + start_ch; if (!data) la = NULL; for (j = 0; j < chans; j++) { IndividualChannelStream *ics = &cpe->ch[j].ics; int k; wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, start_ch + j, ics->window_sequence[0]); ics->window_sequence[1] = ics->window_sequence[0]; ics->window_sequence[0] = wi[j].window_type[0]; ics->use_kb_window[1] = ics->use_kb_window[0]; ics->use_kb_window[0] = wi[j].window_shape; ics->num_windows = wi[j].num_windows; ics->swb_sizes = s->psy.bands [ics->num_windows == 8]; ics->num_swb = s->psy.num_bands[ics->num_windows == 8]; for (k = 0; k < ics->num_windows; k++) ics->group_len[k] = wi[j].grouping[k]; s->cur_channel = start_ch + j; apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2, j); } start_ch += chans; } do { int frame_bits; init_put_bits(&s->pb, frame, buf_size*8); if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) put_bitstream_info(avctx, s, LIBAVCODEC_IDENT); start_ch = 0; memset(chan_el_counter, 0, sizeof(chan_el_counter)); for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; for (j = 0; j < chans; j++) { s->cur_channel = start_ch + j; ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]); s->coder->search_for_quantizers(avctx, s, &cpe->ch[j], s->lambda); } cpe->common_window = 0; if (chans > 1 && wi[0].window_type[0] == wi[1].window_type[0] && wi[0].window_shape == wi[1].window_shape) { cpe->common_window = 1; for (j = 0; j < wi[0].num_windows; j++) { if (wi[0].grouping[j] != wi[1].grouping[j]) { cpe->common_window = 0; break; } } } s->cur_channel = start_ch; if (cpe->common_window && s->coder->search_for_ms) s->coder->search_for_ms(s, cpe, s->lambda); adjust_frame_information(s, cpe, chans); put_bits(&s->pb, 3, tag); put_bits(&s->pb, 4, chan_el_counter[tag]++); if (chans == 2) { put_bits(&s->pb, 1, cpe->common_window); if (cpe->common_window) { put_ics_info(s, &cpe->ch[0].ics); encode_ms_info(&s->pb, cpe); } } for (j = 0; j < chans; j++) { s->cur_channel = start_ch + j; encode_individual_channel(avctx, s, &cpe->ch[j], cpe->common_window); } start_ch += chans; } frame_bits = put_bits_count(&s->pb); if (frame_bits <= 6144 * avctx->channels - 3) break; s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits; } while (1); put_bits(&s->pb, 3, TYPE_END); flush_put_bits(&s->pb); avctx->frame_bits = put_bits_count(&s->pb); // rate control stuff if (!(avctx->flags & CODEC_FLAG_QSCALE)) { float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits; s->lambda *= ratio; s->lambda = FFMIN(s->lambda, 65536.f); } if (!data) s->last_frame = 1; memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return put_bits_count(&s->pb)>>3; }
static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { AACEncContext *s = avctx->priv_data; float **samples = s->planar_samples, *samples2, *la, *overlap; ChannelElement *cpe; int i, ch, w, g, chans, tag, start_ch, ret; int chan_el_counter[4]; FFPsyWindowInfo windows[AAC_MAX_CHANNELS]; if (s->last_frame == 2) return 0; /* add current frame to queue */ if (frame) { if ((ret = ff_af_queue_add(&s->afq, frame) < 0)) return ret; } copy_input_samples(s, frame); if (s->psypp) ff_psy_preprocess(s->psypp, s->planar_samples, s->channels); if (!avctx->frame_number) return 0; start_ch = 0; for (i = 0; i < s->chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = s->chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; for (ch = 0; ch < chans; ch++) { IndividualChannelStream *ics = &cpe->ch[ch].ics; int cur_channel = start_ch + ch; overlap = &samples[cur_channel][0]; samples2 = overlap + 1024; la = samples2 + (448+64); if (!frame) la = NULL; if (tag == TYPE_LFE) { wi[ch].window_type[0] = ONLY_LONG_SEQUENCE; wi[ch].window_shape = 0; wi[ch].num_windows = 1; wi[ch].grouping[0] = 1; /* Only the lowest 12 coefficients are used in a LFE channel. * The expression below results in only the bottom 8 coefficients * being used for 11.025kHz to 16kHz sample rates. */ ics->num_swb = s->samplerate_index >= 8 ? 1 : 3; } else { wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel, ics->window_sequence[0]); } ics->window_sequence[1] = ics->window_sequence[0]; ics->window_sequence[0] = wi[ch].window_type[0]; ics->use_kb_window[1] = ics->use_kb_window[0]; ics->use_kb_window[0] = wi[ch].window_shape; ics->num_windows = wi[ch].num_windows; ics->swb_sizes = s->psy.bands [ics->num_windows == 8]; ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8]; for (w = 0; w < ics->num_windows; w++) ics->group_len[w] = wi[ch].grouping[w]; apply_window_and_mdct(s, &cpe->ch[ch], overlap); } start_ch += chans; } if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels))) { av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n"); return ret; } do { int frame_bits; init_put_bits(&s->pb, avpkt->data, avpkt->size); if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) put_bitstream_info(s, LIBAVCODEC_IDENT); start_ch = 0; memset(chan_el_counter, 0, sizeof(chan_el_counter)); for (i = 0; i < s->chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; const float *coeffs[2]; tag = s->chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; put_bits(&s->pb, 3, tag); put_bits(&s->pb, 4, chan_el_counter[tag]++); for (ch = 0; ch < chans; ch++) coeffs[ch] = cpe->ch[ch].coeffs; s->psy.model->analyze(&s->psy, start_ch, coeffs, wi); for (ch = 0; ch < chans; ch++) { s->cur_channel = start_ch * 2 + ch; s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda); } cpe->common_window = 0; if (chans > 1 && wi[0].window_type[0] == wi[1].window_type[0] && wi[0].window_shape == wi[1].window_shape) { cpe->common_window = 1; for (w = 0; w < wi[0].num_windows; w++) { if (wi[0].grouping[w] != wi[1].grouping[w]) { cpe->common_window = 0; break; } } } s->cur_channel = start_ch * 2; if (s->options.stereo_mode && cpe->common_window) { if (s->options.stereo_mode > 0) { IndividualChannelStream *ics = &cpe->ch[0].ics; for (w = 0; w < ics->num_windows; w += ics->group_len[w]) for (g = 0; g < ics->num_swb; g++) cpe->ms_mask[w*16+g] = 1; } else if (s->coder->search_for_ms) { s->coder->search_for_ms(s, cpe, s->lambda); } } adjust_frame_information(cpe, chans); if (chans == 2) { put_bits(&s->pb, 1, cpe->common_window); if (cpe->common_window) { put_ics_info(s, &cpe->ch[0].ics); encode_ms_info(&s->pb, cpe); } } for (ch = 0; ch < chans; ch++) { s->cur_channel = start_ch + ch; encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window); } start_ch += chans; } frame_bits = put_bits_count(&s->pb); if (frame_bits <= 6144 * s->channels - 3) { s->psy.bitres.bits = frame_bits / s->channels; break; } s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits; } while (1); put_bits(&s->pb, 3, TYPE_END); flush_put_bits(&s->pb); avctx->frame_bits = put_bits_count(&s->pb); // rate control stuff if (!(avctx->flags & CODEC_FLAG_QSCALE)) { float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits; s->lambda *= ratio; s->lambda = FFMIN(s->lambda, 65536.f); } if (!frame) s->last_frame++; ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts, &avpkt->duration); avpkt->size = put_bits_count(&s->pb) >> 3; *got_packet_ptr = 1; return 0; }
int main(int argc, char **argv) { unsigned int p, i, type, size, retry; AVProbeData pd = { 0 }; AVLFG state; PutBitContext pb; int retry_count= 4097; int max_size = 65537; int j; for (j = i = 1; i<argc; i++) { if (!strcmp(argv[i], "-f") && i+1<argc && !single_format) { single_format = argv[++i]; } else if (read_int(argv[i])>0 && j == 1) { retry_count = read_int(argv[i]); j++; } else if (read_int(argv[i])>0 && j == 2) { max_size = read_int(argv[i]); j++; } else { fprintf(stderr, "probetest [-f <input format>] [<retry_count> [<max_size>]]\n"); return 1; } } if (max_size > 1000000000U/8) { fprintf(stderr, "max_size out of bounds\n"); return 1; } if (retry_count > 1000000000U) { fprintf(stderr, "retry_count out of bounds\n"); return 1; } avcodec_register_all(); av_register_all(); av_lfg_init(&state, 0xdeadbeef); pd.buf = NULL; for (size = 1; size < max_size; size *= 2) { pd.buf_size = size; pd.buf = av_realloc(pd.buf, size + AVPROBE_PADDING_SIZE); pd.filename = ""; if (!pd.buf) { fprintf(stderr, "out of memory\n"); return 1; } memset(pd.buf, 0, size + AVPROBE_PADDING_SIZE); fprintf(stderr, "testing size=%d\n", size); for (retry = 0; retry < retry_count; retry += FFMAX(size, 32)) { for (type = 0; type < 4; type++) { for (p = 0; p < 4096; p++) { unsigned hist = 0; init_put_bits(&pb, pd.buf, size); switch (type) { case 0: for (i = 0; i < size * 8; i++) put_bits(&pb, 1, (av_lfg_get(&state) & 0xFFFFFFFF) > p << 20); break; case 1: for (i = 0; i < size * 8; i++) { unsigned int p2 = hist ? p & 0x3F : (p >> 6); unsigned int v = (av_lfg_get(&state) & 0xFFFFFFFF) > p2 << 26; put_bits(&pb, 1, v); hist = v; } break; case 2: for (i = 0; i < size * 8; i++) { unsigned int p2 = (p >> (hist * 3)) & 7; unsigned int v = (av_lfg_get(&state) & 0xFFFFFFFF) > p2 << 29; put_bits(&pb, 1, v); hist = (2 * hist + v) & 3; } break; case 3: for (i = 0; i < size; i++) { int c = 0; while (p & 63) { c = (av_lfg_get(&state) & 0xFFFFFFFF) >> 24; if (c >= 'a' && c <= 'z' && (p & 1)) break; else if (c >= 'A' && c <= 'Z' && (p & 2)) break; else if (c >= '0' && c <= '9' && (p & 4)) break; else if (c == ' ' && (p & 8)) break; else if (c == 0 && (p & 16)) break; else if (c == 1 && (p & 32)) break; } pd.buf[i] = c; } } flush_put_bits(&pb); probe(&pd, type, p, size); } } } } if(AV_READ_TIME()) print_times(); return failures; }
int ff_adts_write_frame_header(ADTSContext *ctx, uint8_t *buf, int size, int pce_size) { PutBitContext pb; init_put_bits(&pb, buf, ADTS_HEADER_SIZE); /* adts_fixed_header */ put_bits(&pb, 12, 0xfff); /* syncword */ put_bits(&pb, 1, 0); /* ID */ put_bits(&pb, 2, 0); /* layer */ put_bits(&pb, 1, 1); /* protection_absent */ put_bits(&pb, 2, ctx->objecttype); /* profile_objecttype */ put_bits(&pb, 4, ctx->sample_rate_index); put_bits(&pb, 1, 0); /* private_bit */ put_bits(&pb, 3, ctx->channel_conf); /* channel_configuration */ put_bits(&pb, 1, 0); /* original_copy */ put_bits(&pb, 1, 0); /* home */ /* adts_variable_header */ put_bits(&pb, 1, 0); /* copyright_identification_bit */ put_bits(&pb, 1, 0); /* copyright_identification_start */ put_bits(&pb, 13, ADTS_HEADER_SIZE + size + pce_size); /* aac_frame_length */ put_bits(&pb, 11, 0x7ff); /* adts_buffer_fullness */ put_bits(&pb, 2, 0); /* number_of_raw_data_blocks_in_frame */ flush_put_bits(&pb); return 0; }
void ff_mjpeg_encode_picture_header(AVCodecContext *avctx, PutBitContext *pb, ScanTable *intra_scantable, int pred, uint16_t luma_intra_matrix[64], uint16_t chroma_intra_matrix[64]) { const int lossless = avctx->codec_id != AV_CODEC_ID_MJPEG && avctx->codec_id != AV_CODEC_ID_AMV; int hsample[4], vsample[4]; int i; int components = 3 + (avctx->pix_fmt == AV_PIX_FMT_BGRA); int chroma_matrix = !!memcmp(luma_intra_matrix, chroma_intra_matrix, sizeof(luma_intra_matrix[0])*64); ff_mjpeg_init_hvsample(avctx, hsample, vsample); put_marker(pb, SOI); // hack for AMV mjpeg format if(avctx->codec_id == AV_CODEC_ID_AMV) goto end; jpeg_put_comments(avctx, pb); jpeg_table_header(avctx, pb, intra_scantable, luma_intra_matrix, chroma_intra_matrix, hsample); switch (avctx->codec_id) { case AV_CODEC_ID_MJPEG: put_marker(pb, SOF0 ); break; case AV_CODEC_ID_LJPEG: put_marker(pb, SOF3 ); break; default: av_assert0(0); } put_bits(pb, 16, 17); if (lossless && ( avctx->pix_fmt == AV_PIX_FMT_BGR0 || avctx->pix_fmt == AV_PIX_FMT_BGRA || avctx->pix_fmt == AV_PIX_FMT_BGR24)) put_bits(pb, 8, 9); /* 9 bits/component RCT */ else put_bits(pb, 8, 8); /* 8 bits/component */ put_bits(pb, 16, avctx->height); put_bits(pb, 16, avctx->width); put_bits(pb, 8, components); /* 3 or 4 components */ /* Y component */ put_bits(pb, 8, 1); /* component number */ put_bits(pb, 4, hsample[0]); /* H factor */ put_bits(pb, 4, vsample[0]); /* V factor */ put_bits(pb, 8, 0); /* select matrix */ /* Cb component */ put_bits(pb, 8, 2); /* component number */ put_bits(pb, 4, hsample[1]); /* H factor */ put_bits(pb, 4, vsample[1]); /* V factor */ put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */ /* Cr component */ put_bits(pb, 8, 3); /* component number */ put_bits(pb, 4, hsample[2]); /* H factor */ put_bits(pb, 4, vsample[2]); /* V factor */ put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */ if (components == 4) { put_bits(pb, 8, 4); /* component number */ put_bits(pb, 4, hsample[3]); /* H factor */ put_bits(pb, 4, vsample[3]); /* V factor */ put_bits(pb, 8, 0); /* select matrix */ } /* scan header */ put_marker(pb, SOS); put_bits(pb, 16, 6 + 2*components); /* length */ put_bits(pb, 8, components); /* 3 components */ /* Y component */ put_bits(pb, 8, 1); /* index */ put_bits(pb, 4, 0); /* DC huffman table index */ put_bits(pb, 4, 0); /* AC huffman table index */ /* Cb component */ put_bits(pb, 8, 2); /* index */ put_bits(pb, 4, 1); /* DC huffman table index */ put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */ /* Cr component */ put_bits(pb, 8, 3); /* index */ put_bits(pb, 4, 1); /* DC huffman table index */ put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */ if (components == 4) { /* Alpha component */ put_bits(pb, 8, 4); /* index */ put_bits(pb, 4, 0); /* DC huffman table index */ put_bits(pb, 4, 0); /* AC huffman table index */ } put_bits(pb, 8, lossless ? pred : 0); /* Ss (not used) */ switch (avctx->codec_id) { case AV_CODEC_ID_MJPEG: put_bits(pb, 8, 63); break; /* Se (not used) */ case AV_CODEC_ID_LJPEG: put_bits(pb, 8, 0); break; /* not used */ default: av_assert0(0); } put_bits(pb, 8, 0); /* Ah/Al (not used) */ end: if (!lossless) { MpegEncContext *s = avctx->priv_data; av_assert0(avctx->codec->priv_data_size == sizeof(MpegEncContext)); s->esc_pos = put_bits_count(pb) >> 3; for(i=1; i<s->slice_context_count; i++) s->thread_context[i]->esc_pos = 0; }
static int gif_image_write_image(AVIOContext *pb, int x1, int y1, int width, int height, const uint8_t *buf, int linesize, int pix_fmt) { PutBitContext p; uint8_t buffer[200]; /* 100 * 9 / 8 = 113 */ int i, left, w, v; const uint8_t *ptr; /* image block */ avio_w8(pb, 0x2c); avio_wl16(pb, x1); avio_wl16(pb, y1); avio_wl16(pb, width); avio_wl16(pb, height); avio_w8(pb, 0x00); /* flags */ /* no local clut */ avio_w8(pb, 0x08); left= width * height; init_put_bits(&p, buffer, 130); /* * the thing here is the bitstream is written as little packets, with a size byte before * but it's still the same bitstream between packets (no flush !) */ ptr = buf; w = width; while(left>0) { put_bits(&p, 9, 0x0100); /* clear code */ for(i=(left<GIF_CHUNKS)?left:GIF_CHUNKS;i;i--) { if (pix_fmt == PIX_FMT_RGB24) { v = gif_clut_index(ptr[0], ptr[1], ptr[2]); ptr+=3; } else { v = *ptr++; } put_bits(&p, 9, v); if (--w == 0) { w = width; buf += linesize; ptr = buf; } } if(left<=GIF_CHUNKS) { put_bits(&p, 9, 0x101); /* end of stream */ flush_put_bits(&p); } if(put_bits_ptr(&p) - p.buf > 0) { avio_w8(pb, put_bits_ptr(&p) - p.buf); /* byte count of the packet */ avio_write(pb, p.buf, put_bits_ptr(&p) - p.buf); /* the actual buffer */ p.buf_ptr = p.buf; /* dequeue the bytes off the bitstream */ } left-=GIF_CHUNKS; } avio_w8(pb, 0x00); /* end of image block */ return 0; }
static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id) { MpegMuxContext *s = ctx->priv_data; int size, i, private_stream_coded, id; PutBitContext pb; init_put_bits(&pb, buf, 128); put_bits32(&pb, SYSTEM_HEADER_START_CODE); put_bits(&pb, 16, 0); put_bits(&pb, 1, 1); put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */ put_bits(&pb, 1, 1); /* marker */ if (s->is_vcd && only_for_stream_id==VIDEO_ID) { /* This header applies only to the video stream (see VCD standard p. IV-7)*/ put_bits(&pb, 6, 0); } else put_bits(&pb, 6, s->audio_bound); if (s->is_vcd) { /* see VCD standard, p. IV-7*/ put_bits(&pb, 1, 0); put_bits(&pb, 1, 1); } else { put_bits(&pb, 1, 0); /* variable bitrate*/ put_bits(&pb, 1, 0); /* non constrainted bit stream */ } if (s->is_vcd || s->is_dvd) { /* see VCD standard p IV-7 */ put_bits(&pb, 1, 1); /* audio locked */ put_bits(&pb, 1, 1); /* video locked */ } else { put_bits(&pb, 1, 0); /* audio locked */ put_bits(&pb, 1, 0); /* video locked */ } put_bits(&pb, 1, 1); /* marker */ if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) { /* This header applies only to the audio stream (see VCD standard p. IV-7)*/ put_bits(&pb, 5, 0); } else put_bits(&pb, 5, s->video_bound); if (s->is_dvd) { put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */ put_bits(&pb, 7, 0x7f); /* reserved byte */ } else put_bits(&pb, 8, 0xff); /* reserved byte */ /* DVD-Video Stream_bound entries id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1) id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0) id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1) id (0xBF) private stream 2, NAV packs, set to 2x1024. */ if (s->is_dvd) { int P_STD_max_video = 0; int P_STD_max_mpeg_audio = 0; int P_STD_max_mpeg_PS1 = 0; for(i=0;i<ctx->nb_streams;i++) { StreamInfo *stream = ctx->streams[i]->priv_data; id = stream->id; if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) { P_STD_max_mpeg_PS1 = stream->max_buffer_size; } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) { P_STD_max_mpeg_audio = stream->max_buffer_size; } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) { P_STD_max_video = stream->max_buffer_size; } } /* video */ put_bits(&pb, 8, 0xb9); /* stream ID */ put_bits(&pb, 2, 3); put_bits(&pb, 1, 1); put_bits(&pb, 13, P_STD_max_video / 1024); /* audio */ if (P_STD_max_mpeg_audio == 0) P_STD_max_mpeg_audio = 4096; put_bits(&pb, 8, 0xb8); /* stream ID */ put_bits(&pb, 2, 3); put_bits(&pb, 1, 0); put_bits(&pb, 13, P_STD_max_mpeg_audio / 128); /* private stream 1 */ put_bits(&pb, 8, 0xbd); /* stream ID */ put_bits(&pb, 2, 3); put_bits(&pb, 1, 0); put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128); /* private stream 2 */ put_bits(&pb, 8, 0xbf); /* stream ID */ put_bits(&pb, 2, 3); put_bits(&pb, 1, 1); put_bits(&pb, 13, 2); } else { /* audio stream info */ private_stream_coded = 0; for(i=0;i<ctx->nb_streams;i++) { StreamInfo *stream = ctx->streams[i]->priv_data; /* For VCDs, only include the stream info for the stream that the pack which contains this system belongs to. (see VCD standard p. IV-7) */ if ( !s->is_vcd || stream->id==only_for_stream_id || only_for_stream_id==0) { id = stream->id; if (id < 0xc0) { /* special case for private streams (AC-3 uses that) */ if (private_stream_coded) continue; private_stream_coded = 1; id = 0xbd; } put_bits(&pb, 8, id); /* stream ID */ put_bits(&pb, 2, 3); if (id < 0xe0) { /* audio */ put_bits(&pb, 1, 0); put_bits(&pb, 13, stream->max_buffer_size / 128); } else { /* video */ put_bits(&pb, 1, 1); put_bits(&pb, 13, stream->max_buffer_size / 1024); } } } } flush_put_bits(&pb); size = put_bits_ptr(&pb) - pb.buf; /* patch packet size */ buf[4] = (size - 6) >> 8; buf[5] = (size - 6) & 0xff; return size; }
static int encode_superframe(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { WMACodecContext *s = avctx->priv_data; int i, total_gain, ret; s->block_len_bits = s->frame_len_bits; // required by non variable block len s->block_len = 1 << s->block_len_bits; apply_window_and_mdct(avctx, frame); if (s->ms_stereo) { float a, b; int i; for (i = 0; i < s->block_len; i++) { a = s->coefs[0][i] * 0.5; b = s->coefs[1][i] * 0.5; s->coefs[0][i] = a + b; s->coefs[1][i] = a - b; } } if ((ret = ff_alloc_packet(avpkt, 2 * MAX_CODED_SUPERFRAME_SIZE))) { av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n"); return ret; } #if 1 total_gain = 128; for (i = 64; i; i >>= 1) { int error = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain - i); if (error < 0) total_gain -= i; } #else total_gain = 90; best = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain); for (i = 32; i; i >>= 1) { int scoreL = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain - i); int scoreR = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain + i); av_log(NULL, AV_LOG_ERROR, "%d %d %d (%d)\n", scoreL, best, scoreR, total_gain); if (scoreL < FFMIN(best, scoreR)) { best = scoreL; total_gain -= i; } else if (scoreR < best) { best = scoreR; total_gain += i; } } #endif /* 1 */ if ((i = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain)) >= 0) { av_log(avctx, AV_LOG_ERROR, "required frame size too large. please " "use a higher bit rate.\n"); return AVERROR(EINVAL); } assert((put_bits_count(&s->pb) & 7) == 0); while (i++) put_bits(&s->pb, 8, 'N'); flush_put_bits(&s->pb); if (frame->pts != AV_NOPTS_VALUE) avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding); avpkt->size = avctx->block_align; *got_packet_ptr = 1; return 0; }
static int put_pack_header(AVFormatContext *ctx, uint8_t *buf, int64_t timestamp) { MpegMuxContext *s = ctx->priv_data; PutBitContext pb; init_put_bits(&pb, buf, 128); put_bits32(&pb, PACK_START_CODE); if (s->is_mpeg2) { put_bits(&pb, 2, 0x1); } else { put_bits(&pb, 4, 0x2); } put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07)); put_bits(&pb, 1, 1); put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff)); put_bits(&pb, 1, 1); put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff)); put_bits(&pb, 1, 1); if (s->is_mpeg2) { /* clock extension */ put_bits(&pb, 9, 0); } put_bits(&pb, 1, 1); put_bits(&pb, 22, s->mux_rate); put_bits(&pb, 1, 1); if (s->is_mpeg2) { put_bits(&pb, 1, 1); put_bits(&pb, 5, 0x1f); /* reserved */ put_bits(&pb, 3, 0); /* stuffing length */ } flush_put_bits(&pb); return put_bits_ptr(&pb) - pb.buf; }
/* Nearly identical to wmv1 but that is just because we do not use the * useless M$ crap features. It is duplicated here in case someone wants * to add support for these crap features. */ void ff_wmv2_encode_mb(MpegEncContext * s, DCTELEM block[6][64], int motion_x, int motion_y) { Wmv2Context * const w= (Wmv2Context*)s; int cbp, coded_cbp, i; int pred_x, pred_y; uint8_t *coded_block; ff_msmpeg4_handle_slices(s); if (!s->mb_intra) { /* compute cbp */ cbp = 0; for (i = 0; i < 6; i++) { if (s->block_last_index[i] >= 0) cbp |= 1 << (5 - i); } put_bits(&s->pb, wmv2_inter_table[w->cbp_table_index][cbp + 64][1], wmv2_inter_table[w->cbp_table_index][cbp + 64][0]); /* motion vector */ h263_pred_motion(s, 0, 0, &pred_x, &pred_y); ff_msmpeg4_encode_motion(s, motion_x - pred_x, motion_y - pred_y); } else { /* compute cbp */ cbp = 0; coded_cbp = 0; for (i = 0; i < 6; i++) { int val, pred; val = (s->block_last_index[i] >= 1); cbp |= val << (5 - i); if (i < 4) { /* predict value for close blocks only for luma */ pred = ff_msmpeg4_coded_block_pred(s, i, &coded_block); *coded_block = val; val = val ^ pred; } coded_cbp |= val << (5 - i); } if (s->pict_type == FF_I_TYPE) { put_bits(&s->pb, ff_msmp4_mb_i_table[coded_cbp][1], ff_msmp4_mb_i_table[coded_cbp][0]); } else { put_bits(&s->pb, wmv2_inter_table[w->cbp_table_index][cbp][1], wmv2_inter_table[w->cbp_table_index][cbp][0]); } put_bits(&s->pb, 1, 0); /* no AC prediction yet */ if(s->inter_intra_pred){ s->h263_aic_dir=0; put_bits(&s->pb, table_inter_intra[s->h263_aic_dir][1], table_inter_intra[s->h263_aic_dir][0]); } } for (i = 0; i < 6; i++) { ff_msmpeg4_encode_block(s, block[i], i); } }
static int encode_bitstream(FlashSVContext *s, AVFrame *p, uint8_t *buf, int buf_size, int block_width, int block_height, uint8_t *previous_frame, int* I_frame) { PutBitContext pb; int h_blocks, v_blocks, h_part, v_part, i, j; int buf_pos, res; int pred_blocks = 0; init_put_bits(&pb, buf, buf_size*8); put_bits(&pb, 4, (block_width/16)-1); put_bits(&pb, 12, s->image_width); put_bits(&pb, 4, (block_height/16)-1); put_bits(&pb, 12, s->image_height); flush_put_bits(&pb); buf_pos=4; h_blocks = s->image_width / block_width; h_part = s->image_width % block_width; v_blocks = s->image_height / block_height; v_part = s->image_height % block_height; /* loop over all block columns */ for (j = 0; j < v_blocks + (v_part?1:0); j++) { int hp = j*block_height; // horiz position in frame int hs = (j<v_blocks)?block_height:v_part; // size of block /* loop over all block rows */ for (i = 0; i < h_blocks + (h_part?1:0); i++) { int wp = i*block_width; // vert position in frame int ws = (i<h_blocks)?block_width:h_part; // size of block int ret=Z_OK; uint8_t *ptr; ptr = buf+buf_pos; //copy the block to the temp buffer before compression (if it differs from the previous frame's block) res = copy_region_enc(p->data[0], s->tmpblock, s->image_height-(hp+hs+1), wp, hs, ws, p->linesize[0], previous_frame); if (res || *I_frame) { unsigned long zsize; zsize = 3*block_width*block_height; ret = compress2(ptr+2, &zsize, s->tmpblock, 3*ws*hs, 9); //ret = deflateReset(&(s->zstream)); if (ret != Z_OK) av_log(s->avctx, AV_LOG_ERROR, "error while compressing block %dx%d\n", i, j); bytestream_put_be16(&ptr,(unsigned int)zsize); buf_pos += zsize+2; //av_log(avctx, AV_LOG_ERROR, "buf_pos = %d\n", buf_pos); } else { pred_blocks++; bytestream_put_be16(&ptr,0); buf_pos += 2; } } } if (pred_blocks) *I_frame = 0; else *I_frame = 1; return buf_pos; }
/* put sequence header if needed */ static void mpeg1_encode_sequence_header(MpegEncContext *s) { unsigned int vbv_buffer_size; unsigned int fps, v; int i; uint64_t time_code; float best_aspect_error= 1E10; float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio); int constraint_parameter_flag; if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA) if (s->current_picture.key_frame) { AVRational framerate= ff_frame_rate_tab[s->frame_rate_index]; /* mpeg1 header repeated every gop */ put_header(s, SEQ_START_CODE); put_sbits(&s->pb, 12, s->width ); put_sbits(&s->pb, 12, s->height); for(i=1; i<15; i++){ float error= aspect_ratio; if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1) error-= 1.0/ff_mpeg1_aspect[i]; else error-= av_q2d(ff_mpeg2_aspect[i])*s->height/s->width; error= FFABS(error); if(error < best_aspect_error){ best_aspect_error= error; s->aspect_ratio_info= i; } } put_bits(&s->pb, 4, s->aspect_ratio_info); put_bits(&s->pb, 4, s->frame_rate_index); if(s->avctx->rc_max_rate){ v = (s->avctx->rc_max_rate + 399) / 400; if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO) v = 0x3ffff; }else{ v= 0x3FFFF; } if(s->avctx->rc_buffer_size) vbv_buffer_size = s->avctx->rc_buffer_size; else /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */ vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024; vbv_buffer_size= (vbv_buffer_size + 16383) / 16384; put_sbits(&s->pb, 18, v); put_bits(&s->pb, 1, 1); /* marker */ put_sbits(&s->pb, 10, vbv_buffer_size); constraint_parameter_flag= s->width <= 768 && s->height <= 576 && s->mb_width * s->mb_height <= 396 && s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 && framerate.num <= framerate.den*30 && s->avctx->me_range && s->avctx->me_range < 128 && vbv_buffer_size <= 20 && v <= 1856000/400 && s->codec_id == CODEC_ID_MPEG1VIDEO; put_bits(&s->pb, 1, constraint_parameter_flag); ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix); ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix); if(s->codec_id == CODEC_ID_MPEG2VIDEO){ put_header(s, EXT_START_CODE); put_bits(&s->pb, 4, 1); //seq ext put_bits(&s->pb, 1, s->avctx->profile == 0); //escx 1 for 4:2:2 profile */ put_bits(&s->pb, 3, s->avctx->profile); //profile put_bits(&s->pb, 4, s->avctx->level); //level put_bits(&s->pb, 1, s->progressive_sequence); put_bits(&s->pb, 2, s->chroma_format); put_bits(&s->pb, 2, s->width >>12); put_bits(&s->pb, 2, s->height>>12); put_bits(&s->pb, 12, v>>18); //bitrate ext put_bits(&s->pb, 1, 1); //marker put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext put_bits(&s->pb, 1, s->low_delay); put_bits(&s->pb, 2, 0); // frame_rate_ext_n put_bits(&s->pb, 5, 0); // frame_rate_ext_d }
static void put_header(MpegEncContext *s, int header) { align_put_bits(&s->pb); put_bits(&s->pb, 16, header>>16); put_bits(&s->pb, 16, header&0xFFFF); }