2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
35 #include "mpegvideo.h"
38 #include "h264_mvpred.h"
41 #include "rectangle.h"
43 #include "vdpau_internal.h"
44 #include "libavutil/avassert.h"
51 static const uint8_t rem6[QP_MAX_NUM+1]={
52 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
55 static const uint8_t div6[QP_MAX_NUM+1]={
56 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,
59 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
68 * Check if the top & left blocks are available if needed and
69 * change the dc mode so it only uses the available blocks.
71 int ff_h264_check_intra4x4_pred_mode(H264Context *h){
72 MpegEncContext * const s = &h->s;
73 static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
74 static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
77 if(!(h->top_samples_available&0x8000)){
79 int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
81 av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
84 h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
89 if((h->left_samples_available&0x8888)!=0x8888){
90 static const int mask[4]={0x8000,0x2000,0x80,0x20};
92 if(!(h->left_samples_available&mask[i])){
93 int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
95 av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
98 h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
105 } //FIXME cleanup like check_intra_pred_mode
107 static int check_intra_pred_mode(H264Context *h, int mode, int is_chroma){
108 MpegEncContext * const s = &h->s;
109 static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
110 static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
113 av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
117 if(!(h->top_samples_available&0x8000)){
120 av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
125 if((h->left_samples_available&0x8080) != 0x8080){
127 if(is_chroma && (h->left_samples_available&0x8080)){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
128 mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
131 av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
140 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
142 int ff_h264_check_intra16x16_pred_mode(H264Context *h, int mode)
144 return check_intra_pred_mode(h, mode, 0);
148 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
150 int ff_h264_check_intra_chroma_pred_mode(H264Context *h, int mode)
152 return check_intra_pred_mode(h, mode, 1);
156 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
161 // src[0]&0x80; //forbidden bit
162 h->nal_ref_idc= src[0]>>5;
163 h->nal_unit_type= src[0]&0x1F;
167 #if HAVE_FAST_UNALIGNED
170 for(i=0; i+1<length; i+=9){
171 if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
174 for(i=0; i+1<length; i+=5){
175 if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
178 if(i>0 && !src[i]) i--;
182 for(i=0; i+1<length; i+=2){
184 if(i>0 && src[i-1]==0) i--;
186 if(i+2<length && src[i+1]==0 && src[i+2]<=3){
188 /* startcode, so we must be past the end */
196 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
197 si=h->rbsp_buffer_size[bufidx];
198 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
199 dst= h->rbsp_buffer[bufidx];
200 if(si != h->rbsp_buffer_size[bufidx])
201 memset(dst + length, 0, FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
207 if(i>=length-1){ //no escaped 0
209 *consumed= length+1; //+1 for the header
210 if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
213 memcpy(dst, src, length);
218 //printf("decoding esc\n");
222 //remove escapes (very rare 1:2^22)
224 dst[di++]= src[si++];
225 dst[di++]= src[si++];
226 }else if(src[si]==0 && src[si+1]==0){
227 if(src[si+2]==3){ //escape
232 }else //next start code
236 dst[di++]= src[si++];
239 dst[di++]= src[si++];
242 memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
245 *consumed= si + 1;//+1 for the header
246 //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
251 * Identify the exact end of the bitstream
252 * @return the length of the trailing, or 0 if damaged
254 static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
258 tprintf(h->s.avctx, "rbsp trailing %X\n", v);
267 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
268 int y_offset, int list){
269 int raw_my= h->mv_cache[list][ scan8[n] ][1];
270 int filter_height= (raw_my&3) ? 2 : 0;
271 int full_my= (raw_my>>2) + y_offset;
272 int top = full_my - filter_height, bottom = full_my + height + filter_height;
274 return FFMAX(abs(top), bottom);
277 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
278 int y_offset, int list0, int list1, int *nrefs){
279 MpegEncContext * const s = &h->s;
282 y_offset += 16*(s->mb_y >> MB_FIELD);
285 int ref_n = h->ref_cache[0][ scan8[n] ];
286 Picture *ref= &h->ref_list[0][ref_n];
288 // Error resilience puts the current picture in the ref list.
289 // Don't try to wait on these as it will cause a deadlock.
290 // Fields can wait on each other, though.
291 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
292 (ref->f.reference & 3) != s->picture_structure) {
293 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
294 if (refs[0][ref_n] < 0) nrefs[0] += 1;
295 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
300 int ref_n = h->ref_cache[1][ scan8[n] ];
301 Picture *ref= &h->ref_list[1][ref_n];
303 if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
304 (ref->f.reference & 3) != s->picture_structure) {
305 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
306 if (refs[1][ref_n] < 0) nrefs[1] += 1;
307 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
313 * Wait until all reference frames are available for MC operations.
315 * @param h the H264 context
317 static void await_references(H264Context *h){
318 MpegEncContext * const s = &h->s;
319 const int mb_xy= h->mb_xy;
320 const int mb_type = s->current_picture.f.mb_type[mb_xy];
325 memset(refs, -1, sizeof(refs));
327 if(IS_16X16(mb_type)){
328 get_lowest_part_y(h, refs, 0, 16, 0,
329 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
330 }else if(IS_16X8(mb_type)){
331 get_lowest_part_y(h, refs, 0, 8, 0,
332 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
333 get_lowest_part_y(h, refs, 8, 8, 8,
334 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
335 }else if(IS_8X16(mb_type)){
336 get_lowest_part_y(h, refs, 0, 16, 0,
337 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
338 get_lowest_part_y(h, refs, 4, 16, 0,
339 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
343 assert(IS_8X8(mb_type));
346 const int sub_mb_type= h->sub_mb_type[i];
348 int y_offset= (i&2)<<2;
350 if(IS_SUB_8X8(sub_mb_type)){
351 get_lowest_part_y(h, refs, n , 8, y_offset,
352 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
353 }else if(IS_SUB_8X4(sub_mb_type)){
354 get_lowest_part_y(h, refs, n , 4, y_offset,
355 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
356 get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
357 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
358 }else if(IS_SUB_4X8(sub_mb_type)){
359 get_lowest_part_y(h, refs, n , 8, y_offset,
360 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
361 get_lowest_part_y(h, refs, n+1, 8, y_offset,
362 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
365 assert(IS_SUB_4X4(sub_mb_type));
367 int sub_y_offset= y_offset + 2*(j&2);
368 get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
369 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
375 for(list=h->list_count-1; list>=0; list--){
376 for(ref=0; ref<48 && nrefs[list]; ref++){
377 int row = refs[list][ref];
379 Picture *ref_pic = &h->ref_list[list][ref];
380 int ref_field = ref_pic->f.reference - 1;
381 int ref_field_picture = ref_pic->field_picture;
382 int pic_height = 16*s->mb_height >> ref_field_picture;
387 if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
388 ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
389 ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) , pic_height-1), 0);
390 }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
391 ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field , pic_height-1), 0);
392 }else if(FIELD_PICTURE){
393 ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
395 ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
404 * DCT transforms the 16 dc values.
405 * @param qp quantization parameter ??? FIXME
407 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
408 // const int qmul= dequant_coeff[qp][0];
410 int temp[16]; //FIXME check if this is a good idea
411 static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
412 static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
415 const int offset= y_offset[i];
416 const int z0= block[offset+stride*0] + block[offset+stride*4];
417 const int z1= block[offset+stride*0] - block[offset+stride*4];
418 const int z2= block[offset+stride*1] - block[offset+stride*5];
419 const int z3= block[offset+stride*1] + block[offset+stride*5];
428 const int offset= x_offset[i];
429 const int z0= temp[4*0+i] + temp[4*2+i];
430 const int z1= temp[4*0+i] - temp[4*2+i];
431 const int z2= temp[4*1+i] - temp[4*3+i];
432 const int z3= temp[4*1+i] + temp[4*3+i];
434 block[stride*0 +offset]= (z0 + z3)>>1;
435 block[stride*2 +offset]= (z1 + z2)>>1;
436 block[stride*8 +offset]= (z1 - z2)>>1;
437 block[stride*10+offset]= (z0 - z3)>>1;
446 static void chroma_dc_dct_c(DCTELEM *block){
447 const int stride= 16*2;
448 const int xStride= 16;
451 a= block[stride*0 + xStride*0];
452 b= block[stride*0 + xStride*1];
453 c= block[stride*1 + xStride*0];
454 d= block[stride*1 + xStride*1];
461 block[stride*0 + xStride*0]= (a+c);
462 block[stride*0 + xStride*1]= (e+b);
463 block[stride*1 + xStride*0]= (a-c);
464 block[stride*1 + xStride*1]= (e-b);
468 static av_always_inline void
469 mc_dir_part(H264Context *h, Picture *pic, int n, int square,
470 int height, int delta, int list,
471 uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
472 int src_x_offset, int src_y_offset,
473 qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op,
474 int pixel_shift, int chroma_idc)
476 MpegEncContext * const s = &h->s;
477 const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
478 int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
479 const int luma_xy= (mx&3) + ((my&3)<<2);
480 int offset = ((mx>>2) << pixel_shift) + (my>>2)*h->mb_linesize;
481 uint8_t * src_y = pic->f.data[0] + offset;
482 uint8_t * src_cb, * src_cr;
483 int extra_width= h->emu_edge_width;
484 int extra_height= h->emu_edge_height;
486 const int full_mx= mx>>2;
487 const int full_my= my>>2;
488 const int pic_width = 16*s->mb_width;
489 const int pic_height = 16*s->mb_height >> MB_FIELD;
492 if(mx&7) extra_width -= 3;
493 if(my&7) extra_height -= 3;
495 if( full_mx < 0-extra_width
496 || full_my < 0-extra_height
497 || full_mx + 16/*FIXME*/ > pic_width + extra_width
498 || full_my + 16/*FIXME*/ > pic_height + extra_height){
499 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
500 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
501 src_y= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
505 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
507 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
510 if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
512 if(chroma_idc == 3 /* yuv444 */){
513 src_cb = pic->f.data[1] + offset;
515 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
516 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
517 src_cb= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
519 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); //FIXME try variable height perhaps?
521 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
524 src_cr = pic->f.data[2] + offset;
526 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
527 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
528 src_cr= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
530 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); //FIXME try variable height perhaps?
532 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
537 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
538 if(chroma_idc == 1 /* yuv420 */ && MB_FIELD){
539 // chroma offset when predicting from a field of opposite parity
540 my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
541 emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
544 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
545 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
548 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
549 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
550 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
551 src_cb= s->edge_emu_buffer;
553 chroma_op(dest_cb, src_cb, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
554 mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
557 s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
558 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
559 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
560 src_cr= s->edge_emu_buffer;
562 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
563 mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
566 static av_always_inline void
567 mc_part_std(H264Context *h, int n, int square, int height, int delta,
568 uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
569 int x_offset, int y_offset,
570 qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
571 qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
572 int list0, int list1, int pixel_shift, int chroma_idc)
574 MpegEncContext * const s = &h->s;
575 qpel_mc_func *qpix_op= qpix_put;
576 h264_chroma_mc_func chroma_op= chroma_put;
578 dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
579 if (chroma_idc == 3 /* yuv444 */) {
580 dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
581 dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
582 } else if (chroma_idc == 2 /* yuv422 */) {
583 dest_cb += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
584 dest_cr += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
585 } else /* yuv420 */ {
586 dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
587 dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
589 x_offset += 8*s->mb_x;
590 y_offset += 8*(s->mb_y >> MB_FIELD);
593 Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
594 mc_dir_part(h, ref, n, square, height, delta, 0,
595 dest_y, dest_cb, dest_cr, x_offset, y_offset,
596 qpix_op, chroma_op, pixel_shift, chroma_idc);
599 chroma_op= chroma_avg;
603 Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
604 mc_dir_part(h, ref, n, square, height, delta, 1,
605 dest_y, dest_cb, dest_cr, x_offset, y_offset,
606 qpix_op, chroma_op, pixel_shift, chroma_idc);
610 static av_always_inline void
611 mc_part_weighted(H264Context *h, int n, int square, int height, int delta,
612 uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
613 int x_offset, int y_offset,
614 qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
615 h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
616 h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
617 int list0, int list1, int pixel_shift, int chroma_idc){
618 MpegEncContext * const s = &h->s;
621 dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
622 if (chroma_idc == 3 /* yuv444 */) {
623 chroma_height = height;
624 chroma_weight_avg = luma_weight_avg;
625 chroma_weight_op = luma_weight_op;
626 dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
627 dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
628 } else if (chroma_idc == 2 /* yuv422 */) {
629 chroma_height = height;
630 dest_cb += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
631 dest_cr += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
632 } else /* yuv420 */ {
633 chroma_height = height >> 1;
634 dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
635 dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
637 x_offset += 8*s->mb_x;
638 y_offset += 8*(s->mb_y >> MB_FIELD);
641 /* don't optimize for luma-only case, since B-frames usually
642 * use implicit weights => chroma too. */
643 uint8_t *tmp_cb = s->obmc_scratchpad;
644 uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
645 uint8_t *tmp_y = s->obmc_scratchpad + 16*h->mb_uvlinesize;
646 int refn0 = h->ref_cache[0][ scan8[n] ];
647 int refn1 = h->ref_cache[1][ scan8[n] ];
649 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
650 dest_y, dest_cb, dest_cr,
651 x_offset, y_offset, qpix_put, chroma_put,
652 pixel_shift, chroma_idc);
653 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
654 tmp_y, tmp_cb, tmp_cr,
655 x_offset, y_offset, qpix_put, chroma_put,
656 pixel_shift, chroma_idc);
658 if(h->use_weight == 2){
659 int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
660 int weight1 = 64 - weight0;
661 luma_weight_avg( dest_y, tmp_y, h-> mb_linesize,
662 height, 5, weight0, weight1, 0);
663 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
664 chroma_height, 5, weight0, weight1, 0);
665 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
666 chroma_height, 5, weight0, weight1, 0);
668 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height, h->luma_log2_weight_denom,
669 h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
670 h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
671 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
672 h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
673 h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
674 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
675 h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
676 h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
679 int list = list1 ? 1 : 0;
680 int refn = h->ref_cache[list][ scan8[n] ];
681 Picture *ref= &h->ref_list[list][refn];
682 mc_dir_part(h, ref, n, square, height, delta, list,
683 dest_y, dest_cb, dest_cr, x_offset, y_offset,
684 qpix_put, chroma_put, pixel_shift, chroma_idc);
686 luma_weight_op(dest_y, h->mb_linesize, height, h->luma_log2_weight_denom,
687 h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
688 if(h->use_weight_chroma){
689 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
690 h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
691 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
692 h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
697 static av_always_inline void
698 mc_part(H264Context *h, int n, int square, int height, int delta,
699 uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
700 int x_offset, int y_offset,
701 qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
702 qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
703 h264_weight_func *weight_op, h264_biweight_func *weight_avg,
704 int list0, int list1, int pixel_shift, int chroma_idc)
706 if((h->use_weight==2 && list0 && list1
707 && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
709 mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
710 x_offset, y_offset, qpix_put, chroma_put,
711 weight_op[0], weight_op[1], weight_avg[0],
712 weight_avg[1], list0, list1, pixel_shift, chroma_idc);
714 mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
715 x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
716 chroma_avg, list0, list1, pixel_shift, chroma_idc);
719 static av_always_inline void
720 prefetch_motion(H264Context *h, int list, int pixel_shift, int chroma_idc)
722 /* fetch pixels for estimated mv 4 macroblocks ahead
723 * optimized for 64byte cache lines */
724 MpegEncContext * const s = &h->s;
725 const int refn = h->ref_cache[list][scan8[0]];
727 const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
728 const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
729 uint8_t **src = h->ref_list[list][refn].f.data;
730 int off= (mx << pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize + (64 << pixel_shift);
731 s->dsp.prefetch(src[0]+off, s->linesize, 4);
732 if (chroma_idc == 3 /* yuv444 */) {
733 s->dsp.prefetch(src[1]+off, s->linesize, 4);
734 s->dsp.prefetch(src[2]+off, s->linesize, 4);
736 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
737 s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
742 static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
743 qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
744 qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
745 h264_weight_func *weight_op, h264_biweight_func *weight_avg,
746 int pixel_shift, int chroma_idc)
748 MpegEncContext * const s = &h->s;
749 const int mb_xy= h->mb_xy;
750 const int mb_type = s->current_picture.f.mb_type[mb_xy];
752 assert(IS_INTER(mb_type));
754 if(HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
756 prefetch_motion(h, 0, pixel_shift, chroma_idc);
758 if(IS_16X16(mb_type)){
759 mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
760 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
761 weight_op, weight_avg,
762 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
763 pixel_shift, chroma_idc);
764 }else if(IS_16X8(mb_type)){
765 mc_part(h, 0, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
766 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
767 weight_op, weight_avg,
768 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
769 pixel_shift, chroma_idc);
770 mc_part(h, 8, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
771 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
772 weight_op, weight_avg,
773 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
774 pixel_shift, chroma_idc);
775 }else if(IS_8X16(mb_type)){
776 mc_part(h, 0, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
777 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
778 &weight_op[1], &weight_avg[1],
779 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
780 pixel_shift, chroma_idc);
781 mc_part(h, 4, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
782 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
783 &weight_op[1], &weight_avg[1],
784 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
785 pixel_shift, chroma_idc);
789 assert(IS_8X8(mb_type));
792 const int sub_mb_type= h->sub_mb_type[i];
794 int x_offset= (i&1)<<2;
795 int y_offset= (i&2)<<1;
797 if(IS_SUB_8X8(sub_mb_type)){
798 mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
799 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
800 &weight_op[1], &weight_avg[1],
801 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
802 pixel_shift, chroma_idc);
803 }else if(IS_SUB_8X4(sub_mb_type)){
804 mc_part(h, n , 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset,
805 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
806 &weight_op[1], &weight_avg[1],
807 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
808 pixel_shift, chroma_idc);
809 mc_part(h, n+2, 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
810 qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
811 &weight_op[1], &weight_avg[1],
812 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
813 pixel_shift, chroma_idc);
814 }else if(IS_SUB_4X8(sub_mb_type)){
815 mc_part(h, n , 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
816 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
817 &weight_op[2], &weight_avg[2],
818 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
819 pixel_shift, chroma_idc);
820 mc_part(h, n+1, 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
821 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
822 &weight_op[2], &weight_avg[2],
823 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
824 pixel_shift, chroma_idc);
827 assert(IS_SUB_4X4(sub_mb_type));
829 int sub_x_offset= x_offset + 2*(j&1);
830 int sub_y_offset= y_offset + (j&2);
831 mc_part(h, n+j, 1, 4, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
832 qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
833 &weight_op[2], &weight_avg[2],
834 IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
835 pixel_shift, chroma_idc);
841 prefetch_motion(h, 1, pixel_shift, chroma_idc);
844 static av_always_inline void
845 hl_motion_420(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
846 qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
847 qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
848 h264_weight_func *weight_op, h264_biweight_func *weight_avg,
851 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
852 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 1);
855 static av_always_inline void
856 hl_motion_422(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
857 qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
858 qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
859 h264_weight_func *weight_op, h264_biweight_func *weight_avg,
862 hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
863 qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 2);
866 static void free_tables(H264Context *h, int free_rbsp){
870 av_freep(&h->intra4x4_pred_mode);
871 av_freep(&h->chroma_pred_mode_table);
872 av_freep(&h->cbp_table);
873 av_freep(&h->mvd_table[0]);
874 av_freep(&h->mvd_table[1]);
875 av_freep(&h->direct_table);
876 av_freep(&h->non_zero_count);
877 av_freep(&h->slice_table_base);
878 h->slice_table= NULL;
879 av_freep(&h->list_counts);
881 av_freep(&h->mb2b_xy);
882 av_freep(&h->mb2br_xy);
884 for(i = 0; i < MAX_THREADS; i++) {
885 hx = h->thread_context[i];
887 av_freep(&hx->top_borders[1]);
888 av_freep(&hx->top_borders[0]);
889 av_freep(&hx->s.obmc_scratchpad);
891 av_freep(&hx->rbsp_buffer[1]);
892 av_freep(&hx->rbsp_buffer[0]);
893 hx->rbsp_buffer_size[0] = 0;
894 hx->rbsp_buffer_size[1] = 0;
896 if (i) av_freep(&h->thread_context[i]);
900 static void init_dequant8_coeff_table(H264Context *h){
902 const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
905 h->dequant8_coeff[i] = h->dequant8_buffer[i];
907 if(!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64*sizeof(uint8_t))){
908 h->dequant8_coeff[i] = h->dequant8_buffer[j];
915 for(q=0; q<max_qp+1; q++){
919 h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
920 ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
921 h->pps.scaling_matrix8[i][x]) << shift;
926 static void init_dequant4_coeff_table(H264Context *h){
928 const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
930 h->dequant4_coeff[i] = h->dequant4_buffer[i];
932 if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
933 h->dequant4_coeff[i] = h->dequant4_buffer[j];
940 for(q=0; q<max_qp+1; q++){
941 int shift = div6[q] + 2;
944 h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
945 ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
946 h->pps.scaling_matrix4[i][x]) << shift;
951 static void init_dequant_tables(H264Context *h){
953 init_dequant4_coeff_table(h);
954 if(h->pps.transform_8x8_mode)
955 init_dequant8_coeff_table(h);
956 if(h->sps.transform_bypass){
959 h->dequant4_coeff[i][0][x] = 1<<6;
960 if(h->pps.transform_8x8_mode)
963 h->dequant8_coeff[i][0][x] = 1<<6;
968 int ff_h264_alloc_tables(H264Context *h){
969 MpegEncContext * const s = &h->s;
970 const int big_mb_num= s->mb_stride * (s->mb_height+1);
971 const int row_mb_num= 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
974 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8 * sizeof(uint8_t), fail)
976 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count , big_mb_num * 48 * sizeof(uint8_t), fail)
977 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
978 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
980 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
981 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
982 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
983 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
984 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
986 memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base));
987 h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
989 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy , big_mb_num * sizeof(uint32_t), fail);
990 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
991 for(y=0; y<s->mb_height; y++){
992 for(x=0; x<s->mb_width; x++){
993 const int mb_xy= x + y*s->mb_stride;
994 const int b_xy = 4*x + 4*y*h->b_stride;
996 h->mb2b_xy [mb_xy]= b_xy;
997 h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
1001 s->obmc_scratchpad = NULL;
1003 if(!h->dequant4_coeff[0])
1004 init_dequant_tables(h);
1013 * Mimic alloc_tables(), but for every context thread.
1015 static void clone_tables(H264Context *dst, H264Context *src, int i){
1016 MpegEncContext * const s = &src->s;
1017 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
1018 dst->non_zero_count = src->non_zero_count;
1019 dst->slice_table = src->slice_table;
1020 dst->cbp_table = src->cbp_table;
1021 dst->mb2b_xy = src->mb2b_xy;
1022 dst->mb2br_xy = src->mb2br_xy;
1023 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1024 dst->mvd_table[0] = src->mvd_table[0] + i*8*2*s->mb_stride;
1025 dst->mvd_table[1] = src->mvd_table[1] + i*8*2*s->mb_stride;
1026 dst->direct_table = src->direct_table;
1027 dst->list_counts = src->list_counts;
1029 dst->s.obmc_scratchpad = NULL;
1030 ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma, src->sps.chroma_format_idc);
1035 * Allocate buffers which are not shared amongst multiple threads.
1037 static int context_init(H264Context *h){
1038 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
1039 FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
1041 h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
1042 h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
1046 return -1; // free_tables will clean up for us
1049 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
1051 static av_cold void common_init(H264Context *h){
1052 MpegEncContext * const s = &h->s;
1054 s->width = s->avctx->width;
1055 s->height = s->avctx->height;
1056 s->codec_id= s->avctx->codec->id;
1058 s->avctx->bits_per_raw_sample = 8;
1059 h->cur_chroma_format_idc = 1;
1061 ff_h264dsp_init(&h->h264dsp,
1062 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
1063 ff_h264_pred_init(&h->hpc, s->codec_id,
1064 s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
1066 h->dequant_coeff_pps= -1;
1067 s->unrestricted_mv=1;
1069 s->dsp.dct_bits = 16;
1070 dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
1072 memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
1073 memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
1076 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1078 AVCodecContext *avctx = h->s.avctx;
1080 if(!buf || size <= 0)
1084 int i, cnt, nalsize;
1085 const unsigned char *p = buf;
1090 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1093 /* sps and pps in the avcC always have length coded with 2 bytes,
1094 so put a fake nal_length_size = 2 while parsing them */
1095 h->nal_length_size = 2;
1096 // Decode sps from avcC
1097 cnt = *(p+5) & 0x1f; // Number of sps
1099 for (i = 0; i < cnt; i++) {
1100 nalsize = AV_RB16(p) + 2;
1101 if(nalsize > size - (p-buf))
1103 if(decode_nal_units(h, p, nalsize) < 0) {
1104 av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
1109 // Decode pps from avcC
1110 cnt = *(p++); // Number of pps
1111 for (i = 0; i < cnt; i++) {
1112 nalsize = AV_RB16(p) + 2;
1113 if(nalsize > size - (p-buf))
1115 if (decode_nal_units(h, p, nalsize) < 0) {
1116 av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
1121 // Now store right nal length size, that will be use to parse all other nals
1122 h->nal_length_size = (buf[4] & 0x03) + 1;
1125 if(decode_nal_units(h, buf, size) < 0)
1131 av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1132 H264Context *h= avctx->priv_data;
1133 MpegEncContext * const s = &h->s;
1136 MPV_decode_defaults(s);
1141 s->out_format = FMT_H264;
1142 s->workaround_bugs= avctx->workaround_bugs;
1145 // s->decode_mb= ff_h263_decode_mb;
1146 s->quarter_sample = 1;
1147 if(!avctx->has_b_frames)
1150 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1152 ff_h264_decode_init_vlc();
1155 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1157 h->thread_context[0] = h;
1158 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1159 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1160 h->last_pocs[i] = INT_MIN;
1161 h->prev_poc_msb= 1<<16;
1162 h->prev_frame_num= -1;
1164 ff_h264_reset_sei(h);
1165 if(avctx->codec_id == CODEC_ID_H264){
1166 if(avctx->ticks_per_frame == 1){
1167 s->avctx->time_base.den *=2;
1169 avctx->ticks_per_frame = 2;
1172 if(avctx->extradata_size > 0 && avctx->extradata &&
1173 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size))
1176 if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1177 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1184 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
1185 static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1189 for (i=0; i<count; i++){
1190 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1191 IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
1193 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1197 static void copy_parameter_set(void **to, void **from, int count, int size)
1201 for (i=0; i<count; i++){
1202 if (to[i] && !from[i]) av_freep(&to[i]);
1203 else if (from[i] && !to[i]) to[i] = av_malloc(size);
1205 if (from[i]) memcpy(to[i], from[i], size);
1209 static int decode_init_thread_copy(AVCodecContext *avctx){
1210 H264Context *h= avctx->priv_data;
1212 if (!avctx->internal->is_copy)
1214 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1215 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1220 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1221 static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1222 H264Context *h= dst->priv_data, *h1= src->priv_data;
1223 MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1224 int inited = s->context_initialized, err;
1227 if(dst == src || !s1->context_initialized) return 0;
1229 err = ff_mpeg_update_thread_context(dst, src);
1232 //FIXME handle width/height changing
1234 for(i = 0; i < MAX_SPS_COUNT; i++)
1235 av_freep(h->sps_buffers + i);
1237 for(i = 0; i < MAX_PPS_COUNT; i++)
1238 av_freep(h->pps_buffers + i);
1240 memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1241 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1242 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1243 if (ff_h264_alloc_tables(h) < 0) {
1244 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1245 return AVERROR(ENOMEM);
1250 h->rbsp_buffer[i] = NULL;
1251 h->rbsp_buffer_size[i] = 0;
1254 h->thread_context[0] = h;
1256 // frame_start may not be called for the next thread (if it's decoding a bottom field)
1257 // so this has to be allocated here
1258 h->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1260 s->dsp.clear_blocks(h->mb);
1261 s->dsp.clear_blocks(h->mb+(24*16<<h->pixel_shift));
1264 //extradata/NAL handling
1265 h->is_avc = h1->is_avc;
1268 copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1270 copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1273 //Dequantization matrices
1274 //FIXME these are big - can they be only copied when PPS changes?
1275 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1278 h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1281 h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1283 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1286 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1289 copy_fields(h, h1, ref_count, list_count);
1290 copy_fields(h, h1, ref_list, intra_gb);
1291 copy_fields(h, h1, short_ref, cabac_init_idc);
1293 copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
1294 copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
1295 copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1297 h->last_slice_type = h1->last_slice_type;
1300 if(!s->current_picture_ptr) return 0;
1303 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1304 h->prev_poc_msb = h->poc_msb;
1305 h->prev_poc_lsb = h->poc_lsb;
1307 h->prev_frame_num_offset= h->frame_num_offset;
1308 h->prev_frame_num = h->frame_num;
1309 h->outputed_poc = h->next_outputed_poc;
1314 int ff_h264_frame_start(H264Context *h){
1315 MpegEncContext * const s = &h->s;
1317 const int pixel_shift = h->pixel_shift;
1318 int thread_count = (s->avctx->active_thread_type & FF_THREAD_SLICE) ? s->avctx->thread_count : 1;
1320 if(MPV_frame_start(s, s->avctx) < 0)
1322 ff_er_frame_start(s);
1324 * MPV_frame_start uses pict_type to derive key_frame.
1325 * This is incorrect for H.264; IDR markings must be used.
1326 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1327 * See decode_nal_units().
1329 s->current_picture_ptr->f.key_frame = 0;
1330 s->current_picture_ptr->mmco_reset= 0;
1332 assert(s->linesize && s->uvlinesize);
1334 for(i=0; i<16; i++){
1335 h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1336 h->block_offset[48+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1338 for(i=0; i<16; i++){
1339 h->block_offset[16+i]=
1340 h->block_offset[32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1341 h->block_offset[48+16+i]=
1342 h->block_offset[48+32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1345 /* can't be in alloc_tables because linesize isn't known there.
1346 * FIXME: redo bipred weight to not require extra buffer? */
1347 for(i = 0; i < thread_count; i++)
1348 if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1349 h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1351 /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
1352 memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1354 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.f.reference /*|| h->contains_intra*/ || 1;
1356 // We mark the current picture as non-reference after allocating it, so
1357 // that if we break out due to an error it can be released automatically
1358 // in the next MPV_frame_start().
1359 // SVQ3 as well as most other codecs have only last/next/current and thus
1360 // get released even with set reference, besides SVQ3 and others do not
1361 // mark frames as reference later "naturally".
1362 if(s->codec_id != CODEC_ID_SVQ3)
1363 s->current_picture_ptr->f.reference = 0;
1365 s->current_picture_ptr->field_poc[0]=
1366 s->current_picture_ptr->field_poc[1]= INT_MAX;
1368 h->next_output_pic = NULL;
1370 assert(s->current_picture_ptr->long_ref==0);
1376 * Run setup operations that must be run after slice header decoding.
1377 * This includes finding the next displayed frame.
1379 * @param h h264 master context
1380 * @param setup_finished enough NALs have been read that we can call
1381 * ff_thread_finish_setup()
1383 static void decode_postinit(H264Context *h, int setup_finished){
1384 MpegEncContext * const s = &h->s;
1385 Picture *out = s->current_picture_ptr;
1386 Picture *cur = s->current_picture_ptr;
1387 int i, pics, out_of_order, out_idx;
1389 s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1390 s->current_picture_ptr->f.pict_type = s->pict_type;
1392 if (h->next_output_pic) return;
1394 if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1395 //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
1396 //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
1397 //to find this yet, so we assume the worst for now.
1398 //if (setup_finished)
1399 // ff_thread_finish_setup(s->avctx);
1403 cur->f.interlaced_frame = 0;
1404 cur->f.repeat_pict = 0;
1406 /* Signal interlacing information externally. */
1407 /* Prioritize picture timing SEI information over used decoding process if it exists. */
1409 if(h->sps.pic_struct_present_flag){
1410 switch (h->sei_pic_struct)
1412 case SEI_PIC_STRUCT_FRAME:
1414 case SEI_PIC_STRUCT_TOP_FIELD:
1415 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1416 cur->f.interlaced_frame = 1;
1418 case SEI_PIC_STRUCT_TOP_BOTTOM:
1419 case SEI_PIC_STRUCT_BOTTOM_TOP:
1420 if (FIELD_OR_MBAFF_PICTURE)
1421 cur->f.interlaced_frame = 1;
1423 // try to flag soft telecine progressive
1424 cur->f.interlaced_frame = h->prev_interlaced_frame;
1426 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1427 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1428 // Signal the possibility of telecined film externally (pic_struct 5,6)
1429 // From these hints, let the applications decide if they apply deinterlacing.
1430 cur->f.repeat_pict = 1;
1432 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1433 // Force progressive here, as doubling interlaced frame is a bad idea.
1434 cur->f.repeat_pict = 2;
1436 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1437 cur->f.repeat_pict = 4;
1441 if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1442 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1444 /* Derive interlacing flag from used decoding process. */
1445 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1447 h->prev_interlaced_frame = cur->f.interlaced_frame;
1449 if (cur->field_poc[0] != cur->field_poc[1]){
1450 /* Derive top_field_first from field pocs. */
1451 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1453 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1454 /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1455 if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1456 || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1457 cur->f.top_field_first = 1;
1459 cur->f.top_field_first = 0;
1461 /* Most likely progressive */
1462 cur->f.top_field_first = 0;
1466 cur->mmco_reset = h->mmco_reset;
1468 //FIXME do something with unavailable reference frames
1470 /* Sort B-frames into display order */
1472 if(h->sps.bitstream_restriction_flag
1473 && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1474 s->avctx->has_b_frames = h->sps.num_reorder_frames;
1478 if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1479 && !h->sps.bitstream_restriction_flag){
1480 s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1484 for (i = 0; 1; i++) {
1485 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1487 h->last_pocs[i-1] = cur->poc;
1490 h->last_pocs[i-1]= h->last_pocs[i];
1493 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1494 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1495 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
1496 out_of_order = FFMAX(out_of_order, 1);
1497 if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1498 av_log(s->avctx, AV_LOG_WARNING, "Increasing reorder buffer to %d\n", out_of_order);
1499 s->avctx->has_b_frames = out_of_order;
1504 while(h->delayed_pic[pics]) pics++;
1506 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1508 h->delayed_pic[pics++] = cur;
1509 if (cur->f.reference == 0)
1510 cur->f.reference = DELAYED_PIC_REF;
1512 out = h->delayed_pic[0];
1514 for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1515 if(h->delayed_pic[i]->poc < out->poc){
1516 out = h->delayed_pic[i];
1519 if (s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1520 h->next_outputed_poc= INT_MIN;
1521 out_of_order = out->poc < h->next_outputed_poc;
1523 if(out_of_order || pics > s->avctx->has_b_frames){
1524 out->f.reference &= ~DELAYED_PIC_REF;
1525 out->owner2 = s; // for frame threading, the owner must be the second field's thread
1526 // or else the first thread can release the picture and reuse it unsafely
1527 for(i=out_idx; h->delayed_pic[i]; i++)
1528 h->delayed_pic[i] = h->delayed_pic[i+1];
1530 if(!out_of_order && pics > s->avctx->has_b_frames){
1531 h->next_output_pic = out;
1532 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1533 h->next_outputed_poc = INT_MIN;
1535 h->next_outputed_poc = out->poc;
1537 av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1540 if (h->next_output_pic && h->next_output_pic->sync) {
1545 ff_thread_finish_setup(s->avctx);
1548 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1549 uint8_t *src_cb, uint8_t *src_cr,
1550 int linesize, int uvlinesize, int simple)
1552 MpegEncContext * const s = &h->s;
1553 uint8_t *top_border;
1555 const int pixel_shift = h->pixel_shift;
1556 int chroma444 = CHROMA444;
1557 int chroma422 = CHROMA422;
1560 src_cb -= uvlinesize;
1561 src_cr -= uvlinesize;
1563 if(!simple && FRAME_MBAFF){
1566 top_border = h->top_borders[0][s->mb_x];
1567 AV_COPY128(top_border, src_y + 15*linesize);
1569 AV_COPY128(top_border+16, src_y+15*linesize+16);
1570 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1573 AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
1574 AV_COPY128(top_border+48, src_cb + 15*uvlinesize+16);
1575 AV_COPY128(top_border+64, src_cr + 15*uvlinesize);
1576 AV_COPY128(top_border+80, src_cr + 15*uvlinesize+16);
1578 AV_COPY128(top_border+16, src_cb + 15*uvlinesize);
1579 AV_COPY128(top_border+32, src_cr + 15*uvlinesize);
1581 } else if(chroma422){
1583 AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
1584 AV_COPY128(top_border+48, src_cr + 15*uvlinesize);
1586 AV_COPY64(top_border+16, src_cb + 15*uvlinesize);
1587 AV_COPY64(top_border+24, src_cr + 15*uvlinesize);
1591 AV_COPY128(top_border+32, src_cb+7*uvlinesize);
1592 AV_COPY128(top_border+48, src_cr+7*uvlinesize);
1594 AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1595 AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1606 top_border = h->top_borders[top_idx][s->mb_x];
1607 // There are two lines saved, the line above the the top macroblock of a pair,
1608 // and the line above the bottom macroblock
1609 AV_COPY128(top_border, src_y + 16*linesize);
1611 AV_COPY128(top_border+16, src_y+16*linesize+16);
1613 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1616 AV_COPY128(top_border+32, src_cb + 16*linesize);
1617 AV_COPY128(top_border+48, src_cb + 16*linesize+16);
1618 AV_COPY128(top_border+64, src_cr + 16*linesize);
1619 AV_COPY128(top_border+80, src_cr + 16*linesize+16);
1621 AV_COPY128(top_border+16, src_cb + 16*linesize);
1622 AV_COPY128(top_border+32, src_cr + 16*linesize);
1624 } else if(chroma422) {
1626 AV_COPY128(top_border+32, src_cb+16*uvlinesize);
1627 AV_COPY128(top_border+48, src_cr+16*uvlinesize);
1629 AV_COPY64(top_border+16, src_cb+16*uvlinesize);
1630 AV_COPY64(top_border+24, src_cr+16*uvlinesize);
1634 AV_COPY128(top_border+32, src_cb+8*uvlinesize);
1635 AV_COPY128(top_border+48, src_cr+8*uvlinesize);
1637 AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1638 AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1644 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1645 uint8_t *src_cb, uint8_t *src_cr,
1646 int linesize, int uvlinesize,
1647 int xchg, int chroma444,
1648 int simple, int pixel_shift){
1649 MpegEncContext * const s = &h->s;
1650 int deblock_topleft;
1653 uint8_t *top_border_m1;
1654 uint8_t *top_border;
1656 if(!simple && FRAME_MBAFF){
1661 top_idx = MB_MBAFF ? 0 : 1;
1665 if(h->deblocking_filter == 2) {
1666 deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1667 deblock_top = h->top_type;
1669 deblock_topleft = (s->mb_x > 0);
1670 deblock_top = (s->mb_y > !!MB_FIELD);
1673 src_y -= linesize + 1 + pixel_shift;
1674 src_cb -= uvlinesize + 1 + pixel_shift;
1675 src_cr -= uvlinesize + 1 + pixel_shift;
1677 top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1678 top_border = h->top_borders[top_idx][s->mb_x];
1680 #define XCHG(a,b,xchg)\
1683 AV_SWAP64(b+0,a+0);\
1684 AV_SWAP64(b+8,a+8);\
1689 if (xchg) AV_SWAP64(b,a);\
1690 else AV_COPY64(b,a);
1693 if(deblock_topleft){
1694 XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
1696 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1697 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1698 if(s->mb_x+1 < s->mb_width){
1699 XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
1702 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1704 if(deblock_topleft){
1705 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1706 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1708 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1709 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1710 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1711 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1712 if(s->mb_x+1 < s->mb_width){
1713 XCHG(h->top_borders[top_idx][s->mb_x+1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1714 XCHG(h->top_borders[top_idx][s->mb_x+1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1718 if(deblock_topleft){
1719 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1720 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1722 XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
1723 XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
1729 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
1730 if (high_bit_depth) {
1731 return AV_RN32A(((int32_t*)mb) + index);
1733 return AV_RN16A(mb + index);
1736 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
1737 if (high_bit_depth) {
1738 AV_WN32A(((int32_t*)mb) + index, value);
1740 AV_WN16A(mb + index, value);
1743 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1744 int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1746 MpegEncContext * const s = &h->s;
1747 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1748 void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1750 int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];
1751 block_offset += 16*p;
1752 if(IS_INTRA4x4(mb_type)){
1753 if(simple || !s->encoding){
1754 if(IS_8x8DCT(mb_type)){
1755 if(transform_bypass){
1757 idct_add = s->dsp.add_pixels8;
1759 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1760 idct_add = h->h264dsp.h264_idct8_add;
1762 for(i=0; i<16; i+=4){
1763 uint8_t * const ptr= dest_y + block_offset[i];
1764 const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1765 if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1766 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1768 const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1769 h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1770 (h->topright_samples_available<<i)&0x4000, linesize);
1772 if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1773 idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1775 idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1780 if(transform_bypass){
1782 idct_add = s->dsp.add_pixels4;
1784 idct_dc_add = h->h264dsp.h264_idct_dc_add;
1785 idct_add = h->h264dsp.h264_idct_add;
1787 for(i=0; i<16; i++){
1788 uint8_t * const ptr= dest_y + block_offset[i];
1789 const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1791 if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1792 h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1797 if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1798 const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1799 assert(s->mb_y || linesize <= block_offset[i]);
1800 if(!topright_avail){
1802 tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1803 topright= (uint8_t*) &tr_high;
1805 tr= ptr[3 - linesize]*0x01010101u;
1806 topright= (uint8_t*) &tr;
1809 topright= ptr + (4 << pixel_shift) - linesize;
1813 h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1814 nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1817 if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1818 idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1820 idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1821 }else if(CONFIG_SVQ3_DECODER)
1822 ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
1829 h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1831 if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){
1832 if(!transform_bypass)
1833 h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);
1835 static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1836 8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1837 for(i = 0; i < 16; i++)
1838 dctcoef_set(h->mb+(p*256 << pixel_shift), pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
1841 }else if(CONFIG_SVQ3_DECODER)
1842 ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
1846 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1847 int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1849 MpegEncContext * const s = &h->s;
1850 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1852 block_offset += 16*p;
1853 if(!IS_INTRA4x4(mb_type)){
1855 if(IS_INTRA16x16(mb_type)){
1856 if(transform_bypass){
1857 if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1858 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize);
1860 for(i=0; i<16; i++){
1861 if(h->non_zero_count_cache[ scan8[i+p*16] ] || dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1862 s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1866 h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1868 }else if(h->cbp&15){
1869 if(transform_bypass){
1870 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1871 idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1872 for(i=0; i<16; i+=di){
1873 if(h->non_zero_count_cache[ scan8[i+p*16] ]){
1874 idct_add(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1878 if(IS_8x8DCT(mb_type)){
1879 h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1881 h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1885 }else if(CONFIG_SVQ3_DECODER) {
1886 for(i=0; i<16; i++){
1887 if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
1888 uint8_t * const ptr= dest_y + block_offset[i];
1889 ff_svq3_add_idct_c(ptr, h->mb + i*16 + p*256, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1896 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift)
1898 MpegEncContext * const s = &h->s;
1899 const int mb_x= s->mb_x;
1900 const int mb_y= s->mb_y;
1901 const int mb_xy= h->mb_xy;
1902 const int mb_type = s->current_picture.f.mb_type[mb_xy];
1903 uint8_t *dest_y, *dest_cb, *dest_cr;
1904 int linesize, uvlinesize /*dct_offset*/;
1906 int *block_offset = &h->block_offset[0];
1907 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1908 /* is_h264 should always be true if SVQ3 is disabled. */
1909 const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1910 void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1911 const int block_h = 16 >> s->chroma_y_shift;
1912 const int chroma422 = CHROMA422;
1914 dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
1915 dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
1916 dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
1918 s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
1919 s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
1921 h->list_counts[mb_xy]= h->list_count;
1923 if (!simple && MB_FIELD) {
1924 linesize = h->mb_linesize = s->linesize * 2;
1925 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1926 block_offset = &h->block_offset[48];
1927 if(mb_y&1){ //FIXME move out of this function?
1928 dest_y -= s->linesize*15;
1929 dest_cb-= s->uvlinesize * (block_h - 1);
1930 dest_cr-= s->uvlinesize * (block_h - 1);
1934 for(list=0; list<h->list_count; list++){
1935 if(!USES_LIST(mb_type, list))
1937 if(IS_16X16(mb_type)){
1938 int8_t *ref = &h->ref_cache[list][scan8[0]];
1939 fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1941 for(i=0; i<16; i+=4){
1942 int ref = h->ref_cache[list][scan8[i]];
1944 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1950 linesize = h->mb_linesize = s->linesize;
1951 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1952 // dct_offset = s->linesize * 16;
1955 if (!simple && IS_INTRA_PCM(mb_type)) {
1956 const int bit_depth = h->sps.bit_depth_luma;
1960 init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1962 for (i = 0; i < 16; i++) {
1963 uint16_t *tmp_y = (uint16_t*)(dest_y + i*linesize);
1964 for (j = 0; j < 16; j++)
1965 tmp_y[j] = get_bits(&gb, bit_depth);
1967 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1968 if (!h->sps.chroma_format_idc) {
1969 for (i = 0; i < block_h; i++) {
1970 uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1971 uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1972 for (j = 0; j < 8; j++) {
1973 tmp_cb[j] = tmp_cr[j] = 1 << (bit_depth - 1);
1977 for (i = 0; i < block_h; i++) {
1978 uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1979 for (j = 0; j < 8; j++)
1980 tmp_cb[j] = get_bits(&gb, bit_depth);
1982 for (i = 0; i < block_h; i++) {
1983 uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1984 for (j = 0; j < 8; j++)
1985 tmp_cr[j] = get_bits(&gb, bit_depth);
1990 for (i=0; i<16; i++) {
1991 memcpy(dest_y + i* linesize, h->mb + i*8, 16);
1993 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1994 if (!h->sps.chroma_format_idc) {
1995 for (i=0; i<8; i++) {
1996 memset(dest_cb + i*uvlinesize, 1 << (bit_depth - 1), 8);
1997 memset(dest_cr + i*uvlinesize, 1 << (bit_depth - 1), 8);
2000 for (i=0; i<block_h; i++) {
2001 memcpy(dest_cb + i*uvlinesize, h->mb + 128 + i*4, 8);
2002 memcpy(dest_cr + i*uvlinesize, h->mb + 160 + i*4, 8);
2008 if(IS_INTRA(mb_type)){
2009 if(h->deblocking_filter)
2010 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, 0, simple, pixel_shift);
2012 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2013 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2014 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2017 hl_decode_mb_predict_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
2019 if(h->deblocking_filter)
2020 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, 0, simple, pixel_shift);
2023 hl_motion_422(h, dest_y, dest_cb, dest_cr,
2024 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2025 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2026 h->h264dsp.weight_h264_pixels_tab,
2027 h->h264dsp.biweight_h264_pixels_tab,
2030 hl_motion_420(h, dest_y, dest_cb, dest_cr,
2031 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2032 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2033 h->h264dsp.weight_h264_pixels_tab,
2034 h->h264dsp.biweight_h264_pixels_tab,
2039 hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
2041 if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
2042 uint8_t *dest[2] = {dest_cb, dest_cr};
2043 if(transform_bypass){
2044 if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
2045 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16*1 << pixel_shift), uvlinesize);
2046 h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 32, h->mb + (16*16*2 << pixel_shift), uvlinesize);
2048 idct_add = s->dsp.add_pixels4;
2050 for(i=j*16; i<j*16+4; i++){
2051 if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
2052 idct_add (dest[j-1] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
2055 for(i=j*16+4; i<j*16+8; i++){
2056 if(h->non_zero_count_cache[ scan8[i+4] ] || dctcoef_get(h->mb, pixel_shift, i*16))
2057 idct_add (dest[j-1] + block_offset[i+4], h->mb + (i*16 << pixel_shift), uvlinesize);
2066 qp[0] = h->chroma_qp[0] + 3;
2067 qp[1] = h->chroma_qp[1] + 3;
2069 qp[0] = h->chroma_qp[0];
2070 qp[1] = h->chroma_qp[1];
2072 if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
2073 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*1 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][qp[0]][0]);
2074 if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
2075 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*2 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][qp[1]][0]);
2076 h->h264dsp.h264_idct_add8(dest, block_offset,
2078 h->non_zero_count_cache);
2080 #if CONFIG_SVQ3_DECODER
2082 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*1, h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
2083 h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*2, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
2085 for(i=j*16; i<j*16+4; i++){
2086 if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2087 uint8_t * const ptr= dest[j-1] + block_offset[i];
2088 ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
2097 if(h->cbp || IS_INTRA(mb_type))
2099 s->dsp.clear_blocks(h->mb);
2100 s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2104 static av_always_inline void hl_decode_mb_444_internal(H264Context *h, int simple, int pixel_shift){
2105 MpegEncContext * const s = &h->s;
2106 const int mb_x= s->mb_x;
2107 const int mb_y= s->mb_y;
2108 const int mb_xy= h->mb_xy;
2109 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2113 int *block_offset = &h->block_offset[0];
2114 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2115 const int plane_count = (simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) ? 3 : 1;
2117 for (p = 0; p < plane_count; p++)
2119 dest[p] = s->current_picture.f.data[p] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2120 s->dsp.prefetch(dest[p] + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
2123 h->list_counts[mb_xy]= h->list_count;
2125 if (!simple && MB_FIELD) {
2126 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2127 block_offset = &h->block_offset[48];
2128 if(mb_y&1) //FIXME move out of this function?
2129 for (p = 0; p < 3; p++)
2130 dest[p] -= s->linesize*15;
2133 for(list=0; list<h->list_count; list++){
2134 if(!USES_LIST(mb_type, list))
2136 if(IS_16X16(mb_type)){
2137 int8_t *ref = &h->ref_cache[list][scan8[0]];
2138 fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2140 for(i=0; i<16; i+=4){
2141 int ref = h->ref_cache[list][scan8[i]];
2143 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2149 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2152 if (!simple && IS_INTRA_PCM(mb_type)) {
2154 const int bit_depth = h->sps.bit_depth_luma;
2156 init_get_bits(&gb, (uint8_t*)h->mb, 768*bit_depth);
2158 for (p = 0; p < plane_count; p++) {
2159 for (i = 0; i < 16; i++) {
2160 uint16_t *tmp = (uint16_t*)(dest[p] + i*linesize);
2161 for (j = 0; j < 16; j++)
2162 tmp[j] = get_bits(&gb, bit_depth);
2166 for (p = 0; p < plane_count; p++) {
2167 for (i = 0; i < 16; i++) {
2168 memcpy(dest[p] + i*linesize, h->mb + p*128 + i*8, 16);
2173 if(IS_INTRA(mb_type)){
2174 if(h->deblocking_filter)
2175 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 1, 1, simple, pixel_shift);
2177 for (p = 0; p < plane_count; p++)
2178 hl_decode_mb_predict_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2180 if(h->deblocking_filter)
2181 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 0, 1, simple, pixel_shift);
2183 hl_motion(h, dest[0], dest[1], dest[2],
2184 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2185 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2186 h->h264dsp.weight_h264_pixels_tab,
2187 h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
2190 for (p = 0; p < plane_count; p++)
2191 hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2193 if(h->cbp || IS_INTRA(mb_type))
2195 s->dsp.clear_blocks(h->mb);
2196 s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2201 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2203 #define hl_decode_mb_simple(sh, bits) \
2204 static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
2205 hl_decode_mb_internal(h, 1, sh); \
2207 hl_decode_mb_simple(0, 8)
2208 hl_decode_mb_simple(1, 16)
2211 * Process a macroblock; this handles edge cases, such as interlacing.
2213 static void av_noinline hl_decode_mb_complex(H264Context *h){
2214 hl_decode_mb_internal(h, 0, h->pixel_shift);
2217 static void av_noinline hl_decode_mb_444_complex(H264Context *h){
2218 hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2221 static void av_noinline hl_decode_mb_444_simple(H264Context *h){
2222 hl_decode_mb_444_internal(h, 1, 0);
2225 void ff_h264_hl_decode_mb(H264Context *h){
2226 MpegEncContext * const s = &h->s;
2227 const int mb_xy= h->mb_xy;
2228 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2229 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2232 if(is_complex || h->pixel_shift)
2233 hl_decode_mb_444_complex(h);
2235 hl_decode_mb_444_simple(h);
2236 } else if (is_complex) {
2237 hl_decode_mb_complex(h);
2238 } else if (h->pixel_shift) {
2239 hl_decode_mb_simple_16(h);
2241 hl_decode_mb_simple_8(h);
2244 static int pred_weight_table(H264Context *h){
2245 MpegEncContext * const s = &h->s;
2247 int luma_def, chroma_def;
2250 h->use_weight_chroma= 0;
2251 h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2252 if(h->sps.chroma_format_idc)
2253 h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2254 luma_def = 1<<h->luma_log2_weight_denom;
2255 chroma_def = 1<<h->chroma_log2_weight_denom;
2257 for(list=0; list<2; list++){
2258 h->luma_weight_flag[list] = 0;
2259 h->chroma_weight_flag[list] = 0;
2260 for(i=0; i<h->ref_count[list]; i++){
2261 int luma_weight_flag, chroma_weight_flag;
2263 luma_weight_flag= get_bits1(&s->gb);
2264 if(luma_weight_flag){
2265 h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
2266 h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
2267 if( h->luma_weight[i][list][0] != luma_def
2268 || h->luma_weight[i][list][1] != 0) {
2270 h->luma_weight_flag[list]= 1;
2273 h->luma_weight[i][list][0]= luma_def;
2274 h->luma_weight[i][list][1]= 0;
2277 if(h->sps.chroma_format_idc){
2278 chroma_weight_flag= get_bits1(&s->gb);
2279 if(chroma_weight_flag){
2282 h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
2283 h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
2284 if( h->chroma_weight[i][list][j][0] != chroma_def
2285 || h->chroma_weight[i][list][j][1] != 0) {
2286 h->use_weight_chroma= 1;
2287 h->chroma_weight_flag[list]= 1;
2293 h->chroma_weight[i][list][j][0]= chroma_def;
2294 h->chroma_weight[i][list][j][1]= 0;
2299 if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
2301 h->use_weight= h->use_weight || h->use_weight_chroma;
2306 * Initialize implicit_weight table.
2307 * @param field 0/1 initialize the weight for interlaced MBAFF
2308 * -1 initializes the rest
2310 static void implicit_weight_table(H264Context *h, int field){
2311 MpegEncContext * const s = &h->s;
2312 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2314 for (i = 0; i < 2; i++) {
2315 h->luma_weight_flag[i] = 0;
2316 h->chroma_weight_flag[i] = 0;
2320 if (s->picture_structure == PICT_FRAME) {
2321 cur_poc = s->current_picture_ptr->poc;
2323 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2325 if( h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
2326 && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
2328 h->use_weight_chroma= 0;
2332 ref_count0= h->ref_count[0];
2333 ref_count1= h->ref_count[1];
2335 cur_poc = s->current_picture_ptr->field_poc[field];
2337 ref_count0= 16+2*h->ref_count[0];
2338 ref_count1= 16+2*h->ref_count[1];
2342 h->use_weight_chroma= 2;
2343 h->luma_log2_weight_denom= 5;
2344 h->chroma_log2_weight_denom= 5;
2346 for(ref0=ref_start; ref0 < ref_count0; ref0++){
2347 int poc0 = h->ref_list[0][ref0].poc;
2348 for(ref1=ref_start; ref1 < ref_count1; ref1++){
2350 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2351 int poc1 = h->ref_list[1][ref1].poc;
2352 int td = av_clip(poc1 - poc0, -128, 127);
2354 int tb = av_clip(cur_poc - poc0, -128, 127);
2355 int tx = (16384 + (FFABS(td) >> 1)) / td;
2356 int dist_scale_factor = (tb*tx + 32) >> 8;
2357 if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
2358 w = 64 - dist_scale_factor;
2362 h->implicit_weight[ref0][ref1][0]=
2363 h->implicit_weight[ref0][ref1][1]= w;
2365 h->implicit_weight[ref0][ref1][field]=w;
2372 * instantaneous decoder refresh.
2374 static void idr(H264Context *h){
2376 ff_h264_remove_all_refs(h);
2377 h->prev_frame_num= 0;
2378 h->prev_frame_num_offset= 0;
2379 h->prev_poc_msb= 1<<16;
2381 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2382 h->last_pocs[i] = INT_MIN;
2385 /* forget old pics after a seek */
2386 static void flush_dpb(AVCodecContext *avctx){
2387 H264Context *h= avctx->priv_data;
2389 for(i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2390 if(h->delayed_pic[i])
2391 h->delayed_pic[i]->f.reference = 0;
2392 h->delayed_pic[i]= NULL;
2394 h->outputed_poc=h->next_outputed_poc= INT_MIN;
2395 h->prev_interlaced_frame = 1;
2397 h->prev_frame_num= -1;
2398 if(h->s.current_picture_ptr)
2399 h->s.current_picture_ptr->f.reference = 0;
2400 h->s.first_field= 0;
2401 ff_h264_reset_sei(h);
2402 ff_mpeg_flush(avctx);
2403 h->recovery_frame= -1;
2407 static int init_poc(H264Context *h){
2408 MpegEncContext * const s = &h->s;
2409 const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2411 Picture *cur = s->current_picture_ptr;
2413 h->frame_num_offset= h->prev_frame_num_offset;
2414 if(h->frame_num < h->prev_frame_num)
2415 h->frame_num_offset += max_frame_num;
2417 if(h->sps.poc_type==0){
2418 const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2420 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2421 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2422 else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2423 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2425 h->poc_msb = h->prev_poc_msb;
2426 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2428 field_poc[1] = h->poc_msb + h->poc_lsb;
2429 if(s->picture_structure == PICT_FRAME)
2430 field_poc[1] += h->delta_poc_bottom;
2431 }else if(h->sps.poc_type==1){
2432 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2435 if(h->sps.poc_cycle_length != 0)
2436 abs_frame_num = h->frame_num_offset + h->frame_num;
2440 if(h->nal_ref_idc==0 && abs_frame_num > 0)
2443 expected_delta_per_poc_cycle = 0;
2444 for(i=0; i < h->sps.poc_cycle_length; i++)
2445 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2447 if(abs_frame_num > 0){
2448 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2449 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2451 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2452 for(i = 0; i <= frame_num_in_poc_cycle; i++)
2453 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2457 if(h->nal_ref_idc == 0)
2458 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2460 field_poc[0] = expectedpoc + h->delta_poc[0];
2461 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2463 if(s->picture_structure == PICT_FRAME)
2464 field_poc[1] += h->delta_poc[1];
2466 int poc= 2*(h->frame_num_offset + h->frame_num);
2475 if(s->picture_structure != PICT_BOTTOM_FIELD)
2476 s->current_picture_ptr->field_poc[0]= field_poc[0];
2477 if(s->picture_structure != PICT_TOP_FIELD)
2478 s->current_picture_ptr->field_poc[1]= field_poc[1];
2479 cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2486 * initialize scan tables
2488 static void init_scan_tables(H264Context *h){
2490 for(i=0; i<16; i++){
2491 #define T(x) (x>>2) | ((x<<2) & 0xF)
2492 h->zigzag_scan[i] = T(zigzag_scan[i]);
2493 h-> field_scan[i] = T( field_scan[i]);
2496 for(i=0; i<64; i++){
2497 #define T(x) (x>>3) | ((x&7)<<3)
2498 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2499 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2500 h->field_scan8x8[i] = T(field_scan8x8[i]);
2501 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2504 if(h->sps.transform_bypass){ //FIXME same ugly
2505 h->zigzag_scan_q0 = zigzag_scan;
2506 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2507 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2508 h->field_scan_q0 = field_scan;
2509 h->field_scan8x8_q0 = field_scan8x8;
2510 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2512 h->zigzag_scan_q0 = h->zigzag_scan;
2513 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2514 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2515 h->field_scan_q0 = h->field_scan;
2516 h->field_scan8x8_q0 = h->field_scan8x8;
2517 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2521 static int field_end(H264Context *h, int in_setup){
2522 MpegEncContext * const s = &h->s;
2523 AVCodecContext * const avctx= s->avctx;
2527 if (!in_setup && !s->dropable)
2528 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2529 s->picture_structure==PICT_BOTTOM_FIELD);
2531 if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2532 ff_vdpau_h264_set_reference_frames(s);
2534 if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2536 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2537 h->prev_poc_msb= h->poc_msb;
2538 h->prev_poc_lsb= h->poc_lsb;
2540 h->prev_frame_num_offset= h->frame_num_offset;
2541 h->prev_frame_num= h->frame_num;
2542 h->outputed_poc = h->next_outputed_poc;
2545 if (avctx->hwaccel) {
2546 if (avctx->hwaccel->end_frame(avctx) < 0)
2547 av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2550 if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2551 ff_vdpau_h264_picture_complete(s);
2554 * FIXME: Error handling code does not seem to support interlaced
2555 * when slices span multiple rows
2556 * The ff_er_add_slice calls don't work right for bottom
2557 * fields; they cause massive erroneous error concealing
2558 * Error marking covers both fields (top and bottom).
2559 * This causes a mismatched s->error_count
2560 * and a bad error table. Further, the error count goes to
2561 * INT_MAX when called for bottom field, because mb_y is
2562 * past end by one (callers fault) and resync_mb_y != 0
2563 * causes problems for the first MB line, too.
2576 * Replicate H264 "master" context to thread contexts.
2578 static void clone_slice(H264Context *dst, H264Context *src)
2580 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2581 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2582 dst->s.current_picture = src->s.current_picture;
2583 dst->s.linesize = src->s.linesize;
2584 dst->s.uvlinesize = src->s.uvlinesize;
2585 dst->s.first_field = src->s.first_field;
2587 dst->prev_poc_msb = src->prev_poc_msb;
2588 dst->prev_poc_lsb = src->prev_poc_lsb;
2589 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2590 dst->prev_frame_num = src->prev_frame_num;
2591 dst->short_ref_count = src->short_ref_count;
2593 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2594 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2595 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2596 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2598 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2599 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2603 * Compute profile from profile_idc and constraint_set?_flags.
2607 * @return profile as defined by FF_PROFILE_H264_*
2609 int ff_h264_get_profile(SPS *sps)
2611 int profile = sps->profile_idc;
2613 switch(sps->profile_idc) {
2614 case FF_PROFILE_H264_BASELINE:
2615 // constraint_set1_flag set to 1
2616 profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2618 case FF_PROFILE_H264_HIGH_10:
2619 case FF_PROFILE_H264_HIGH_422:
2620 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2621 // constraint_set3_flag set to 1
2622 profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2630 * Decode a slice header.
2631 * This will also call MPV_common_init() and frame_start() as needed.
2633 * @param h h264context
2634 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2636 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2638 static int decode_slice_header(H264Context *h, H264Context *h0){
2639 MpegEncContext * const s = &h->s;
2640 MpegEncContext * const s0 = &h0->s;
2641 unsigned int first_mb_in_slice;
2642 unsigned int pps_id;
2643 int num_ref_idx_active_override_flag;
2644 unsigned int slice_type, tmp, i, j;
2645 int default_ref_list_done = 0;
2646 int last_pic_structure;
2648 s->dropable= h->nal_ref_idc == 0;
2650 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2651 if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
2652 s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2653 s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2655 s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2656 s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2659 first_mb_in_slice= get_ue_golomb_long(&s->gb);
2661 if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2662 if(h0->current_slice && FIELD_PICTURE){
2666 h0->current_slice = 0;
2667 if (!s0->first_field)
2668 s->current_picture_ptr= NULL;
2671 slice_type= get_ue_golomb_31(&s->gb);
2673 av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
2678 h->slice_type_fixed=1;
2680 h->slice_type_fixed=0;
2682 slice_type= golomb_to_pict_type[ slice_type ];
2683 if (slice_type == AV_PICTURE_TYPE_I
2684 || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2685 default_ref_list_done = 1;
2687 h->slice_type= slice_type;
2688 h->slice_type_nos= slice_type & 3;
2690 s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2692 pps_id= get_ue_golomb(&s->gb);
2693 if(pps_id>=MAX_PPS_COUNT){
2694 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2697 if(!h0->pps_buffers[pps_id]) {
2698 av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2701 h->pps= *h0->pps_buffers[pps_id];
2703 if(!h0->sps_buffers[h->pps.sps_id]) {
2704 av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2707 h->sps = *h0->sps_buffers[h->pps.sps_id];
2709 s->avctx->profile = ff_h264_get_profile(&h->sps);
2710 s->avctx->level = h->sps.level_idc;
2711 s->avctx->refs = h->sps.ref_frame_count;
2713 if(h == h0 && h->dequant_coeff_pps != pps_id){
2714 h->dequant_coeff_pps = pps_id;
2715 init_dequant_tables(h);
2718 s->mb_width= h->sps.mb_width;
2719 s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2721 h->b_stride= s->mb_width*4;
2723 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2725 s->width = 16*s->mb_width;
2726 s->height= 16*s->mb_height;
2728 if (s->context_initialized
2729 && ( s->width != s->avctx->coded_width || s->height != s->avctx->coded_height
2730 || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2731 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2732 || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2734 av_log_missing_feature(s->avctx, "Width/height/bit depth/chroma idc changing with threads is", 0);
2735 return -1; // width / height changed during parallelized decoding
2738 flush_dpb(s->avctx);
2742 if (!s->context_initialized) {
2744 av_log(h->s.avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n");
2747 avcodec_set_dimensions(s->avctx, s->width, s->height);
2748 s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2749 s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
2750 s->avctx->sample_aspect_ratio= h->sps.sar;
2751 av_assert0(s->avctx->sample_aspect_ratio.den);
2753 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2754 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2755 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10 &&
2756 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2757 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2758 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2759 h->pixel_shift = h->sps.bit_depth_luma > 8;
2761 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2762 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2763 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2764 dsputil_init(&s->dsp, s->avctx);
2766 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2767 h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2772 if(h->sps.video_signal_type_present_flag){
2773 s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2774 if(h->sps.colour_description_present_flag){
2775 s->avctx->color_primaries = h->sps.color_primaries;
2776 s->avctx->color_trc = h->sps.color_trc;
2777 s->avctx->colorspace = h->sps.colorspace;
2781 if(h->sps.timing_info_present_flag){
2782 int64_t den= h->sps.time_scale;
2783 if(h->x264_build < 44U)
2785 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2786 h->sps.num_units_in_tick, den, 1<<30);
2789 switch (h->sps.bit_depth_luma) {
2792 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2793 s->avctx->pix_fmt = PIX_FMT_GBRP9;
2795 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
2796 } else if (CHROMA422)
2797 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
2799 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2803 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2804 s->avctx->pix_fmt = PIX_FMT_GBRP10;
2806 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
2807 } else if (CHROMA422)
2808 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
2810 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2814 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P : PIX_FMT_YUV444P;
2815 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2816 s->avctx->pix_fmt = PIX_FMT_GBR24P;
2817 av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2818 } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2819 av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2821 } else if (CHROMA422) {
2822 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P : PIX_FMT_YUV422P;
2824 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2825 s->avctx->codec->pix_fmts ?
2826 s->avctx->codec->pix_fmts :
2827 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2828 hwaccel_pixfmt_list_h264_jpeg_420 :
2829 ff_hwaccel_pixfmt_list_420);
2833 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2835 if (MPV_common_init(s) < 0) {
2836 av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed.\n");
2840 h->prev_interlaced_frame = 1;
2842 init_scan_tables(h);
2843 if (ff_h264_alloc_tables(h) < 0) {
2844 av_log(h->s.avctx, AV_LOG_ERROR, "Could not allocate memory for h264\n");
2845 return AVERROR(ENOMEM);
2848 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2849 if (context_init(h) < 0) {
2850 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2854 for(i = 1; i < s->avctx->thread_count; i++) {
2856 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2857 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2858 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2859 c->h264dsp = h->h264dsp;
2862 c->pixel_shift = h->pixel_shift;
2863 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2864 init_scan_tables(c);
2865 clone_tables(c, h, i);
2868 for(i = 0; i < s->avctx->thread_count; i++)
2869 if (context_init(h->thread_context[i]) < 0) {
2870 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2876 h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2879 h->mb_aff_frame = 0;
2880 last_pic_structure = s0->picture_structure;
2881 if(h->sps.frame_mbs_only_flag){
2882 s->picture_structure= PICT_FRAME;
2884 if(!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B){
2885 av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2888 if(get_bits1(&s->gb)) { //field_pic_flag
2889 s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2891 s->picture_structure= PICT_FRAME;
2892 h->mb_aff_frame = h->sps.mb_aff;
2895 h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2897 if(h0->current_slice == 0){
2898 // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
2899 if(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2900 int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
2902 if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
2904 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2905 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2906 if (unwrap_prev_frame_num < 0)
2907 unwrap_prev_frame_num += max_frame_num;
2909 h->prev_frame_num = unwrap_prev_frame_num;
2913 while(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
2914 h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2915 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2916 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2917 if (ff_h264_frame_start(h) < 0)
2919 h->prev_frame_num++;
2920 h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2921 s->current_picture_ptr->frame_num= h->prev_frame_num;
2922 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2923 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2924 ff_generate_sliding_window_mmcos(h);
2925 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2926 (s->avctx->err_recognition & AV_EF_EXPLODE))
2927 return AVERROR_INVALIDDATA;
2928 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2929 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2930 * about there being no actual duplicates.
2931 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2932 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2934 if (h->short_ref_count) {
2936 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2937 (const uint8_t**)prev->f.data, prev->f.linesize,
2938 s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2939 h->short_ref[0]->poc = prev->poc+2;
2941 h->short_ref[0]->frame_num = h->prev_frame_num;
2945 /* See if we have a decoded first field looking for a pair... */
2946 if (s0->first_field) {
2947 assert(s0->current_picture_ptr);
2948 assert(s0->current_picture_ptr->f.data[0]);
2949 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2951 /* figure out if we have a complementary field pair */
2952 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2954 * Previous field is unmatched. Don't display it, but let it
2955 * remain for reference if marked as such.
2957 s0->current_picture_ptr = NULL;
2958 s0->first_field = FIELD_PICTURE;
2961 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2963 * This and previous field had
2964 * different frame_nums. Consider this field first in
2965 * pair. Throw away previous field except for reference
2968 s0->first_field = 1;
2969 s0->current_picture_ptr = NULL;
2972 /* Second field in complementary pair */
2973 s0->first_field = 0;
2978 /* Frame or first field in a potentially complementary pair */
2979 assert(!s0->current_picture_ptr);
2980 s0->first_field = FIELD_PICTURE;
2983 if(!FIELD_PICTURE || s0->first_field) {
2984 if (ff_h264_frame_start(h) < 0) {
2985 s0->first_field = 0;
2989 ff_release_unused_pictures(s, 0);
2995 s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2997 assert(s->mb_num == s->mb_width * s->mb_height);
2998 if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2999 first_mb_in_slice >= s->mb_num){
3000 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3003 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3004 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3005 if (s->picture_structure == PICT_BOTTOM_FIELD)
3006 s->resync_mb_y = s->mb_y = s->mb_y + 1;
3007 assert(s->mb_y < s->mb_height);
3009 if(s->picture_structure==PICT_FRAME){
3010 h->curr_pic_num= h->frame_num;
3011 h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3013 h->curr_pic_num= 2*h->frame_num + 1;
3014 h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3017 if(h->nal_unit_type == NAL_IDR_SLICE){
3018 get_ue_golomb(&s->gb); /* idr_pic_id */
3021 if(h->sps.poc_type==0){
3022 h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3024 if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3025 h->delta_poc_bottom= get_se_golomb(&s->gb);
3029 if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3030 h->delta_poc[0]= get_se_golomb(&s->gb);
3032 if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3033 h->delta_poc[1]= get_se_golomb(&s->gb);
3038 if(h->pps.redundant_pic_cnt_present){
3039 h->redundant_pic_count= get_ue_golomb(&s->gb);
3042 //set defaults, might be overridden a few lines later
3043 h->ref_count[0]= h->pps.ref_count[0];
3044 h->ref_count[1]= h->pps.ref_count[1];
3046 if(h->slice_type_nos != AV_PICTURE_TYPE_I){
3047 unsigned max= (16<<(s->picture_structure != PICT_FRAME))-1;
3048 if(h->slice_type_nos == AV_PICTURE_TYPE_B){
3049 h->direct_spatial_mv_pred= get_bits1(&s->gb);
3051 num_ref_idx_active_override_flag= get_bits1(&s->gb);
3053 if(num_ref_idx_active_override_flag){
3054 h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3055 if(h->slice_type_nos==AV_PICTURE_TYPE_B)
3056 h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3059 if(h->ref_count[0]-1 > max || h->ref_count[1]-1 > max){
3060 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3061 h->ref_count[0]= h->ref_count[1]= 1;
3064 if(h->slice_type_nos == AV_PICTURE_TYPE_B)
3069 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3071 if(!default_ref_list_done){
3072 ff_h264_fill_default_ref_list(h);
3075 if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3076 h->ref_count[1]= h->ref_count[0]= 0;
3080 if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
3081 s->last_picture_ptr= &h->ref_list[0][0];
3082 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3084 if(h->slice_type_nos==AV_PICTURE_TYPE_B){
3085 s->next_picture_ptr= &h->ref_list[1][0];
3086 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3089 if( (h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P )
3090 || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
3091 pred_weight_table(h);
3092 else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3093 implicit_weight_table(h, -1);
3096 for (i = 0; i < 2; i++) {
3097 h->luma_weight_flag[i] = 0;
3098 h->chroma_weight_flag[i] = 0;
3102 if(h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3103 (s->avctx->err_recognition & AV_EF_EXPLODE))
3104 return AVERROR_INVALIDDATA;
3107 ff_h264_fill_mbaff_ref_list(h);
3109 if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3110 implicit_weight_table(h, 0);
3111 implicit_weight_table(h, 1);
3115 if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3116 ff_h264_direct_dist_scale_factor(h);
3117 ff_h264_direct_ref_list_init(h);
3119 if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
3120 tmp = get_ue_golomb_31(&s->gb);
3122 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3125 h->cabac_init_idc= tmp;
3128 h->last_qscale_diff = 0;
3129 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3130 if(tmp>51+6*(h->sps.bit_depth_luma-8)){
3131 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3135 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3136 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3137 //FIXME qscale / qp ... stuff
3138 if(h->slice_type == AV_PICTURE_TYPE_SP){
3139 get_bits1(&s->gb); /* sp_for_switch_flag */
3141 if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
3142 get_se_golomb(&s->gb); /* slice_qs_delta */
3145 h->deblocking_filter = 1;
3146 h->slice_alpha_c0_offset = 52;
3147 h->slice_beta_offset = 52;
3148 if( h->pps.deblocking_filter_parameters_present ) {
3149 tmp= get_ue_golomb_31(&s->gb);
3151 av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
3154 h->deblocking_filter= tmp;
3155 if(h->deblocking_filter < 2)
3156 h->deblocking_filter^= 1; // 1<->0
3158 if( h->deblocking_filter ) {
3159 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3160 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3161 if( h->slice_alpha_c0_offset > 104U
3162 || h->slice_beta_offset > 104U){
3163 av_log(s->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset);
3169 if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
3170 ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
3171 ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B)
3172 ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
3173 h->deblocking_filter= 0;
3175 if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
3176 if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
3177 /* Cheat slightly for speed:
3178 Do not bother to deblock across slices. */
3179 h->deblocking_filter = 2;
3181 h0->max_contexts = 1;
3182 if(!h0->single_decode_warning) {
3183 av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3184 h0->single_decode_warning = 1;
3187 av_log(h->s.avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n");
3192 h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset)
3193 - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1])
3194 + 6 * (h->sps.bit_depth_luma - 8);
3197 if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3198 slice_group_change_cycle= get_bits(&s->gb, ?);
3201 h0->last_slice_type = slice_type;
3202 h->slice_num = ++h0->current_slice;
3205 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3206 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3207 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3208 && h->slice_num >= MAX_SLICES) {
3209 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3210 av_log(s->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3215 int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
3216 for(i=0; i<16; i++){
3218 if (h->ref_list[j][i].f.data[0]) {
3220 uint8_t *base = h->ref_list[j][i].f.base[0];
3221 for(k=0; k<h->short_ref_count; k++)
3222 if (h->short_ref[k]->f.base[0] == base) {
3226 for(k=0; k<h->long_ref_count; k++)
3227 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3228 id_list[i]= h->short_ref_count + k;
3237 ref2frm[i+2]= 4*id_list[i]
3238 + (h->ref_list[j][i].f.reference & 3);
3241 for(i=16; i<48; i++)
3242 ref2frm[i+4]= 4*id_list[(i-16)>>1]
3243 + (h->ref_list[j][i].f.reference & 3);
3246 //FIXME: fix draw_edges+PAFF+frame threads
3247 h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
3248 h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3250 if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3251 av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3253 (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
3255 av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3256 pps_id, h->frame_num,
3257 s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3258 h->ref_count[0], h->ref_count[1],
3260 h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
3262 h->use_weight==1 && h->use_weight_chroma ? "c" : "",
3263 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
3270 int ff_h264_get_slice_type(const H264Context *h)
3272 switch (h->slice_type) {
3273 case AV_PICTURE_TYPE_P: return 0;
3274 case AV_PICTURE_TYPE_B: return 1;
3275 case AV_PICTURE_TYPE_I: return 2;
3276 case AV_PICTURE_TYPE_SP: return 3;
3277 case AV_PICTURE_TYPE_SI: return 4;
3282 static av_always_inline void fill_filter_caches_inter(H264Context *h, MpegEncContext * const s, int mb_type, int top_xy,
3283 int left_xy[LEFT_MBS], int top_type, int left_type[LEFT_MBS], int mb_xy, int list)
3285 int b_stride = h->b_stride;
3286 int16_t (*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3287 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3288 if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
3289 if(USES_LIST(top_type, list)){
3290 const int b_xy= h->mb2b_xy[top_xy] + 3*b_stride;
3291 const int b8_xy= 4*top_xy + 2;
3292 int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3293 AV_COPY128(mv_dst - 1*8, s->current_picture.f.motion_val[list][b_xy + 0]);
3295 ref_cache[1 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3297 ref_cache[3 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3299 AV_ZERO128(mv_dst - 1*8);
3300 AV_WN32A(&ref_cache[0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3303 if(!IS_INTERLACED(mb_type^left_type[LTOP])){
3304 if(USES_LIST(left_type[LTOP], list)){
3305 const int b_xy= h->mb2b_xy[left_xy[LTOP]] + 3;
3306 const int b8_xy= 4*left_xy[LTOP] + 1;
3307 int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[LTOP]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3308 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride*0]);
3309 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride*1]);
3310 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride*2]);
3311 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride*3]);
3313 ref_cache[-1 + 8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*0]];
3315 ref_cache[-1 + 24]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*1]];
3317 AV_ZERO32(mv_dst - 1 + 0);
3318 AV_ZERO32(mv_dst - 1 + 8);
3319 AV_ZERO32(mv_dst - 1 +16);
3320 AV_ZERO32(mv_dst - 1 +24);
3324 ref_cache[-1 + 24]= LIST_NOT_USED;
3329 if(!USES_LIST(mb_type, list)){
3330 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0,0), 4);
3331 AV_WN32A(&ref_cache[0*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3332 AV_WN32A(&ref_cache[1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3333 AV_WN32A(&ref_cache[2*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3334 AV_WN32A(&ref_cache[3*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3339 int8_t *ref = &s->current_picture.f.ref_index[list][4*mb_xy];
3340 int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3341 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101;
3342 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]],ref2frm[list][ref[3]])&0x00FF00FF)*0x0101;
3343 AV_WN32A(&ref_cache[0*8], ref01);
3344 AV_WN32A(&ref_cache[1*8], ref01);
3345 AV_WN32A(&ref_cache[2*8], ref23);
3346 AV_WN32A(&ref_cache[3*8], ref23);
3350 int16_t (*mv_src)[2] = &s->current_picture.f.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
3351 AV_COPY128(mv_dst + 8*0, mv_src + 0*b_stride);
3352 AV_COPY128(mv_dst + 8*1, mv_src + 1*b_stride);
3353 AV_COPY128(mv_dst + 8*2, mv_src + 2*b_stride);
3354 AV_COPY128(mv_dst + 8*3, mv_src + 3*b_stride);
3360 * @return non zero if the loop filter can be skipped
3362 static int fill_filter_caches(H264Context *h, int mb_type){
3363 MpegEncContext * const s = &h->s;
3364 const int mb_xy= h->mb_xy;
3365 int top_xy, left_xy[LEFT_MBS];
3366 int top_type, left_type[LEFT_MBS];
3370 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3372 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3373 * stuff, I can't imagine that these complex rules are worth it. */
3375 left_xy[LBOT] = left_xy[LTOP] = mb_xy-1;
3377 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3378 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3380 if (left_mb_field_flag != curr_mb_field_flag) {
3381 left_xy[LTOP] -= s->mb_stride;
3384 if(curr_mb_field_flag){
3385 top_xy += s->mb_stride & (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3387 if (left_mb_field_flag != curr_mb_field_flag) {
3388 left_xy[LBOT] += s->mb_stride;
3393 h->top_mb_xy = top_xy;
3394 h->left_mb_xy[LTOP] = left_xy[LTOP];
3395 h->left_mb_xy[LBOT] = left_xy[LBOT];
3397 //for sufficiently low qp, filtering wouldn't do anything
3398 //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
3399 int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
3400 int qp = s->current_picture.f.qscale_table[mb_xy];
3402 && (left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh)
3403 && (top_xy < 0 || ((qp + s->current_picture.f.qscale_table[top_xy ] + 1) >> 1) <= qp_thresh)) {
3406 if ((left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LBOT] ] + 1) >> 1) <= qp_thresh) &&
3407 (top_xy < s->mb_stride || ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3412 top_type = s->current_picture.f.mb_type[top_xy];
3413 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3414 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3415 if(h->deblocking_filter == 2){
3416 if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
3417 if(h->slice_table[left_xy[LBOT]] != h->slice_num) left_type[LTOP]= left_type[LBOT]= 0;
3419 if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
3420 if(h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP]= left_type[LBOT] =0;
3422 h->top_type = top_type;
3423 h->left_type[LTOP]= left_type[LTOP];
3424 h->left_type[LBOT]= left_type[LBOT];
3426 if(IS_INTRA(mb_type))
3429 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0);
3430 if(h->list_count == 2)
3431 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1);
3433 nnz = h->non_zero_count[mb_xy];
3434 nnz_cache = h->non_zero_count_cache;
3435 AV_COPY32(&nnz_cache[4+8*1], &nnz[ 0]);
3436 AV_COPY32(&nnz_cache[4+8*2], &nnz[ 4]);
3437 AV_COPY32(&nnz_cache[4+8*3], &nnz[ 8]);
3438 AV_COPY32(&nnz_cache[4+8*4], &nnz[12]);
3439 h->cbp= h->cbp_table[mb_xy];
3442 nnz = h->non_zero_count[top_xy];
3443 AV_COPY32(&nnz_cache[4+8*0], &nnz[3*4]);
3446 if(left_type[LTOP]){
3447 nnz = h->non_zero_count[left_xy[LTOP]];
3448 nnz_cache[3+8*1]= nnz[3+0*4];
3449 nnz_cache[3+8*2]= nnz[3+1*4];
3450 nnz_cache[3+8*3]= nnz[3+2*4];
3451 nnz_cache[3+8*4]= nnz[3+3*4];
3454 // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
3455 if(!CABAC && h->pps.transform_8x8_mode){
3456 if(IS_8x8DCT(top_type)){
3458 nnz_cache[5+8*0]= (h->cbp_table[top_xy] & 0x4000) >> 12;
3460 nnz_cache[7+8*0]= (h->cbp_table[top_xy] & 0x8000) >> 12;
3462 if(IS_8x8DCT(left_type[LTOP])){
3464 nnz_cache[3+8*2]= (h->cbp_table[left_xy[LTOP]]&0x2000) >> 12; //FIXME check MBAFF
3466 if(IS_8x8DCT(left_type[LBOT])){
3468 nnz_cache[3+8*4]= (h->cbp_table[left_xy[LBOT]]&0x8000) >> 12; //FIXME check MBAFF
3471 if(IS_8x8DCT(mb_type)){
3472 nnz_cache[scan8[0 ]]= nnz_cache[scan8[1 ]]=
3473 nnz_cache[scan8[2 ]]= nnz_cache[scan8[3 ]]= (h->cbp & 0x1000) >> 12;
3475 nnz_cache[scan8[0+ 4]]= nnz_cache[scan8[1+ 4]]=
3476 nnz_cache[scan8[2+ 4]]= nnz_cache[scan8[3+ 4]]= (h->cbp & 0x2000) >> 12;
3478 nnz_cache[scan8[0+ 8]]= nnz_cache[scan8[1+ 8]]=
3479 nnz_cache[scan8[2+ 8]]= nnz_cache[scan8[3+ 8]]= (h->cbp & 0x4000) >> 12;
3481 nnz_cache[scan8[0+12]]= nnz_cache[scan8[1+12]]=
3482 nnz_cache[scan8[2+12]]= nnz_cache[scan8[3+12]]= (h->cbp & 0x8000) >> 12;
3489 static void loop_filter(H264Context *h, int start_x, int end_x){
3490 MpegEncContext * const s = &h->s;
3491 uint8_t *dest_y, *dest_cb, *dest_cr;
3492 int linesize, uvlinesize, mb_x, mb_y;
3493 const int end_mb_y= s->mb_y + FRAME_MBAFF;
3494 const int old_slice_type= h->slice_type;
3495 const int pixel_shift = h->pixel_shift;
3496 const int block_h = 16 >> s->chroma_y_shift;
3498 if(h->deblocking_filter) {
3499 for(mb_x= start_x; mb_x<end_x; mb_x++){
3500 for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
3502 mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
3503 h->slice_num= h->slice_table[mb_xy];
3504 mb_type = s->current_picture.f.mb_type[mb_xy];
3505 h->list_count= h->list_counts[mb_xy];
3508 h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3512 dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
3513 dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
3514 dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
3515 //FIXME simplify above
3518 linesize = h->mb_linesize = s->linesize * 2;
3519 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3520 if(mb_y&1){ //FIXME move out of this function?
3521 dest_y -= s->linesize*15;
3522 dest_cb-= s->uvlinesize * (block_h - 1);
3523 dest_cr-= s->uvlinesize * (block_h - 1);
3526 linesize = h->mb_linesize = s->linesize;
3527 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3529 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
3530 if(fill_filter_caches(h, mb_type))
3532 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3533 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3536 ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3538 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3543 h->slice_type= old_slice_type;
3545 s->mb_y= end_mb_y - FRAME_MBAFF;
3546 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3547 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3550 static void predict_field_decoding_flag(H264Context *h){
3551 MpegEncContext * const s = &h->s;
3552 const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3553 int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
3554 ? s->current_picture.f.mb_type[mb_xy - 1]
3555 : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
3556 ? s->current_picture.f.mb_type[mb_xy - s->mb_stride]
3558 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3562 * Draw edges and report progress for the last MB row.
3564 static void decode_finish_row(H264Context *h){
3565 MpegEncContext * const s = &h->s;
3566 int top = 16*(s->mb_y >> FIELD_PICTURE);
3567 int height = 16 << FRAME_MBAFF;
3568 int deblock_border = (16 + 4) << FRAME_MBAFF;
3569 int pic_height = 16*s->mb_height >> FIELD_PICTURE;
3571 if (h->deblocking_filter) {
3572 if((top + height) >= pic_height)
3573 height += deblock_border;
3575 top -= deblock_border;
3578 if (top >= pic_height || (top + height) < h->emu_edge_height)
3581 height = FFMIN(height, pic_height - top);
3582 if (top < h->emu_edge_height) {
3583 height = top+height;
3587 ff_draw_horiz_band(s, top, height);
3589 if (s->dropable) return;
3591 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3592 s->picture_structure==PICT_BOTTOM_FIELD);
3595 static int decode_slice(struct AVCodecContext *avctx, void *arg){
3596 H264Context *h = *(void**)arg;
3597 MpegEncContext * const s = &h->s;
3598 const int part_mask= s->partitioned_frame ? (ER_AC_END|ER_AC_ERROR) : 0x7F;
3599 int lf_x_start = s->mb_x;
3603 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3604 (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3606 if( h->pps.cabac ) {
3608 align_get_bits( &s->gb );
3611 ff_init_cabac_states( &h->cabac);
3612 ff_init_cabac_decoder( &h->cabac,
3613 s->gb.buffer + get_bits_count(&s->gb)/8,
3614 (get_bits_left(&s->gb) + 7)/8);
3616 ff_h264_init_cabac_states(h);
3620 int ret = ff_h264_decode_mb_cabac(h);
3622 //STOP_TIMER("decode_mb_cabac")
3624 if(ret>=0) ff_h264_hl_decode_mb(h);
3626 if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
3629 ret = ff_h264_decode_mb_cabac(h);
3631 if(ret>=0) ff_h264_hl_decode_mb(h);
3634 eos = get_cabac_terminate( &h->cabac );
3636 if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3637 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, ER_MB_END&part_mask);
3638 if (s->mb_x >= lf_x_start) loop_filter(h, lf_x_start, s->mb_x + 1);
3641 if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3642 av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
3643 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3647 if( ++s->mb_x >= s->mb_width ) {
3648 loop_filter(h, lf_x_start, s->mb_x);
3649 s->mb_x = lf_x_start = 0;
3650 decode_finish_row(h);
3652 if(FIELD_OR_MBAFF_PICTURE) {
3654 if(FRAME_MBAFF && s->mb_y < s->mb_height)
3655 predict_field_decoding_flag(h);
3659 if( eos || s->mb_y >= s->mb_height ) {
3660 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3661 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, ER_MB_END&part_mask);
3662 if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
3669 int ret = ff_h264_decode_mb_cavlc(h);
3671 if(ret>=0) ff_h264_hl_decode_mb(h);
3673 if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3675 ret = ff_h264_decode_mb_cavlc(h);
3677 if(ret>=0) ff_h264_hl_decode_mb(h);
3682 av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3683 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3687 if(++s->mb_x >= s->mb_width){
3688 loop_filter(h, lf_x_start, s->mb_x);
3689 s->mb_x = lf_x_start = 0;
3690 decode_finish_row(h);
3692 if(FIELD_OR_MBAFF_PICTURE) {
3694 if(FRAME_MBAFF && s->mb_y < s->mb_height)
3695 predict_field_decoding_flag(h);
3697 if(s->mb_y >= s->mb_height){
3698 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3700 if( get_bits_count(&s->gb) == s->gb.size_in_bits
3701 || get_bits_count(&s->gb) < s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3702 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, ER_MB_END&part_mask);
3706 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_END&part_mask);
3713 if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3714 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3715 if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3716 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, ER_MB_END&part_mask);
3717 if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
3721 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3731 * Call decode_slice() for each context.
3733 * @param h h264 master context
3734 * @param context_count number of contexts to execute
3736 static int execute_decode_slices(H264Context *h, int context_count){
3737 MpegEncContext * const s = &h->s;
3738 AVCodecContext * const avctx= s->avctx;
3742 if (s->avctx->hwaccel || s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3744 if(context_count == 1) {
3745 return decode_slice(avctx, &h);
3747 for(i = 1; i < context_count; i++) {
3748 hx = h->thread_context[i];
3749 hx->s.err_recognition = avctx->err_recognition;
3750 hx->s.error_count = 0;
3751 hx->x264_build= h->x264_build;
3754 avctx->execute(avctx, decode_slice,
3755 h->thread_context, NULL, context_count, sizeof(void*));
3757 /* pull back stuff from slices to master context */
3758 hx = h->thread_context[context_count - 1];
3759 s->mb_x = hx->s.mb_x;
3760 s->mb_y = hx->s.mb_y;
3761 s->dropable = hx->s.dropable;
3762 s->picture_structure = hx->s.picture_structure;
3763 for(i = 1; i < context_count; i++)
3764 h->s.error_count += h->thread_context[i]->s.error_count;
3771 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3772 MpegEncContext * const s = &h->s;
3773 AVCodecContext * const avctx= s->avctx;
3774 H264Context *hx; ///< thread context
3778 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3779 int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts
3782 h->nal_unit_type= 0;
3784 h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
3785 if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
3786 h->current_slice = 0;
3787 if (!s->first_field)
3788 s->current_picture_ptr= NULL;
3789 ff_h264_reset_sei(h);
3792 for(;pass <= 1;pass++){
3795 next_avc = h->is_avc ? 0 : buf_size;
3805 if(buf_index >= next_avc) {
3806 if (buf_index >= buf_size - h->nal_length_size) break;
3808 for(i = 0; i < h->nal_length_size; i++)
3809 nalsize = (nalsize << 8) | buf[buf_index++];
3810 if(nalsize <= 0 || nalsize > buf_size - buf_index){
3811 av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
3814 next_avc= buf_index + nalsize;
3816 // start code prefix search
3817 for(; buf_index + 3 < next_avc; buf_index++){
3818 // This should always succeed in the first iteration.
3819 if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
3823 if(buf_index+3 >= buf_size) break;
3826 if(buf_index >= next_avc) continue;
3829 hx = h->thread_context[context_count];
3831 ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
3832 if (ptr==NULL || dst_length < 0){
3835 i= buf_index + consumed;
3836 if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
3837 buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
3838 s->workaround_bugs |= FF_BUG_TRUNCATED;
3840 if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
3841 while(dst_length > 0 && ptr[dst_length - 1] == 0)
3844 bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
3846 if(s->avctx->debug&FF_DEBUG_STARTCODE){
3847 av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
3850 if (h->is_avc && (nalsize != consumed) && nalsize){
3851 av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
3854 buf_index += consumed;
3858 // packets can sometimes contain multiple PPS/SPS
3859 // e.g. two PAFF field pictures in one packet, or a demuxer which splits NALs strangely
3860 // if so, when frame threading we can't start the next thread until we've read all of them
3861 switch (hx->nal_unit_type) {
3864 nals_needed = nal_index;
3868 init_get_bits(&hx->s.gb, ptr, bit_length);
3869 if (!get_ue_golomb(&hx->s.gb))
3870 nals_needed = nal_index;
3875 //FIXME do not discard SEI id
3876 if(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
3881 switch(hx->nal_unit_type){
3883 if (h->nal_unit_type != NAL_IDR_SLICE) {
3884 av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices\n");
3887 idr(h); // FIXME ensure we don't lose some frames if there is reordering
3889 init_get_bits(&hx->s.gb, ptr, bit_length);
3891 hx->inter_gb_ptr= &hx->s.gb;
3892 hx->s.data_partitioning = 0;
3894 if((err = decode_slice_header(hx, h)))
3897 if ( h->sei_recovery_frame_cnt >= 0
3898 && ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
3899 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
3900 (1 << h->sps.log2_max_frame_num);
3903 s->current_picture_ptr->f.key_frame |=
3904 (hx->nal_unit_type == NAL_IDR_SLICE);
3906 if (h->recovery_frame == h->frame_num) {
3908 h->recovery_frame = -1;
3911 h->sync |= !!s->current_picture_ptr->f.key_frame;
3912 h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
3913 s->current_picture_ptr->sync = h->sync;
3915 if (h->current_slice == 1) {
3916 if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3917 decode_postinit(h, nal_index >= nals_needed);
3920 if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3922 if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3923 ff_vdpau_h264_picture_start(s);
3926 if(hx->redundant_pic_count==0
3927 && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3928 && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
3929 && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
3930 && avctx->skip_frame < AVDISCARD_ALL){
3931 if(avctx->hwaccel) {
3932 if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3935 if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3936 static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3937 ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3938 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3944 init_get_bits(&hx->s.gb, ptr, bit_length);
3946 hx->inter_gb_ptr= NULL;
3948 if ((err = decode_slice_header(hx, h)) < 0)
3951 hx->s.data_partitioning = 1;
3955 init_get_bits(&hx->intra_gb, ptr, bit_length);
3956 hx->intra_gb_ptr= &hx->intra_gb;
3959 init_get_bits(&hx->inter_gb, ptr, bit_length);
3960 hx->inter_gb_ptr= &hx->inter_gb;
3962 if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3963 && s->context_initialized
3964 && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3965 && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
3966 && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
3967 && avctx->skip_frame < AVDISCARD_ALL)
3971 init_get_bits(&s->gb, ptr, bit_length);
3972 ff_h264_decode_sei(h);
3975 init_get_bits(&s->gb, ptr, bit_length);
3976 if(ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)){
3977 av_log(h->s.avctx, AV_LOG_DEBUG, "SPS decoding failure, trying alternative mode\n");
3978 if(h->is_avc) av_assert0(next_avc - buf_index + consumed == nalsize);
3979 init_get_bits(&s->gb, &buf[buf_index + 1 - consumed], 8*(next_avc - buf_index + consumed));
3980 ff_h264_decode_seq_parameter_set(h);
3983 if (s->flags& CODEC_FLAG_LOW_DELAY ||
3984 (h->sps.bitstream_restriction_flag && !h->sps.num_reorder_frames))
3987 if(avctx->has_b_frames < 2)
3988 avctx->has_b_frames= !s->low_delay;
3991 init_get_bits(&s->gb, ptr, bit_length);
3993 ff_h264_decode_picture_parameter_set(h, bit_length);
3997 case NAL_END_SEQUENCE:
3998 case NAL_END_STREAM:
3999 case NAL_FILLER_DATA:
4001 case NAL_AUXILIARY_SLICE:
4004 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
4007 if(context_count == h->max_contexts) {
4008 execute_decode_slices(h, context_count);
4013 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4015 /* Slice could not be decoded in parallel mode, copy down
4016 * NAL unit stuff to context 0 and restart. Note that
4017 * rbsp_buffer is not transferred, but since we no longer
4018 * run in parallel mode this should not be an issue. */
4019 h->nal_unit_type = hx->nal_unit_type;
4020 h->nal_ref_idc = hx->nal_ref_idc;
4027 execute_decode_slices(h, context_count);
4032 * Return the number of bytes consumed for building the current frame.
4034 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
4035 if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
4036 if(pos+10>buf_size) pos=buf_size; // oops ;)
4041 static int decode_frame(AVCodecContext *avctx,
4042 void *data, int *data_size,
4045 const uint8_t *buf = avpkt->data;
4046 int buf_size = avpkt->size;
4047 H264Context *h = avctx->priv_data;
4048 MpegEncContext *s = &h->s;
4049 AVFrame *pict = data;
4054 s->flags= avctx->flags;
4055 s->flags2= avctx->flags2;
4057 /* end of stream, output what is still in the buffers */
4058 if (buf_size == 0) {
4061 s->current_picture_ptr = NULL;
4063 //FIXME factorize this with the output code below
4064 out = h->delayed_pic[0];
4066 for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
4067 if(h->delayed_pic[i]->poc < out->poc){
4068 out = h->delayed_pic[i];
4072 for(i=out_idx; h->delayed_pic[i]; i++)
4073 h->delayed_pic[i] = h->delayed_pic[i+1];
4076 *data_size = sizeof(AVFrame);
4077 *pict= *(AVFrame*)out;
4082 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4083 int cnt= buf[5]&0x1f;
4086 int nalsize= AV_RB16(p) + 2;
4087 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4095 int nalsize= AV_RB16(p) + 2;
4096 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4101 return ff_h264_decode_extradata(h, buf, buf_size);
4105 buf_index=decode_nal_units(h, buf, buf_size);
4109 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4110 av_assert0(buf_index <= buf_size);
4111 buf_size = buf_index;
4115 if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
4116 if (avctx->skip_frame >= AVDISCARD_NONREF ||
4117 buf_size >= 4 && !memcmp("Q264", buf, 4))
4119 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4123 if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
4125 if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h, 1);
4129 *data_size = 0; /* Wait for second field. */
4130 if (h->next_output_pic && h->next_output_pic->sync) {
4131 if(h->sync>1 || h->next_output_pic->f.pict_type != AV_PICTURE_TYPE_B){
4132 *data_size = sizeof(AVFrame);
4133 *pict = *(AVFrame*)h->next_output_pic;
4138 assert(pict->data[0] || !*data_size);
4139 ff_print_debug_info(s, pict);
4140 //printf("out %d\n", (int)pict->data[0]);
4142 return get_consumed_bytes(s, buf_index, buf_size);
4145 static inline void fill_mb_avail(H264Context *h){
4146 MpegEncContext * const s = &h->s;
4147 const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
4150 h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
4151 h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
4152 h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
4158 h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
4159 h->mb_avail[4]= 1; //FIXME move out
4160 h->mb_avail[5]= 0; //FIXME move out
4168 #define SIZE (COUNT*40)
4169 extern AVCodec ff_h264_decoder;
4175 // int int_temp[10000];
4177 AVCodecContext avctx;
4179 avcodec_get_context_defaults3(&avctx, &ff_h264_decoder);
4181 dsputil_init(&dsp, &avctx);
4183 init_put_bits(&pb, temp, SIZE);
4184 printf("testing unsigned exp golomb\n");
4185 for(i=0; i<COUNT; i++){
4187 set_ue_golomb(&pb, i);
4188 STOP_TIMER("set_ue_golomb");
4190 flush_put_bits(&pb);
4192 init_get_bits(&gb, temp, 8*SIZE);
4193 for(i=0; i<COUNT; i++){
4196 s= show_bits(&gb, 24);
4199 j= get_ue_golomb(&gb);
4201 printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4204 STOP_TIMER("get_ue_golomb");}
4208 init_put_bits(&pb, temp, SIZE);
4209 printf("testing signed exp golomb\n");
4210 for(i=0; i<COUNT; i++){
4212 set_se_golomb(&pb, i - COUNT/2);
4213 STOP_TIMER("set_se_golomb");
4215 flush_put_bits(&pb);
4217 init_get_bits(&gb, temp, 8*SIZE);
4218 for(i=0; i<COUNT; i++){
4221 s= show_bits(&gb, 24);
4224 j= get_se_golomb(&gb);
4225 if(j != i - COUNT/2){
4226 printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4229 STOP_TIMER("get_se_golomb");}
4232 printf("Testing RBSP\n");
4240 av_cold void ff_h264_free_context(H264Context *h)
4244 free_tables(h, 1); //FIXME cleanup init stuff perhaps
4246 for(i = 0; i < MAX_SPS_COUNT; i++)
4247 av_freep(h->sps_buffers + i);
4249 for(i = 0; i < MAX_PPS_COUNT; i++)
4250 av_freep(h->pps_buffers + i);
4253 av_cold int ff_h264_decode_end(AVCodecContext *avctx)
4255 H264Context *h = avctx->priv_data;
4256 MpegEncContext *s = &h->s;
4258 ff_h264_remove_all_refs(h);
4259 ff_h264_free_context(h);
4263 // memset(h, 0, sizeof(H264Context));
4268 static const AVProfile profiles[] = {
4269 { FF_PROFILE_H264_BASELINE, "Baseline" },
4270 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4271 { FF_PROFILE_H264_MAIN, "Main" },
4272 { FF_PROFILE_H264_EXTENDED, "Extended" },
4273 { FF_PROFILE_H264_HIGH, "High" },
4274 { FF_PROFILE_H264_HIGH_10, "High 10" },
4275 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4276 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4277 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4278 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4279 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4280 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4281 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4282 { FF_PROFILE_UNKNOWN },
4285 static const AVOption h264_options[] = {
4286 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
4287 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
4291 static const AVClass h264_class = {
4293 av_default_item_name,
4295 LIBAVUTIL_VERSION_INT,
4298 static const AVClass h264_vdpau_class = {
4299 "H264 VDPAU Decoder",
4300 av_default_item_name,
4302 LIBAVUTIL_VERSION_INT,
4305 AVCodec ff_h264_decoder = {
4307 .type = AVMEDIA_TYPE_VIDEO,
4308 .id = CODEC_ID_H264,
4309 .priv_data_size = sizeof(H264Context),
4310 .init = ff_h264_decode_init,
4311 .close = ff_h264_decode_end,
4312 .decode = decode_frame,
4313 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
4314 CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
4316 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4317 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4318 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4319 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4320 .priv_class = &h264_class,
4323 #if CONFIG_H264_VDPAU_DECODER
4324 AVCodec ff_h264_vdpau_decoder = {
4325 .name = "h264_vdpau",
4326 .type = AVMEDIA_TYPE_VIDEO,
4327 .id = CODEC_ID_H264,
4328 .priv_data_size = sizeof(H264Context),
4329 .init = ff_h264_decode_init,
4330 .close = ff_h264_decode_end,
4331 .decode = decode_frame,
4332 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4334 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4335 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
4336 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4337 .priv_class = &h264_vdpau_class,