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;
1319 if(MPV_frame_start(s, s->avctx) < 0)
1321 ff_er_frame_start(s);
1323 * MPV_frame_start uses pict_type to derive key_frame.
1324 * This is incorrect for H.264; IDR markings must be used.
1325 * Zero here; IDR markings per slice in frame or fields are ORed in later.
1326 * See decode_nal_units().
1328 s->current_picture_ptr->f.key_frame = 0;
1329 s->current_picture_ptr->sync = 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 < s->slice_context_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);
2079 } else if (CONFIG_SVQ3_DECODER) {
2080 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]);
2081 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]);
2083 for(i=j*16; i<j*16+4; i++){
2084 if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2085 uint8_t * const ptr= dest[j-1] + block_offset[i];
2086 ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
2094 if(h->cbp || IS_INTRA(mb_type))
2096 s->dsp.clear_blocks(h->mb);
2097 s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2101 static av_always_inline void hl_decode_mb_444_internal(H264Context *h, int simple, int pixel_shift){
2102 MpegEncContext * const s = &h->s;
2103 const int mb_x= s->mb_x;
2104 const int mb_y= s->mb_y;
2105 const int mb_xy= h->mb_xy;
2106 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2110 int *block_offset = &h->block_offset[0];
2111 const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2112 const int plane_count = (simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) ? 3 : 1;
2114 for (p = 0; p < plane_count; p++)
2116 dest[p] = s->current_picture.f.data[p] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2117 s->dsp.prefetch(dest[p] + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
2120 h->list_counts[mb_xy]= h->list_count;
2122 if (!simple && MB_FIELD) {
2123 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2124 block_offset = &h->block_offset[48];
2125 if(mb_y&1) //FIXME move out of this function?
2126 for (p = 0; p < 3; p++)
2127 dest[p] -= s->linesize*15;
2130 for(list=0; list<h->list_count; list++){
2131 if(!USES_LIST(mb_type, list))
2133 if(IS_16X16(mb_type)){
2134 int8_t *ref = &h->ref_cache[list][scan8[0]];
2135 fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2137 for(i=0; i<16; i+=4){
2138 int ref = h->ref_cache[list][scan8[i]];
2140 fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2146 linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2149 if (!simple && IS_INTRA_PCM(mb_type)) {
2151 const int bit_depth = h->sps.bit_depth_luma;
2153 init_get_bits(&gb, (uint8_t*)h->mb, 768*bit_depth);
2155 for (p = 0; p < plane_count; p++) {
2156 for (i = 0; i < 16; i++) {
2157 uint16_t *tmp = (uint16_t*)(dest[p] + i*linesize);
2158 for (j = 0; j < 16; j++)
2159 tmp[j] = get_bits(&gb, bit_depth);
2163 for (p = 0; p < plane_count; p++) {
2164 for (i = 0; i < 16; i++) {
2165 memcpy(dest[p] + i*linesize, h->mb + p*128 + i*8, 16);
2170 if(IS_INTRA(mb_type)){
2171 if(h->deblocking_filter)
2172 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 1, 1, simple, pixel_shift);
2174 for (p = 0; p < plane_count; p++)
2175 hl_decode_mb_predict_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2177 if(h->deblocking_filter)
2178 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 0, 1, simple, pixel_shift);
2180 hl_motion(h, dest[0], dest[1], dest[2],
2181 s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2182 s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2183 h->h264dsp.weight_h264_pixels_tab,
2184 h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
2187 for (p = 0; p < plane_count; p++)
2188 hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2190 if(h->cbp || IS_INTRA(mb_type))
2192 s->dsp.clear_blocks(h->mb);
2193 s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2198 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2200 #define hl_decode_mb_simple(sh, bits) \
2201 static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
2202 hl_decode_mb_internal(h, 1, sh); \
2204 hl_decode_mb_simple(0, 8)
2205 hl_decode_mb_simple(1, 16)
2208 * Process a macroblock; this handles edge cases, such as interlacing.
2210 static void av_noinline hl_decode_mb_complex(H264Context *h){
2211 hl_decode_mb_internal(h, 0, h->pixel_shift);
2214 static void av_noinline hl_decode_mb_444_complex(H264Context *h){
2215 hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2218 static void av_noinline hl_decode_mb_444_simple(H264Context *h){
2219 hl_decode_mb_444_internal(h, 1, 0);
2222 void ff_h264_hl_decode_mb(H264Context *h){
2223 MpegEncContext * const s = &h->s;
2224 const int mb_xy= h->mb_xy;
2225 const int mb_type = s->current_picture.f.mb_type[mb_xy];
2226 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2229 if(is_complex || h->pixel_shift)
2230 hl_decode_mb_444_complex(h);
2232 hl_decode_mb_444_simple(h);
2233 } else if (is_complex) {
2234 hl_decode_mb_complex(h);
2235 } else if (h->pixel_shift) {
2236 hl_decode_mb_simple_16(h);
2238 hl_decode_mb_simple_8(h);
2241 static int pred_weight_table(H264Context *h){
2242 MpegEncContext * const s = &h->s;
2244 int luma_def, chroma_def;
2247 h->use_weight_chroma= 0;
2248 h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2249 if(h->sps.chroma_format_idc)
2250 h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2251 luma_def = 1<<h->luma_log2_weight_denom;
2252 chroma_def = 1<<h->chroma_log2_weight_denom;
2254 for(list=0; list<2; list++){
2255 h->luma_weight_flag[list] = 0;
2256 h->chroma_weight_flag[list] = 0;
2257 for(i=0; i<h->ref_count[list]; i++){
2258 int luma_weight_flag, chroma_weight_flag;
2260 luma_weight_flag= get_bits1(&s->gb);
2261 if(luma_weight_flag){
2262 h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
2263 h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
2264 if( h->luma_weight[i][list][0] != luma_def
2265 || h->luma_weight[i][list][1] != 0) {
2267 h->luma_weight_flag[list]= 1;
2270 h->luma_weight[i][list][0]= luma_def;
2271 h->luma_weight[i][list][1]= 0;
2274 if(h->sps.chroma_format_idc){
2275 chroma_weight_flag= get_bits1(&s->gb);
2276 if(chroma_weight_flag){
2279 h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
2280 h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
2281 if( h->chroma_weight[i][list][j][0] != chroma_def
2282 || h->chroma_weight[i][list][j][1] != 0) {
2283 h->use_weight_chroma= 1;
2284 h->chroma_weight_flag[list]= 1;
2290 h->chroma_weight[i][list][j][0]= chroma_def;
2291 h->chroma_weight[i][list][j][1]= 0;
2296 if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
2298 h->use_weight= h->use_weight || h->use_weight_chroma;
2303 * Initialize implicit_weight table.
2304 * @param field 0/1 initialize the weight for interlaced MBAFF
2305 * -1 initializes the rest
2307 static void implicit_weight_table(H264Context *h, int field){
2308 MpegEncContext * const s = &h->s;
2309 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2311 for (i = 0; i < 2; i++) {
2312 h->luma_weight_flag[i] = 0;
2313 h->chroma_weight_flag[i] = 0;
2317 if (s->picture_structure == PICT_FRAME) {
2318 cur_poc = s->current_picture_ptr->poc;
2320 cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2322 if( h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
2323 && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
2325 h->use_weight_chroma= 0;
2329 ref_count0= h->ref_count[0];
2330 ref_count1= h->ref_count[1];
2332 cur_poc = s->current_picture_ptr->field_poc[field];
2334 ref_count0= 16+2*h->ref_count[0];
2335 ref_count1= 16+2*h->ref_count[1];
2339 h->use_weight_chroma= 2;
2340 h->luma_log2_weight_denom= 5;
2341 h->chroma_log2_weight_denom= 5;
2343 for(ref0=ref_start; ref0 < ref_count0; ref0++){
2344 int poc0 = h->ref_list[0][ref0].poc;
2345 for(ref1=ref_start; ref1 < ref_count1; ref1++){
2347 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2348 int poc1 = h->ref_list[1][ref1].poc;
2349 int td = av_clip(poc1 - poc0, -128, 127);
2351 int tb = av_clip(cur_poc - poc0, -128, 127);
2352 int tx = (16384 + (FFABS(td) >> 1)) / td;
2353 int dist_scale_factor = (tb*tx + 32) >> 8;
2354 if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
2355 w = 64 - dist_scale_factor;
2359 h->implicit_weight[ref0][ref1][0]=
2360 h->implicit_weight[ref0][ref1][1]= w;
2362 h->implicit_weight[ref0][ref1][field]=w;
2369 * instantaneous decoder refresh.
2371 static void idr(H264Context *h){
2373 ff_h264_remove_all_refs(h);
2374 h->prev_frame_num= 0;
2375 h->prev_frame_num_offset= 0;
2376 h->prev_poc_msb= 1<<16;
2378 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2379 h->last_pocs[i] = INT_MIN;
2382 /* forget old pics after a seek */
2383 static void flush_dpb(AVCodecContext *avctx){
2384 H264Context *h= avctx->priv_data;
2386 for(i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2387 if(h->delayed_pic[i])
2388 h->delayed_pic[i]->f.reference = 0;
2389 h->delayed_pic[i]= NULL;
2391 h->outputed_poc=h->next_outputed_poc= INT_MIN;
2392 h->prev_interlaced_frame = 1;
2394 h->prev_frame_num= -1;
2395 if(h->s.current_picture_ptr)
2396 h->s.current_picture_ptr->f.reference = 0;
2397 h->s.first_field= 0;
2398 ff_h264_reset_sei(h);
2399 ff_mpeg_flush(avctx);
2400 h->recovery_frame= -1;
2404 static int init_poc(H264Context *h){
2405 MpegEncContext * const s = &h->s;
2406 const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2408 Picture *cur = s->current_picture_ptr;
2410 h->frame_num_offset= h->prev_frame_num_offset;
2411 if(h->frame_num < h->prev_frame_num)
2412 h->frame_num_offset += max_frame_num;
2414 if(h->sps.poc_type==0){
2415 const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2417 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2418 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2419 else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2420 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2422 h->poc_msb = h->prev_poc_msb;
2423 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2425 field_poc[1] = h->poc_msb + h->poc_lsb;
2426 if(s->picture_structure == PICT_FRAME)
2427 field_poc[1] += h->delta_poc_bottom;
2428 }else if(h->sps.poc_type==1){
2429 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2432 if(h->sps.poc_cycle_length != 0)
2433 abs_frame_num = h->frame_num_offset + h->frame_num;
2437 if(h->nal_ref_idc==0 && abs_frame_num > 0)
2440 expected_delta_per_poc_cycle = 0;
2441 for(i=0; i < h->sps.poc_cycle_length; i++)
2442 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2444 if(abs_frame_num > 0){
2445 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2446 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2448 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2449 for(i = 0; i <= frame_num_in_poc_cycle; i++)
2450 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2454 if(h->nal_ref_idc == 0)
2455 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2457 field_poc[0] = expectedpoc + h->delta_poc[0];
2458 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2460 if(s->picture_structure == PICT_FRAME)
2461 field_poc[1] += h->delta_poc[1];
2463 int poc= 2*(h->frame_num_offset + h->frame_num);
2472 if(s->picture_structure != PICT_BOTTOM_FIELD)
2473 s->current_picture_ptr->field_poc[0]= field_poc[0];
2474 if(s->picture_structure != PICT_TOP_FIELD)
2475 s->current_picture_ptr->field_poc[1]= field_poc[1];
2476 cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2483 * initialize scan tables
2485 static void init_scan_tables(H264Context *h){
2487 for(i=0; i<16; i++){
2488 #define T(x) (x>>2) | ((x<<2) & 0xF)
2489 h->zigzag_scan[i] = T(zigzag_scan[i]);
2490 h-> field_scan[i] = T( field_scan[i]);
2493 for(i=0; i<64; i++){
2494 #define T(x) (x>>3) | ((x&7)<<3)
2495 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2496 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2497 h->field_scan8x8[i] = T(field_scan8x8[i]);
2498 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2501 if(h->sps.transform_bypass){ //FIXME same ugly
2502 h->zigzag_scan_q0 = zigzag_scan;
2503 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2504 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2505 h->field_scan_q0 = field_scan;
2506 h->field_scan8x8_q0 = field_scan8x8;
2507 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2509 h->zigzag_scan_q0 = h->zigzag_scan;
2510 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2511 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2512 h->field_scan_q0 = h->field_scan;
2513 h->field_scan8x8_q0 = h->field_scan8x8;
2514 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2518 static int field_end(H264Context *h, int in_setup){
2519 MpegEncContext * const s = &h->s;
2520 AVCodecContext * const avctx= s->avctx;
2524 if (!in_setup && !s->dropable)
2525 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2526 s->picture_structure==PICT_BOTTOM_FIELD);
2528 if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2529 ff_vdpau_h264_set_reference_frames(s);
2531 if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2533 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2534 h->prev_poc_msb= h->poc_msb;
2535 h->prev_poc_lsb= h->poc_lsb;
2537 h->prev_frame_num_offset= h->frame_num_offset;
2538 h->prev_frame_num= h->frame_num;
2539 h->outputed_poc = h->next_outputed_poc;
2542 if (avctx->hwaccel) {
2543 if (avctx->hwaccel->end_frame(avctx) < 0)
2544 av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2547 if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2548 ff_vdpau_h264_picture_complete(s);
2551 * FIXME: Error handling code does not seem to support interlaced
2552 * when slices span multiple rows
2553 * The ff_er_add_slice calls don't work right for bottom
2554 * fields; they cause massive erroneous error concealing
2555 * Error marking covers both fields (top and bottom).
2556 * This causes a mismatched s->error_count
2557 * and a bad error table. Further, the error count goes to
2558 * INT_MAX when called for bottom field, because mb_y is
2559 * past end by one (callers fault) and resync_mb_y != 0
2560 * causes problems for the first MB line, too.
2573 * Replicate H264 "master" context to thread contexts.
2575 static void clone_slice(H264Context *dst, H264Context *src)
2577 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2578 dst->s.current_picture_ptr = src->s.current_picture_ptr;
2579 dst->s.current_picture = src->s.current_picture;
2580 dst->s.linesize = src->s.linesize;
2581 dst->s.uvlinesize = src->s.uvlinesize;
2582 dst->s.first_field = src->s.first_field;
2584 dst->prev_poc_msb = src->prev_poc_msb;
2585 dst->prev_poc_lsb = src->prev_poc_lsb;
2586 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2587 dst->prev_frame_num = src->prev_frame_num;
2588 dst->short_ref_count = src->short_ref_count;
2590 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2591 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2592 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2593 memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
2595 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2596 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2600 * Compute profile from profile_idc and constraint_set?_flags.
2604 * @return profile as defined by FF_PROFILE_H264_*
2606 int ff_h264_get_profile(SPS *sps)
2608 int profile = sps->profile_idc;
2610 switch(sps->profile_idc) {
2611 case FF_PROFILE_H264_BASELINE:
2612 // constraint_set1_flag set to 1
2613 profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2615 case FF_PROFILE_H264_HIGH_10:
2616 case FF_PROFILE_H264_HIGH_422:
2617 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2618 // constraint_set3_flag set to 1
2619 profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2627 * Decode a slice header.
2628 * This will also call MPV_common_init() and frame_start() as needed.
2630 * @param h h264context
2631 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2633 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2635 static int decode_slice_header(H264Context *h, H264Context *h0){
2636 MpegEncContext * const s = &h->s;
2637 MpegEncContext * const s0 = &h0->s;
2638 unsigned int first_mb_in_slice;
2639 unsigned int pps_id;
2640 int num_ref_idx_active_override_flag;
2641 unsigned int slice_type, tmp, i, j;
2642 int default_ref_list_done = 0;
2643 int last_pic_structure;
2645 s->dropable= h->nal_ref_idc == 0;
2647 /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2648 if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
2649 s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2650 s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2652 s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2653 s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2656 first_mb_in_slice= get_ue_golomb_long(&s->gb);
2658 if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2659 if(h0->current_slice && FIELD_PICTURE){
2663 h0->current_slice = 0;
2664 if (!s0->first_field)
2665 s->current_picture_ptr= NULL;
2668 slice_type= get_ue_golomb_31(&s->gb);
2670 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);
2675 h->slice_type_fixed=1;
2677 h->slice_type_fixed=0;
2679 slice_type= golomb_to_pict_type[ slice_type ];
2680 if (slice_type == AV_PICTURE_TYPE_I
2681 || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2682 default_ref_list_done = 1;
2684 h->slice_type= slice_type;
2685 h->slice_type_nos= slice_type & 3;
2687 s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2689 pps_id= get_ue_golomb(&s->gb);
2690 if(pps_id>=MAX_PPS_COUNT){
2691 av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2694 if(!h0->pps_buffers[pps_id]) {
2695 av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2698 h->pps= *h0->pps_buffers[pps_id];
2700 if(!h0->sps_buffers[h->pps.sps_id]) {
2701 av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2704 h->sps = *h0->sps_buffers[h->pps.sps_id];
2706 s->avctx->profile = ff_h264_get_profile(&h->sps);
2707 s->avctx->level = h->sps.level_idc;
2708 s->avctx->refs = h->sps.ref_frame_count;
2710 if(h == h0 && h->dequant_coeff_pps != pps_id){
2711 h->dequant_coeff_pps = pps_id;
2712 init_dequant_tables(h);
2715 s->mb_width= h->sps.mb_width;
2716 s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2718 h->b_stride= s->mb_width*4;
2720 s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2722 s->width = 16*s->mb_width;
2723 s->height= 16*s->mb_height;
2725 if (s->context_initialized
2726 && ( s->width != s->avctx->coded_width || s->height != s->avctx->coded_height
2727 || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2728 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2729 || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2731 av_log_missing_feature(s->avctx, "Width/height/bit depth/chroma idc changing with threads is", 0);
2732 return -1; // width / height changed during parallelized decoding
2735 flush_dpb(s->avctx);
2739 if (!s->context_initialized) {
2741 av_log(h->s.avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n");
2744 avcodec_set_dimensions(s->avctx, s->width, s->height);
2745 s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2746 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);
2747 s->avctx->sample_aspect_ratio= h->sps.sar;
2748 av_assert0(s->avctx->sample_aspect_ratio.den);
2750 if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2751 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2752 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10 &&
2753 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2754 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2755 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2756 h->pixel_shift = h->sps.bit_depth_luma > 8;
2758 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2759 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2760 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2761 dsputil_init(&s->dsp, s->avctx);
2763 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2764 h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2769 if(h->sps.video_signal_type_present_flag){
2770 s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2771 if(h->sps.colour_description_present_flag){
2772 s->avctx->color_primaries = h->sps.color_primaries;
2773 s->avctx->color_trc = h->sps.color_trc;
2774 s->avctx->colorspace = h->sps.colorspace;
2778 if(h->sps.timing_info_present_flag){
2779 int64_t den= h->sps.time_scale;
2780 if(h->x264_build < 44U)
2782 av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2783 h->sps.num_units_in_tick, den, 1<<30);
2786 switch (h->sps.bit_depth_luma) {
2789 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2790 s->avctx->pix_fmt = PIX_FMT_GBRP9;
2792 s->avctx->pix_fmt = PIX_FMT_YUV444P9;
2793 } else if (CHROMA422)
2794 s->avctx->pix_fmt = PIX_FMT_YUV422P9;
2796 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2800 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2801 s->avctx->pix_fmt = PIX_FMT_GBRP10;
2803 s->avctx->pix_fmt = PIX_FMT_YUV444P10;
2804 } else if (CHROMA422)
2805 s->avctx->pix_fmt = PIX_FMT_YUV422P10;
2807 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2811 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P : PIX_FMT_YUV444P;
2812 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2813 s->avctx->pix_fmt = PIX_FMT_GBR24P;
2814 av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2815 } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2816 av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2818 } else if (CHROMA422) {
2819 s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P : PIX_FMT_YUV422P;
2821 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2822 s->avctx->codec->pix_fmts ?
2823 s->avctx->codec->pix_fmts :
2824 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2825 hwaccel_pixfmt_list_h264_jpeg_420 :
2826 ff_hwaccel_pixfmt_list_420);
2830 s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2832 if (MPV_common_init(s) < 0) {
2833 av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed.\n");
2837 h->prev_interlaced_frame = 1;
2839 init_scan_tables(h);
2840 if (ff_h264_alloc_tables(h) < 0) {
2841 av_log(h->s.avctx, AV_LOG_ERROR, "Could not allocate memory for h264\n");
2842 return AVERROR(ENOMEM);
2845 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2846 if (context_init(h) < 0) {
2847 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2851 for(i = 1; i < s->slice_context_count; i++) {
2853 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2854 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2855 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2856 c->h264dsp = h->h264dsp;
2859 c->pixel_shift = h->pixel_shift;
2860 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2861 init_scan_tables(c);
2862 clone_tables(c, h, i);
2865 for(i = 0; i < s->slice_context_count; i++)
2866 if (context_init(h->thread_context[i]) < 0) {
2867 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2873 h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2876 h->mb_aff_frame = 0;
2877 last_pic_structure = s0->picture_structure;
2878 if(h->sps.frame_mbs_only_flag){
2879 s->picture_structure= PICT_FRAME;
2881 if(!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B){
2882 av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2885 if(get_bits1(&s->gb)) { //field_pic_flag
2886 s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2888 s->picture_structure= PICT_FRAME;
2889 h->mb_aff_frame = h->sps.mb_aff;
2892 h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2894 if(h0->current_slice == 0){
2895 // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
2896 if(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2897 int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
2899 if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
2901 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2902 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2903 if (unwrap_prev_frame_num < 0)
2904 unwrap_prev_frame_num += max_frame_num;
2906 h->prev_frame_num = unwrap_prev_frame_num;
2910 while(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
2911 h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2912 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2913 av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2914 if (ff_h264_frame_start(h) < 0)
2916 h->prev_frame_num++;
2917 h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2918 s->current_picture_ptr->frame_num= h->prev_frame_num;
2919 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2920 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2921 ff_generate_sliding_window_mmcos(h);
2922 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2923 (s->avctx->err_recognition & AV_EF_EXPLODE))
2924 return AVERROR_INVALIDDATA;
2925 /* Error concealment: if a ref is missing, copy the previous ref in its place.
2926 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2927 * about there being no actual duplicates.
2928 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
2929 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2931 if (h->short_ref_count) {
2933 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2934 (const uint8_t**)prev->f.data, prev->f.linesize,
2935 s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2936 h->short_ref[0]->poc = prev->poc+2;
2938 h->short_ref[0]->frame_num = h->prev_frame_num;
2942 /* See if we have a decoded first field looking for a pair... */
2943 if (s0->first_field) {
2944 assert(s0->current_picture_ptr);
2945 assert(s0->current_picture_ptr->f.data[0]);
2946 assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2948 /* figure out if we have a complementary field pair */
2949 if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2951 * Previous field is unmatched. Don't display it, but let it
2952 * remain for reference if marked as such.
2954 s0->current_picture_ptr = NULL;
2955 s0->first_field = FIELD_PICTURE;
2958 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2960 * This and previous field had
2961 * different frame_nums. Consider this field first in
2962 * pair. Throw away previous field except for reference
2965 s0->first_field = 1;
2966 s0->current_picture_ptr = NULL;
2969 /* Second field in complementary pair */
2970 s0->first_field = 0;
2975 /* Frame or first field in a potentially complementary pair */
2976 assert(!s0->current_picture_ptr);
2977 s0->first_field = FIELD_PICTURE;
2980 if(!FIELD_PICTURE || s0->first_field) {
2981 if (ff_h264_frame_start(h) < 0) {
2982 s0->first_field = 0;
2986 ff_release_unused_pictures(s, 0);
2992 s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2994 assert(s->mb_num == s->mb_width * s->mb_height);
2995 if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2996 first_mb_in_slice >= s->mb_num){
2997 av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3000 s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3001 s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3002 if (s->picture_structure == PICT_BOTTOM_FIELD)
3003 s->resync_mb_y = s->mb_y = s->mb_y + 1;
3004 assert(s->mb_y < s->mb_height);
3006 if(s->picture_structure==PICT_FRAME){
3007 h->curr_pic_num= h->frame_num;
3008 h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3010 h->curr_pic_num= 2*h->frame_num + 1;
3011 h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3014 if(h->nal_unit_type == NAL_IDR_SLICE){
3015 get_ue_golomb(&s->gb); /* idr_pic_id */
3018 if(h->sps.poc_type==0){
3019 h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3021 if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3022 h->delta_poc_bottom= get_se_golomb(&s->gb);
3026 if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3027 h->delta_poc[0]= get_se_golomb(&s->gb);
3029 if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3030 h->delta_poc[1]= get_se_golomb(&s->gb);
3035 if(h->pps.redundant_pic_cnt_present){
3036 h->redundant_pic_count= get_ue_golomb(&s->gb);
3039 //set defaults, might be overridden a few lines later
3040 h->ref_count[0]= h->pps.ref_count[0];
3041 h->ref_count[1]= h->pps.ref_count[1];
3043 if(h->slice_type_nos != AV_PICTURE_TYPE_I){
3044 unsigned max= (16<<(s->picture_structure != PICT_FRAME))-1;
3045 if(h->slice_type_nos == AV_PICTURE_TYPE_B){
3046 h->direct_spatial_mv_pred= get_bits1(&s->gb);
3048 num_ref_idx_active_override_flag= get_bits1(&s->gb);
3050 if(num_ref_idx_active_override_flag){
3051 h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3052 if(h->slice_type_nos==AV_PICTURE_TYPE_B)
3053 h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3056 if(h->ref_count[0]-1 > max || h->ref_count[1]-1 > max){
3057 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3058 h->ref_count[0]= h->ref_count[1]= 1;
3061 if(h->slice_type_nos == AV_PICTURE_TYPE_B)
3066 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3068 if(!default_ref_list_done){
3069 ff_h264_fill_default_ref_list(h);
3072 if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3073 h->ref_count[1]= h->ref_count[0]= 0;
3077 if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
3078 s->last_picture_ptr= &h->ref_list[0][0];
3079 ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3081 if(h->slice_type_nos==AV_PICTURE_TYPE_B){
3082 s->next_picture_ptr= &h->ref_list[1][0];
3083 ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3086 if( (h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P )
3087 || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
3088 pred_weight_table(h);
3089 else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3090 implicit_weight_table(h, -1);
3093 for (i = 0; i < 2; i++) {
3094 h->luma_weight_flag[i] = 0;
3095 h->chroma_weight_flag[i] = 0;
3099 if(h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3100 (s->avctx->err_recognition & AV_EF_EXPLODE))
3101 return AVERROR_INVALIDDATA;
3104 ff_h264_fill_mbaff_ref_list(h);
3106 if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3107 implicit_weight_table(h, 0);
3108 implicit_weight_table(h, 1);
3112 if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3113 ff_h264_direct_dist_scale_factor(h);
3114 ff_h264_direct_ref_list_init(h);
3116 if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
3117 tmp = get_ue_golomb_31(&s->gb);
3119 av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3122 h->cabac_init_idc= tmp;
3125 h->last_qscale_diff = 0;
3126 tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3127 if(tmp>51+6*(h->sps.bit_depth_luma-8)){
3128 av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3132 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3133 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3134 //FIXME qscale / qp ... stuff
3135 if(h->slice_type == AV_PICTURE_TYPE_SP){
3136 get_bits1(&s->gb); /* sp_for_switch_flag */
3138 if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
3139 get_se_golomb(&s->gb); /* slice_qs_delta */
3142 h->deblocking_filter = 1;
3143 h->slice_alpha_c0_offset = 52;
3144 h->slice_beta_offset = 52;
3145 if( h->pps.deblocking_filter_parameters_present ) {
3146 tmp= get_ue_golomb_31(&s->gb);
3148 av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
3151 h->deblocking_filter= tmp;
3152 if(h->deblocking_filter < 2)
3153 h->deblocking_filter^= 1; // 1<->0
3155 if( h->deblocking_filter ) {
3156 h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3157 h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
3158 if( h->slice_alpha_c0_offset > 104U
3159 || h->slice_beta_offset > 104U){
3160 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);
3166 if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
3167 ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
3168 ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B)
3169 ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
3170 h->deblocking_filter= 0;
3172 if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
3173 if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
3174 /* Cheat slightly for speed:
3175 Do not bother to deblock across slices. */
3176 h->deblocking_filter = 2;
3178 h0->max_contexts = 1;
3179 if(!h0->single_decode_warning) {
3180 av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3181 h0->single_decode_warning = 1;
3184 av_log(h->s.avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n");
3189 h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset)
3190 - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1])
3191 + 6 * (h->sps.bit_depth_luma - 8);
3194 if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3195 slice_group_change_cycle= get_bits(&s->gb, ?);
3198 h0->last_slice_type = slice_type;
3199 h->slice_num = ++h0->current_slice;
3202 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3203 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3204 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3205 && h->slice_num >= MAX_SLICES) {
3206 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3207 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);
3212 int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
3213 for(i=0; i<16; i++){
3215 if (h->ref_list[j][i].f.data[0]) {
3217 uint8_t *base = h->ref_list[j][i].f.base[0];
3218 for(k=0; k<h->short_ref_count; k++)
3219 if (h->short_ref[k]->f.base[0] == base) {
3223 for(k=0; k<h->long_ref_count; k++)
3224 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3225 id_list[i]= h->short_ref_count + k;
3234 ref2frm[i+2]= 4*id_list[i]
3235 + (h->ref_list[j][i].f.reference & 3);
3238 for(i=16; i<48; i++)
3239 ref2frm[i+4]= 4*id_list[(i-16)>>1]
3240 + (h->ref_list[j][i].f.reference & 3);
3243 //FIXME: fix draw_edges+PAFF+frame threads
3244 h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
3245 h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3247 if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3248 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",
3250 (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
3252 av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3253 pps_id, h->frame_num,
3254 s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3255 h->ref_count[0], h->ref_count[1],
3257 h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
3259 h->use_weight==1 && h->use_weight_chroma ? "c" : "",
3260 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
3267 int ff_h264_get_slice_type(const H264Context *h)
3269 switch (h->slice_type) {
3270 case AV_PICTURE_TYPE_P: return 0;
3271 case AV_PICTURE_TYPE_B: return 1;
3272 case AV_PICTURE_TYPE_I: return 2;
3273 case AV_PICTURE_TYPE_SP: return 3;
3274 case AV_PICTURE_TYPE_SI: return 4;
3279 static av_always_inline void fill_filter_caches_inter(H264Context *h, MpegEncContext * const s, int mb_type, int top_xy,
3280 int left_xy[LEFT_MBS], int top_type, int left_type[LEFT_MBS], int mb_xy, int list)
3282 int b_stride = h->b_stride;
3283 int16_t (*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3284 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3285 if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
3286 if(USES_LIST(top_type, list)){
3287 const int b_xy= h->mb2b_xy[top_xy] + 3*b_stride;
3288 const int b8_xy= 4*top_xy + 2;
3289 int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3290 AV_COPY128(mv_dst - 1*8, s->current_picture.f.motion_val[list][b_xy + 0]);
3292 ref_cache[1 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3294 ref_cache[3 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3296 AV_ZERO128(mv_dst - 1*8);
3297 AV_WN32A(&ref_cache[0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3300 if(!IS_INTERLACED(mb_type^left_type[LTOP])){
3301 if(USES_LIST(left_type[LTOP], list)){
3302 const int b_xy= h->mb2b_xy[left_xy[LTOP]] + 3;
3303 const int b8_xy= 4*left_xy[LTOP] + 1;
3304 int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[LTOP]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3305 AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride*0]);
3306 AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride*1]);
3307 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride*2]);
3308 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride*3]);
3310 ref_cache[-1 + 8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*0]];
3312 ref_cache[-1 + 24]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*1]];
3314 AV_ZERO32(mv_dst - 1 + 0);
3315 AV_ZERO32(mv_dst - 1 + 8);
3316 AV_ZERO32(mv_dst - 1 +16);
3317 AV_ZERO32(mv_dst - 1 +24);
3321 ref_cache[-1 + 24]= LIST_NOT_USED;
3326 if(!USES_LIST(mb_type, list)){
3327 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0,0), 4);
3328 AV_WN32A(&ref_cache[0*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3329 AV_WN32A(&ref_cache[1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3330 AV_WN32A(&ref_cache[2*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3331 AV_WN32A(&ref_cache[3*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3336 int8_t *ref = &s->current_picture.f.ref_index[list][4*mb_xy];
3337 int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3338 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101;
3339 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]],ref2frm[list][ref[3]])&0x00FF00FF)*0x0101;
3340 AV_WN32A(&ref_cache[0*8], ref01);
3341 AV_WN32A(&ref_cache[1*8], ref01);
3342 AV_WN32A(&ref_cache[2*8], ref23);
3343 AV_WN32A(&ref_cache[3*8], ref23);
3347 int16_t (*mv_src)[2] = &s->current_picture.f.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
3348 AV_COPY128(mv_dst + 8*0, mv_src + 0*b_stride);
3349 AV_COPY128(mv_dst + 8*1, mv_src + 1*b_stride);
3350 AV_COPY128(mv_dst + 8*2, mv_src + 2*b_stride);
3351 AV_COPY128(mv_dst + 8*3, mv_src + 3*b_stride);
3357 * @return non zero if the loop filter can be skipped
3359 static int fill_filter_caches(H264Context *h, int mb_type){
3360 MpegEncContext * const s = &h->s;
3361 const int mb_xy= h->mb_xy;
3362 int top_xy, left_xy[LEFT_MBS];
3363 int top_type, left_type[LEFT_MBS];
3367 top_xy = mb_xy - (s->mb_stride << MB_FIELD);
3369 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3370 * stuff, I can't imagine that these complex rules are worth it. */
3372 left_xy[LBOT] = left_xy[LTOP] = mb_xy-1;
3374 const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3375 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3377 if (left_mb_field_flag != curr_mb_field_flag) {
3378 left_xy[LTOP] -= s->mb_stride;
3381 if(curr_mb_field_flag){
3382 top_xy += s->mb_stride & (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3384 if (left_mb_field_flag != curr_mb_field_flag) {
3385 left_xy[LBOT] += s->mb_stride;
3390 h->top_mb_xy = top_xy;
3391 h->left_mb_xy[LTOP] = left_xy[LTOP];
3392 h->left_mb_xy[LBOT] = left_xy[LBOT];
3394 //for sufficiently low qp, filtering wouldn't do anything
3395 //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
3396 int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
3397 int qp = s->current_picture.f.qscale_table[mb_xy];
3399 && (left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh)
3400 && (top_xy < 0 || ((qp + s->current_picture.f.qscale_table[top_xy ] + 1) >> 1) <= qp_thresh)) {
3403 if ((left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LBOT] ] + 1) >> 1) <= qp_thresh) &&
3404 (top_xy < s->mb_stride || ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3409 top_type = s->current_picture.f.mb_type[top_xy];
3410 left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3411 left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3412 if(h->deblocking_filter == 2){
3413 if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
3414 if(h->slice_table[left_xy[LBOT]] != h->slice_num) left_type[LTOP]= left_type[LBOT]= 0;
3416 if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
3417 if(h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP]= left_type[LBOT] =0;
3419 h->top_type = top_type;
3420 h->left_type[LTOP]= left_type[LTOP];
3421 h->left_type[LBOT]= left_type[LBOT];
3423 if(IS_INTRA(mb_type))
3426 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0);
3427 if(h->list_count == 2)
3428 fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1);
3430 nnz = h->non_zero_count[mb_xy];
3431 nnz_cache = h->non_zero_count_cache;
3432 AV_COPY32(&nnz_cache[4+8*1], &nnz[ 0]);
3433 AV_COPY32(&nnz_cache[4+8*2], &nnz[ 4]);
3434 AV_COPY32(&nnz_cache[4+8*3], &nnz[ 8]);
3435 AV_COPY32(&nnz_cache[4+8*4], &nnz[12]);
3436 h->cbp= h->cbp_table[mb_xy];
3439 nnz = h->non_zero_count[top_xy];
3440 AV_COPY32(&nnz_cache[4+8*0], &nnz[3*4]);
3443 if(left_type[LTOP]){
3444 nnz = h->non_zero_count[left_xy[LTOP]];
3445 nnz_cache[3+8*1]= nnz[3+0*4];
3446 nnz_cache[3+8*2]= nnz[3+1*4];
3447 nnz_cache[3+8*3]= nnz[3+2*4];
3448 nnz_cache[3+8*4]= nnz[3+3*4];
3451 // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
3452 if(!CABAC && h->pps.transform_8x8_mode){
3453 if(IS_8x8DCT(top_type)){
3455 nnz_cache[5+8*0]= (h->cbp_table[top_xy] & 0x4000) >> 12;
3457 nnz_cache[7+8*0]= (h->cbp_table[top_xy] & 0x8000) >> 12;
3459 if(IS_8x8DCT(left_type[LTOP])){
3461 nnz_cache[3+8*2]= (h->cbp_table[left_xy[LTOP]]&0x2000) >> 12; //FIXME check MBAFF
3463 if(IS_8x8DCT(left_type[LBOT])){
3465 nnz_cache[3+8*4]= (h->cbp_table[left_xy[LBOT]]&0x8000) >> 12; //FIXME check MBAFF
3468 if(IS_8x8DCT(mb_type)){
3469 nnz_cache[scan8[0 ]]= nnz_cache[scan8[1 ]]=
3470 nnz_cache[scan8[2 ]]= nnz_cache[scan8[3 ]]= (h->cbp & 0x1000) >> 12;
3472 nnz_cache[scan8[0+ 4]]= nnz_cache[scan8[1+ 4]]=
3473 nnz_cache[scan8[2+ 4]]= nnz_cache[scan8[3+ 4]]= (h->cbp & 0x2000) >> 12;
3475 nnz_cache[scan8[0+ 8]]= nnz_cache[scan8[1+ 8]]=
3476 nnz_cache[scan8[2+ 8]]= nnz_cache[scan8[3+ 8]]= (h->cbp & 0x4000) >> 12;
3478 nnz_cache[scan8[0+12]]= nnz_cache[scan8[1+12]]=
3479 nnz_cache[scan8[2+12]]= nnz_cache[scan8[3+12]]= (h->cbp & 0x8000) >> 12;
3486 static void loop_filter(H264Context *h, int start_x, int end_x){
3487 MpegEncContext * const s = &h->s;
3488 uint8_t *dest_y, *dest_cb, *dest_cr;
3489 int linesize, uvlinesize, mb_x, mb_y;
3490 const int end_mb_y= s->mb_y + FRAME_MBAFF;
3491 const int old_slice_type= h->slice_type;
3492 const int pixel_shift = h->pixel_shift;
3493 const int block_h = 16 >> s->chroma_y_shift;
3495 if(h->deblocking_filter) {
3496 for(mb_x= start_x; mb_x<end_x; mb_x++){
3497 for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
3499 mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
3500 h->slice_num= h->slice_table[mb_xy];
3501 mb_type = s->current_picture.f.mb_type[mb_xy];
3502 h->list_count= h->list_counts[mb_xy];
3505 h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
3509 dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
3510 dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
3511 dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
3512 //FIXME simplify above
3515 linesize = h->mb_linesize = s->linesize * 2;
3516 uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
3517 if(mb_y&1){ //FIXME move out of this function?
3518 dest_y -= s->linesize*15;
3519 dest_cb-= s->uvlinesize * (block_h - 1);
3520 dest_cr-= s->uvlinesize * (block_h - 1);
3523 linesize = h->mb_linesize = s->linesize;
3524 uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3526 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
3527 if(fill_filter_caches(h, mb_type))
3529 h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
3530 h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
3533 ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3535 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3540 h->slice_type= old_slice_type;
3542 s->mb_y= end_mb_y - FRAME_MBAFF;
3543 h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3544 h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3547 static void predict_field_decoding_flag(H264Context *h){
3548 MpegEncContext * const s = &h->s;
3549 const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3550 int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
3551 ? s->current_picture.f.mb_type[mb_xy - 1]
3552 : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
3553 ? s->current_picture.f.mb_type[mb_xy - s->mb_stride]
3555 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3559 * Draw edges and report progress for the last MB row.
3561 static void decode_finish_row(H264Context *h){
3562 MpegEncContext * const s = &h->s;
3563 int top = 16*(s->mb_y >> FIELD_PICTURE);
3564 int height = 16 << FRAME_MBAFF;
3565 int deblock_border = (16 + 4) << FRAME_MBAFF;
3566 int pic_height = 16*s->mb_height >> FIELD_PICTURE;
3568 if (h->deblocking_filter) {
3569 if((top + height) >= pic_height)
3570 height += deblock_border;
3572 top -= deblock_border;
3575 if (top >= pic_height || (top + height) < h->emu_edge_height)
3578 height = FFMIN(height, pic_height - top);
3579 if (top < h->emu_edge_height) {
3580 height = top+height;
3584 ff_draw_horiz_band(s, top, height);
3586 if (s->dropable) return;
3588 ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3589 s->picture_structure==PICT_BOTTOM_FIELD);
3592 static int decode_slice(struct AVCodecContext *avctx, void *arg){
3593 H264Context *h = *(void**)arg;
3594 MpegEncContext * const s = &h->s;
3595 const int part_mask= s->partitioned_frame ? (ER_AC_END|ER_AC_ERROR) : 0x7F;
3596 int lf_x_start = s->mb_x;
3600 h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3601 (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3603 if( h->pps.cabac ) {
3605 align_get_bits( &s->gb );
3608 ff_init_cabac_states( &h->cabac);
3609 ff_init_cabac_decoder( &h->cabac,
3610 s->gb.buffer + get_bits_count(&s->gb)/8,
3611 (get_bits_left(&s->gb) + 7)/8);
3613 ff_h264_init_cabac_states(h);
3617 int ret = ff_h264_decode_mb_cabac(h);
3619 //STOP_TIMER("decode_mb_cabac")
3621 if(ret>=0) ff_h264_hl_decode_mb(h);
3623 if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
3626 ret = ff_h264_decode_mb_cabac(h);
3628 if(ret>=0) ff_h264_hl_decode_mb(h);
3631 eos = get_cabac_terminate( &h->cabac );
3633 if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3634 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);
3635 if (s->mb_x >= lf_x_start) loop_filter(h, lf_x_start, s->mb_x + 1);
3638 if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3639 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);
3640 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3644 if( ++s->mb_x >= s->mb_width ) {
3645 loop_filter(h, lf_x_start, s->mb_x);
3646 s->mb_x = lf_x_start = 0;
3647 decode_finish_row(h);
3649 if(FIELD_OR_MBAFF_PICTURE) {
3651 if(FRAME_MBAFF && s->mb_y < s->mb_height)
3652 predict_field_decoding_flag(h);
3656 if( eos || s->mb_y >= s->mb_height ) {
3657 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3658 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);
3659 if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
3666 int ret = ff_h264_decode_mb_cavlc(h);
3668 if(ret>=0) ff_h264_hl_decode_mb(h);
3670 if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3672 ret = ff_h264_decode_mb_cavlc(h);
3674 if(ret>=0) ff_h264_hl_decode_mb(h);
3679 av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3680 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3684 if(++s->mb_x >= s->mb_width){
3685 loop_filter(h, lf_x_start, s->mb_x);
3686 s->mb_x = lf_x_start = 0;
3687 decode_finish_row(h);
3689 if(FIELD_OR_MBAFF_PICTURE) {
3691 if(FRAME_MBAFF && s->mb_y < s->mb_height)
3692 predict_field_decoding_flag(h);
3694 if(s->mb_y >= s->mb_height){
3695 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3697 if( get_bits_count(&s->gb) == s->gb.size_in_bits
3698 || get_bits_count(&s->gb) < s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3699 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);
3703 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_END&part_mask);
3710 if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3711 tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3712 if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3713 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);
3714 if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
3718 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
3728 * Call decode_slice() for each context.
3730 * @param h h264 master context
3731 * @param context_count number of contexts to execute
3733 static int execute_decode_slices(H264Context *h, int context_count){
3734 MpegEncContext * const s = &h->s;
3735 AVCodecContext * const avctx= s->avctx;
3739 if (s->avctx->hwaccel || s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3741 if(context_count == 1) {
3742 return decode_slice(avctx, &h);
3744 for(i = 1; i < context_count; i++) {
3745 hx = h->thread_context[i];
3746 hx->s.err_recognition = avctx->err_recognition;
3747 hx->s.error_count = 0;
3748 hx->x264_build= h->x264_build;
3751 avctx->execute(avctx, decode_slice,
3752 h->thread_context, NULL, context_count, sizeof(void*));
3754 /* pull back stuff from slices to master context */
3755 hx = h->thread_context[context_count - 1];
3756 s->mb_x = hx->s.mb_x;
3757 s->mb_y = hx->s.mb_y;
3758 s->dropable = hx->s.dropable;
3759 s->picture_structure = hx->s.picture_structure;
3760 for(i = 1; i < context_count; i++)
3761 h->s.error_count += h->thread_context[i]->s.error_count;
3768 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3769 MpegEncContext * const s = &h->s;
3770 AVCodecContext * const avctx= s->avctx;
3771 H264Context *hx; ///< thread context
3775 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
3776 int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts
3779 h->nal_unit_type= 0;
3781 if(!s->slice_context_count)
3782 s->slice_context_count= 1;
3783 h->max_contexts = s->slice_context_count;
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<0
3899 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
3900 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
3901 (1 << h->sps.log2_max_frame_num);
3904 s->current_picture_ptr->f.key_frame |=
3905 (hx->nal_unit_type == NAL_IDR_SLICE);
3907 if (h->recovery_frame == h->frame_num) {
3908 s->current_picture_ptr->sync |= 1;
3909 h->recovery_frame = -1;
3912 h->sync |= !!s->current_picture_ptr->f.key_frame;
3913 h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
3914 s->current_picture_ptr->sync |= h->sync;
3916 if (h->current_slice == 1) {
3917 if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3918 decode_postinit(h, nal_index >= nals_needed);
3921 if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3923 if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3924 ff_vdpau_h264_picture_start(s);
3927 if(hx->redundant_pic_count==0
3928 && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3929 && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
3930 && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
3931 && avctx->skip_frame < AVDISCARD_ALL){
3932 if(avctx->hwaccel) {
3933 if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3936 if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3937 static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3938 ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3939 ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3945 init_get_bits(&hx->s.gb, ptr, bit_length);
3947 hx->inter_gb_ptr= NULL;
3949 if ((err = decode_slice_header(hx, h)) < 0)
3952 hx->s.data_partitioning = 1;
3956 init_get_bits(&hx->intra_gb, ptr, bit_length);
3957 hx->intra_gb_ptr= &hx->intra_gb;
3960 init_get_bits(&hx->inter_gb, ptr, bit_length);
3961 hx->inter_gb_ptr= &hx->inter_gb;
3963 if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3964 && s->context_initialized
3965 && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3966 && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
3967 && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
3968 && avctx->skip_frame < AVDISCARD_ALL)
3972 init_get_bits(&s->gb, ptr, bit_length);
3973 ff_h264_decode_sei(h);
3976 init_get_bits(&s->gb, ptr, bit_length);
3977 if(ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)){
3978 av_log(h->s.avctx, AV_LOG_DEBUG, "SPS decoding failure, trying alternative mode\n");
3979 if(h->is_avc) av_assert0(next_avc - buf_index + consumed == nalsize);
3980 init_get_bits(&s->gb, &buf[buf_index + 1 - consumed], 8*(next_avc - buf_index + consumed));
3981 ff_h264_decode_seq_parameter_set(h);
3984 if (s->flags& CODEC_FLAG_LOW_DELAY ||
3985 (h->sps.bitstream_restriction_flag && !h->sps.num_reorder_frames))
3988 if(avctx->has_b_frames < 2)
3989 avctx->has_b_frames= !s->low_delay;
3992 init_get_bits(&s->gb, ptr, bit_length);
3994 ff_h264_decode_picture_parameter_set(h, bit_length);
3998 case NAL_END_SEQUENCE:
3999 case NAL_END_STREAM:
4000 case NAL_FILLER_DATA:
4002 case NAL_AUXILIARY_SLICE:
4005 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
4008 if(context_count == h->max_contexts) {
4009 execute_decode_slices(h, context_count);
4014 av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4016 /* Slice could not be decoded in parallel mode, copy down
4017 * NAL unit stuff to context 0 and restart. Note that
4018 * rbsp_buffer is not transferred, but since we no longer
4019 * run in parallel mode this should not be an issue. */
4020 h->nal_unit_type = hx->nal_unit_type;
4021 h->nal_ref_idc = hx->nal_ref_idc;
4028 execute_decode_slices(h, context_count);
4033 * Return the number of bytes consumed for building the current frame.
4035 static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
4036 if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
4037 if(pos+10>buf_size) pos=buf_size; // oops ;)
4042 static int decode_frame(AVCodecContext *avctx,
4043 void *data, int *data_size,
4046 const uint8_t *buf = avpkt->data;
4047 int buf_size = avpkt->size;
4048 H264Context *h = avctx->priv_data;
4049 MpegEncContext *s = &h->s;
4050 AVFrame *pict = data;
4055 s->flags= avctx->flags;
4056 s->flags2= avctx->flags2;
4058 /* end of stream, output what is still in the buffers */
4059 if (buf_size == 0) {
4062 s->current_picture_ptr = NULL;
4064 //FIXME factorize this with the output code below
4065 out = h->delayed_pic[0];
4067 for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
4068 if(h->delayed_pic[i]->poc < out->poc){
4069 out = h->delayed_pic[i];
4073 for(i=out_idx; h->delayed_pic[i]; i++)
4074 h->delayed_pic[i] = h->delayed_pic[i+1];
4077 *data_size = sizeof(AVFrame);
4078 *pict= *(AVFrame*)out;
4083 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4084 int cnt= buf[5]&0x1f;
4087 int nalsize= AV_RB16(p) + 2;
4088 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4096 int nalsize= AV_RB16(p) + 2;
4097 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4102 return ff_h264_decode_extradata(h, buf, buf_size);
4106 buf_index=decode_nal_units(h, buf, buf_size);
4110 if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4111 av_assert0(buf_index <= buf_size);
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 || h->sync>1)) {
4131 *data_size = sizeof(AVFrame);
4132 *pict = *(AVFrame*)h->next_output_pic;
4136 assert(pict->data[0] || !*data_size);
4137 ff_print_debug_info(s, pict);
4138 //printf("out %d\n", (int)pict->data[0]);
4140 return get_consumed_bytes(s, buf_index, buf_size);
4143 static inline void fill_mb_avail(H264Context *h){
4144 MpegEncContext * const s = &h->s;
4145 const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
4148 h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
4149 h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
4150 h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
4156 h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
4157 h->mb_avail[4]= 1; //FIXME move out
4158 h->mb_avail[5]= 0; //FIXME move out
4166 #define SIZE (COUNT*40)
4167 extern AVCodec ff_h264_decoder;
4174 AVCodecContext avctx;
4176 avcodec_get_context_defaults3(&avctx, &ff_h264_decoder);
4178 dsputil_init(&dsp, &avctx);
4180 init_put_bits(&pb, temp, SIZE);
4181 printf("testing unsigned exp golomb\n");
4182 for(i=0; i<COUNT; i++){
4184 set_ue_golomb(&pb, i);
4185 STOP_TIMER("set_ue_golomb");
4187 flush_put_bits(&pb);
4189 init_get_bits(&gb, temp, 8*SIZE);
4190 for(i=0; i<COUNT; i++){
4191 int j, s = show_bits(&gb, 24);
4194 j= get_ue_golomb(&gb);
4196 printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4199 STOP_TIMER("get_ue_golomb");}
4203 init_put_bits(&pb, temp, SIZE);
4204 printf("testing signed exp golomb\n");
4205 for(i=0; i<COUNT; i++){
4207 set_se_golomb(&pb, i - COUNT/2);
4208 STOP_TIMER("set_se_golomb");
4210 flush_put_bits(&pb);
4212 init_get_bits(&gb, temp, 8*SIZE);
4213 for(i=0; i<COUNT; i++){
4214 int j, s = show_bits(&gb, 24);
4217 j= get_se_golomb(&gb);
4218 if(j != i - COUNT/2){
4219 printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4222 STOP_TIMER("get_se_golomb");}
4225 printf("Testing RBSP\n");
4233 av_cold void ff_h264_free_context(H264Context *h)
4237 free_tables(h, 1); //FIXME cleanup init stuff perhaps
4239 for(i = 0; i < MAX_SPS_COUNT; i++)
4240 av_freep(h->sps_buffers + i);
4242 for(i = 0; i < MAX_PPS_COUNT; i++)
4243 av_freep(h->pps_buffers + i);
4246 av_cold int ff_h264_decode_end(AVCodecContext *avctx)
4248 H264Context *h = avctx->priv_data;
4249 MpegEncContext *s = &h->s;
4251 ff_h264_remove_all_refs(h);
4252 ff_h264_free_context(h);
4256 // memset(h, 0, sizeof(H264Context));
4261 static const AVProfile profiles[] = {
4262 { FF_PROFILE_H264_BASELINE, "Baseline" },
4263 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4264 { FF_PROFILE_H264_MAIN, "Main" },
4265 { FF_PROFILE_H264_EXTENDED, "Extended" },
4266 { FF_PROFILE_H264_HIGH, "High" },
4267 { FF_PROFILE_H264_HIGH_10, "High 10" },
4268 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4269 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4270 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4271 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4272 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4273 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4274 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4275 { FF_PROFILE_UNKNOWN },
4278 static const AVOption h264_options[] = {
4279 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
4280 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
4284 static const AVClass h264_class = {
4286 av_default_item_name,
4288 LIBAVUTIL_VERSION_INT,
4291 static const AVClass h264_vdpau_class = {
4292 "H264 VDPAU Decoder",
4293 av_default_item_name,
4295 LIBAVUTIL_VERSION_INT,
4298 AVCodec ff_h264_decoder = {
4300 .type = AVMEDIA_TYPE_VIDEO,
4301 .id = CODEC_ID_H264,
4302 .priv_data_size = sizeof(H264Context),
4303 .init = ff_h264_decode_init,
4304 .close = ff_h264_decode_end,
4305 .decode = decode_frame,
4306 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
4307 CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
4309 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4310 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4311 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4312 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4313 .priv_class = &h264_class,
4316 #if CONFIG_H264_VDPAU_DECODER
4317 AVCodec ff_h264_vdpau_decoder = {
4318 .name = "h264_vdpau",
4319 .type = AVMEDIA_TYPE_VIDEO,
4320 .id = CODEC_ID_H264,
4321 .priv_data_size = sizeof(H264Context),
4322 .init = ff_h264_decode_init,
4323 .close = ff_h264_decode_end,
4324 .decode = decode_frame,
4325 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4327 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4328 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
4329 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4330 .priv_class = &h264_vdpau_class,