You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3830 lines
141KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  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.
  11. *
  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.
  16. *
  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
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #include "libavutil/imgutils.h"
  27. #include "internal.h"
  28. #include "dsputil.h"
  29. #include "avcodec.h"
  30. #include "mpegvideo.h"
  31. #include "h264.h"
  32. #include "h264data.h"
  33. #include "h264_mvpred.h"
  34. #include "golomb.h"
  35. #include "mathops.h"
  36. #include "rectangle.h"
  37. #include "thread.h"
  38. #include "vdpau_internal.h"
  39. #include "libavutil/avassert.h"
  40. #include "cabac.h"
  41. //#undef NDEBUG
  42. #include <assert.h>
  43. static const uint8_t rem6[52]={
  44. 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,
  45. };
  46. static const uint8_t div6[52]={
  47. 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,
  48. };
  49. static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  50. PIX_FMT_DXVA2_VLD,
  51. PIX_FMT_VAAPI_VLD,
  52. PIX_FMT_YUVJ420P,
  53. PIX_FMT_NONE
  54. };
  55. void ff_h264_write_back_intra_pred_mode(H264Context *h){
  56. int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
  57. AV_COPY32(mode, h->intra4x4_pred_mode_cache + 4 + 8*4);
  58. mode[4]= h->intra4x4_pred_mode_cache[7+8*3];
  59. mode[5]= h->intra4x4_pred_mode_cache[7+8*2];
  60. mode[6]= h->intra4x4_pred_mode_cache[7+8*1];
  61. }
  62. /**
  63. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  64. */
  65. int ff_h264_check_intra4x4_pred_mode(H264Context *h){
  66. MpegEncContext * const s = &h->s;
  67. static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
  68. static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
  69. int i;
  70. if(!(h->top_samples_available&0x8000)){
  71. for(i=0; i<4; i++){
  72. int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
  73. if(status<0){
  74. 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);
  75. return -1;
  76. } else if(status){
  77. h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
  78. }
  79. }
  80. }
  81. if((h->left_samples_available&0x8888)!=0x8888){
  82. static const int mask[4]={0x8000,0x2000,0x80,0x20};
  83. for(i=0; i<4; i++){
  84. if(!(h->left_samples_available&mask[i])){
  85. int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
  86. if(status<0){
  87. 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);
  88. return -1;
  89. } else if(status){
  90. h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
  91. }
  92. }
  93. }
  94. }
  95. return 0;
  96. } //FIXME cleanup like ff_h264_check_intra_pred_mode
  97. /**
  98. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  99. */
  100. int ff_h264_check_intra_pred_mode(H264Context *h, int mode){
  101. MpegEncContext * const s = &h->s;
  102. static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
  103. static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
  104. if(mode > 6U) {
  105. 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);
  106. return -1;
  107. }
  108. if(!(h->top_samples_available&0x8000)){
  109. mode= top[ mode ];
  110. if(mode<0){
  111. 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);
  112. return -1;
  113. }
  114. }
  115. if((h->left_samples_available&0x8080) != 0x8080){
  116. mode= left[ mode ];
  117. if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
  118. mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
  119. }
  120. if(mode<0){
  121. 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);
  122. return -1;
  123. }
  124. }
  125. return mode;
  126. }
  127. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
  128. int i, si, di;
  129. uint8_t *dst;
  130. int bufidx;
  131. // src[0]&0x80; //forbidden bit
  132. h->nal_ref_idc= src[0]>>5;
  133. h->nal_unit_type= src[0]&0x1F;
  134. src++; length--;
  135. #if 0
  136. for(i=0; i<length; i++)
  137. printf("%2X ", src[i]);
  138. #endif
  139. #if HAVE_FAST_UNALIGNED
  140. # if HAVE_FAST_64BIT
  141. # define RS 7
  142. for(i=0; i+1<length; i+=9){
  143. if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
  144. # else
  145. # define RS 3
  146. for(i=0; i+1<length; i+=5){
  147. if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
  148. # endif
  149. continue;
  150. if(i>0 && !src[i]) i--;
  151. while(src[i]) i++;
  152. #else
  153. # define RS 0
  154. for(i=0; i+1<length; i+=2){
  155. if(src[i]) continue;
  156. if(i>0 && src[i-1]==0) i--;
  157. #endif
  158. if(i+2<length && src[i+1]==0 && src[i+2]<=3){
  159. if(src[i+2]!=3){
  160. /* startcode, so we must be past the end */
  161. length=i;
  162. }
  163. break;
  164. }
  165. i-= RS;
  166. }
  167. if(i>=length-1){ //no escaped 0
  168. *dst_length= length;
  169. *consumed= length+1; //+1 for the header
  170. return src;
  171. }
  172. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
  173. av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE);
  174. dst= h->rbsp_buffer[bufidx];
  175. if (dst == NULL){
  176. return NULL;
  177. }
  178. //printf("decoding esc\n");
  179. memcpy(dst, src, i);
  180. si=di=i;
  181. while(si+2<length){
  182. //remove escapes (very rare 1:2^22)
  183. if(src[si+2]>3){
  184. dst[di++]= src[si++];
  185. dst[di++]= src[si++];
  186. }else if(src[si]==0 && src[si+1]==0){
  187. if(src[si+2]==3){ //escape
  188. dst[di++]= 0;
  189. dst[di++]= 0;
  190. si+=3;
  191. continue;
  192. }else //next start code
  193. goto nsc;
  194. }
  195. dst[di++]= src[si++];
  196. }
  197. while(si<length)
  198. dst[di++]= src[si++];
  199. nsc:
  200. memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  201. *dst_length= di;
  202. *consumed= si + 1;//+1 for the header
  203. //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
  204. return dst;
  205. }
  206. /**
  207. * Identify the exact end of the bitstream
  208. * @return the length of the trailing, or 0 if damaged
  209. */
  210. static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
  211. int v= *src;
  212. int r;
  213. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  214. for(r=1; r<9; r++){
  215. if(v&1) return r;
  216. v>>=1;
  217. }
  218. return 0;
  219. }
  220. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
  221. int y_offset, int list){
  222. int raw_my= h->mv_cache[list][ scan8[n] ][1];
  223. int filter_height= (raw_my&3) ? 2 : 0;
  224. int full_my= (raw_my>>2) + y_offset;
  225. int top = full_my - filter_height, bottom = full_my + height + filter_height;
  226. return FFMAX(abs(top), bottom);
  227. }
  228. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
  229. int y_offset, int list0, int list1, int *nrefs){
  230. MpegEncContext * const s = &h->s;
  231. int my;
  232. y_offset += 16*(s->mb_y >> MB_FIELD);
  233. if(list0){
  234. int ref_n = h->ref_cache[0][ scan8[n] ];
  235. Picture *ref= &h->ref_list[0][ref_n];
  236. // Error resilience puts the current picture in the ref list.
  237. // Don't try to wait on these as it will cause a deadlock.
  238. // Fields can wait on each other, though.
  239. if(ref->thread_opaque != s->current_picture.thread_opaque ||
  240. (ref->reference&3) != s->picture_structure) {
  241. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  242. if (refs[0][ref_n] < 0) nrefs[0] += 1;
  243. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  244. }
  245. }
  246. if(list1){
  247. int ref_n = h->ref_cache[1][ scan8[n] ];
  248. Picture *ref= &h->ref_list[1][ref_n];
  249. if(ref->thread_opaque != s->current_picture.thread_opaque ||
  250. (ref->reference&3) != s->picture_structure) {
  251. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  252. if (refs[1][ref_n] < 0) nrefs[1] += 1;
  253. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  254. }
  255. }
  256. }
  257. /**
  258. * Wait until all reference frames are available for MC operations.
  259. *
  260. * @param h the H264 context
  261. */
  262. static void await_references(H264Context *h){
  263. MpegEncContext * const s = &h->s;
  264. const int mb_xy= h->mb_xy;
  265. const int mb_type= s->current_picture.mb_type[mb_xy];
  266. int refs[2][48];
  267. int nrefs[2] = {0};
  268. int ref, list;
  269. memset(refs, -1, sizeof(refs));
  270. if(IS_16X16(mb_type)){
  271. get_lowest_part_y(h, refs, 0, 16, 0,
  272. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  273. }else if(IS_16X8(mb_type)){
  274. get_lowest_part_y(h, refs, 0, 8, 0,
  275. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  276. get_lowest_part_y(h, refs, 8, 8, 8,
  277. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  278. }else if(IS_8X16(mb_type)){
  279. get_lowest_part_y(h, refs, 0, 16, 0,
  280. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  281. get_lowest_part_y(h, refs, 4, 16, 0,
  282. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  283. }else{
  284. int i;
  285. assert(IS_8X8(mb_type));
  286. for(i=0; i<4; i++){
  287. const int sub_mb_type= h->sub_mb_type[i];
  288. const int n= 4*i;
  289. int y_offset= (i&2)<<2;
  290. if(IS_SUB_8X8(sub_mb_type)){
  291. get_lowest_part_y(h, refs, n , 8, y_offset,
  292. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  293. }else if(IS_SUB_8X4(sub_mb_type)){
  294. get_lowest_part_y(h, refs, n , 4, y_offset,
  295. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  296. get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
  297. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  298. }else if(IS_SUB_4X8(sub_mb_type)){
  299. get_lowest_part_y(h, refs, n , 8, y_offset,
  300. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  301. get_lowest_part_y(h, refs, n+1, 8, y_offset,
  302. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  303. }else{
  304. int j;
  305. assert(IS_SUB_4X4(sub_mb_type));
  306. for(j=0; j<4; j++){
  307. int sub_y_offset= y_offset + 2*(j&2);
  308. get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
  309. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  310. }
  311. }
  312. }
  313. }
  314. for(list=h->list_count-1; list>=0; list--){
  315. for(ref=0; ref<48 && nrefs[list]; ref++){
  316. int row = refs[list][ref];
  317. if(row >= 0){
  318. Picture *ref_pic = &h->ref_list[list][ref];
  319. int ref_field = ref_pic->reference - 1;
  320. int ref_field_picture = ref_pic->field_picture;
  321. int pic_height = 16*s->mb_height >> ref_field_picture;
  322. row <<= MB_MBAFF;
  323. nrefs[list]--;
  324. if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
  325. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
  326. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) , pic_height-1), 0);
  327. }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
  328. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field , pic_height-1), 0);
  329. }else if(FIELD_PICTURE){
  330. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
  331. }else{
  332. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. #if 0
  339. /**
  340. * DCT transforms the 16 dc values.
  341. * @param qp quantization parameter ??? FIXME
  342. */
  343. static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
  344. // const int qmul= dequant_coeff[qp][0];
  345. int i;
  346. int temp[16]; //FIXME check if this is a good idea
  347. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  348. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  349. for(i=0; i<4; i++){
  350. const int offset= y_offset[i];
  351. const int z0= block[offset+stride*0] + block[offset+stride*4];
  352. const int z1= block[offset+stride*0] - block[offset+stride*4];
  353. const int z2= block[offset+stride*1] - block[offset+stride*5];
  354. const int z3= block[offset+stride*1] + block[offset+stride*5];
  355. temp[4*i+0]= z0+z3;
  356. temp[4*i+1]= z1+z2;
  357. temp[4*i+2]= z1-z2;
  358. temp[4*i+3]= z0-z3;
  359. }
  360. for(i=0; i<4; i++){
  361. const int offset= x_offset[i];
  362. const int z0= temp[4*0+i] + temp[4*2+i];
  363. const int z1= temp[4*0+i] - temp[4*2+i];
  364. const int z2= temp[4*1+i] - temp[4*3+i];
  365. const int z3= temp[4*1+i] + temp[4*3+i];
  366. block[stride*0 +offset]= (z0 + z3)>>1;
  367. block[stride*2 +offset]= (z1 + z2)>>1;
  368. block[stride*8 +offset]= (z1 - z2)>>1;
  369. block[stride*10+offset]= (z0 - z3)>>1;
  370. }
  371. }
  372. #endif
  373. #undef xStride
  374. #undef stride
  375. static void chroma_dc_dequant_idct_c(DCTELEM *block, int qmul){
  376. const int stride= 16*2;
  377. const int xStride= 16;
  378. int a,b,c,d,e;
  379. a= block[stride*0 + xStride*0];
  380. b= block[stride*0 + xStride*1];
  381. c= block[stride*1 + xStride*0];
  382. d= block[stride*1 + xStride*1];
  383. e= a-b;
  384. a= a+b;
  385. b= c-d;
  386. c= c+d;
  387. block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
  388. block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
  389. block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
  390. block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
  391. }
  392. #if 0
  393. static void chroma_dc_dct_c(DCTELEM *block){
  394. const int stride= 16*2;
  395. const int xStride= 16;
  396. int a,b,c,d,e;
  397. a= block[stride*0 + xStride*0];
  398. b= block[stride*0 + xStride*1];
  399. c= block[stride*1 + xStride*0];
  400. d= block[stride*1 + xStride*1];
  401. e= a-b;
  402. a= a+b;
  403. b= c-d;
  404. c= c+d;
  405. block[stride*0 + xStride*0]= (a+c);
  406. block[stride*0 + xStride*1]= (e+b);
  407. block[stride*1 + xStride*0]= (a-c);
  408. block[stride*1 + xStride*1]= (e-b);
  409. }
  410. #endif
  411. static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
  412. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  413. int src_x_offset, int src_y_offset,
  414. qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
  415. MpegEncContext * const s = &h->s;
  416. const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
  417. int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
  418. const int luma_xy= (mx&3) + ((my&3)<<2);
  419. uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
  420. uint8_t * src_cb, * src_cr;
  421. int extra_width= h->emu_edge_width;
  422. int extra_height= h->emu_edge_height;
  423. int emu=0;
  424. const int full_mx= mx>>2;
  425. const int full_my= my>>2;
  426. const int pic_width = 16*s->mb_width;
  427. const int pic_height = 16*s->mb_height >> MB_FIELD;
  428. if(mx&7) extra_width -= 3;
  429. if(my&7) extra_height -= 3;
  430. if( full_mx < 0-extra_width
  431. || full_my < 0-extra_height
  432. || full_mx + 16/*FIXME*/ > pic_width + extra_width
  433. || full_my + 16/*FIXME*/ > pic_height + extra_height){
  434. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  435. src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
  436. emu=1;
  437. }
  438. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
  439. if(!square){
  440. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  441. }
  442. if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
  443. if(MB_FIELD){
  444. // chroma offset when predicting from a field of opposite parity
  445. my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
  446. emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
  447. }
  448. src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  449. src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  450. if(emu){
  451. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  452. src_cb= s->edge_emu_buffer;
  453. }
  454. chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  455. if(emu){
  456. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  457. src_cr= s->edge_emu_buffer;
  458. }
  459. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  460. }
  461. static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
  462. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  463. int x_offset, int y_offset,
  464. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  465. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  466. int list0, int list1){
  467. MpegEncContext * const s = &h->s;
  468. qpel_mc_func *qpix_op= qpix_put;
  469. h264_chroma_mc_func chroma_op= chroma_put;
  470. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  471. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  472. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  473. x_offset += 8*s->mb_x;
  474. y_offset += 8*(s->mb_y >> MB_FIELD);
  475. if(list0){
  476. Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
  477. mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
  478. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  479. qpix_op, chroma_op);
  480. qpix_op= qpix_avg;
  481. chroma_op= chroma_avg;
  482. }
  483. if(list1){
  484. Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
  485. mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
  486. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  487. qpix_op, chroma_op);
  488. }
  489. }
  490. static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
  491. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  492. int x_offset, int y_offset,
  493. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  494. h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
  495. h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
  496. int list0, int list1){
  497. MpegEncContext * const s = &h->s;
  498. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  499. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  500. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  501. x_offset += 8*s->mb_x;
  502. y_offset += 8*(s->mb_y >> MB_FIELD);
  503. if(list0 && list1){
  504. /* don't optimize for luma-only case, since B-frames usually
  505. * use implicit weights => chroma too. */
  506. uint8_t *tmp_cb = s->obmc_scratchpad;
  507. uint8_t *tmp_cr = s->obmc_scratchpad + 8;
  508. uint8_t *tmp_y = s->obmc_scratchpad + 8*h->mb_uvlinesize;
  509. int refn0 = h->ref_cache[0][ scan8[n] ];
  510. int refn1 = h->ref_cache[1][ scan8[n] ];
  511. mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
  512. dest_y, dest_cb, dest_cr,
  513. x_offset, y_offset, qpix_put, chroma_put);
  514. mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
  515. tmp_y, tmp_cb, tmp_cr,
  516. x_offset, y_offset, qpix_put, chroma_put);
  517. if(h->use_weight == 2){
  518. int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
  519. int weight1 = 64 - weight0;
  520. luma_weight_avg( dest_y, tmp_y, h-> mb_linesize, 5, weight0, weight1, 0);
  521. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
  522. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
  523. }else{
  524. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
  525. h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
  526. h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
  527. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  528. h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
  529. h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
  530. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  531. h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
  532. h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
  533. }
  534. }else{
  535. int list = list1 ? 1 : 0;
  536. int refn = h->ref_cache[list][ scan8[n] ];
  537. Picture *ref= &h->ref_list[list][refn];
  538. mc_dir_part(h, ref, n, square, chroma_height, delta, list,
  539. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  540. qpix_put, chroma_put);
  541. luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
  542. h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
  543. if(h->use_weight_chroma){
  544. chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  545. h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
  546. chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  547. h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
  548. }
  549. }
  550. }
  551. static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
  552. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  553. int x_offset, int y_offset,
  554. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  555. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  556. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  557. int list0, int list1){
  558. if((h->use_weight==2 && list0 && list1
  559. && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
  560. || h->use_weight==1)
  561. mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  562. x_offset, y_offset, qpix_put, chroma_put,
  563. weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
  564. else
  565. mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  566. x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
  567. }
  568. static inline void prefetch_motion(H264Context *h, int list){
  569. /* fetch pixels for estimated mv 4 macroblocks ahead
  570. * optimized for 64byte cache lines */
  571. MpegEncContext * const s = &h->s;
  572. const int refn = h->ref_cache[list][scan8[0]];
  573. if(refn >= 0){
  574. const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
  575. const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
  576. uint8_t **src= h->ref_list[list][refn].data;
  577. int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
  578. s->dsp.prefetch(src[0]+off, s->linesize, 4);
  579. off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
  580. s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
  581. }
  582. }
  583. static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  584. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  585. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  586. h264_weight_func *weight_op, h264_biweight_func *weight_avg){
  587. MpegEncContext * const s = &h->s;
  588. const int mb_xy= h->mb_xy;
  589. const int mb_type= s->current_picture.mb_type[mb_xy];
  590. assert(IS_INTER(mb_type));
  591. if(HAVE_PTHREADS && s->avctx->active_thread_type&FF_THREAD_FRAME)
  592. await_references(h);
  593. prefetch_motion(h, 0);
  594. if(IS_16X16(mb_type)){
  595. mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
  596. qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
  597. weight_op, weight_avg,
  598. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  599. }else if(IS_16X8(mb_type)){
  600. mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
  601. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  602. &weight_op[1], &weight_avg[1],
  603. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  604. mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
  605. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  606. &weight_op[1], &weight_avg[1],
  607. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  608. }else if(IS_8X16(mb_type)){
  609. mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
  610. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  611. &weight_op[2], &weight_avg[2],
  612. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  613. mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
  614. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  615. &weight_op[2], &weight_avg[2],
  616. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  617. }else{
  618. int i;
  619. assert(IS_8X8(mb_type));
  620. for(i=0; i<4; i++){
  621. const int sub_mb_type= h->sub_mb_type[i];
  622. const int n= 4*i;
  623. int x_offset= (i&1)<<2;
  624. int y_offset= (i&2)<<1;
  625. if(IS_SUB_8X8(sub_mb_type)){
  626. mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  627. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  628. &weight_op[3], &weight_avg[3],
  629. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  630. }else if(IS_SUB_8X4(sub_mb_type)){
  631. mc_part(h, n , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  632. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  633. &weight_op[4], &weight_avg[4],
  634. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  635. mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
  636. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  637. &weight_op[4], &weight_avg[4],
  638. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  639. }else if(IS_SUB_4X8(sub_mb_type)){
  640. mc_part(h, n , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  641. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  642. &weight_op[5], &weight_avg[5],
  643. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  644. mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
  645. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  646. &weight_op[5], &weight_avg[5],
  647. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  648. }else{
  649. int j;
  650. assert(IS_SUB_4X4(sub_mb_type));
  651. for(j=0; j<4; j++){
  652. int sub_x_offset= x_offset + 2*(j&1);
  653. int sub_y_offset= y_offset + (j&2);
  654. mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
  655. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  656. &weight_op[6], &weight_avg[6],
  657. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  658. }
  659. }
  660. }
  661. }
  662. prefetch_motion(h, 1);
  663. }
  664. static void free_tables(H264Context *h, int free_rbsp){
  665. int i;
  666. H264Context *hx;
  667. av_freep(&h->intra4x4_pred_mode);
  668. av_freep(&h->chroma_pred_mode_table);
  669. av_freep(&h->cbp_table);
  670. av_freep(&h->mvd_table[0]);
  671. av_freep(&h->mvd_table[1]);
  672. av_freep(&h->direct_table);
  673. av_freep(&h->non_zero_count);
  674. av_freep(&h->slice_table_base);
  675. h->slice_table= NULL;
  676. av_freep(&h->list_counts);
  677. av_freep(&h->mb2b_xy);
  678. av_freep(&h->mb2br_xy);
  679. for(i = 0; i < MAX_THREADS; i++) {
  680. hx = h->thread_context[i];
  681. if(!hx) continue;
  682. av_freep(&hx->top_borders[1]);
  683. av_freep(&hx->top_borders[0]);
  684. av_freep(&hx->s.obmc_scratchpad);
  685. if (free_rbsp){
  686. av_freep(&hx->rbsp_buffer[1]);
  687. av_freep(&hx->rbsp_buffer[0]);
  688. hx->rbsp_buffer_size[0] = 0;
  689. hx->rbsp_buffer_size[1] = 0;
  690. }
  691. if (i) av_freep(&h->thread_context[i]);
  692. }
  693. }
  694. static void init_dequant8_coeff_table(H264Context *h){
  695. int i,q,x;
  696. h->dequant8_coeff[0] = h->dequant8_buffer[0];
  697. h->dequant8_coeff[1] = h->dequant8_buffer[1];
  698. for(i=0; i<2; i++ ){
  699. if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
  700. h->dequant8_coeff[1] = h->dequant8_buffer[0];
  701. break;
  702. }
  703. for(q=0; q<52; q++){
  704. int shift = div6[q];
  705. int idx = rem6[q];
  706. for(x=0; x<64; x++)
  707. h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
  708. ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
  709. h->pps.scaling_matrix8[i][x]) << shift;
  710. }
  711. }
  712. }
  713. static void init_dequant4_coeff_table(H264Context *h){
  714. int i,j,q,x;
  715. for(i=0; i<6; i++ ){
  716. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  717. for(j=0; j<i; j++){
  718. if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
  719. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  720. break;
  721. }
  722. }
  723. if(j<i)
  724. continue;
  725. for(q=0; q<52; q++){
  726. int shift = div6[q] + 2;
  727. int idx = rem6[q];
  728. for(x=0; x<16; x++)
  729. h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
  730. ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
  731. h->pps.scaling_matrix4[i][x]) << shift;
  732. }
  733. }
  734. }
  735. static void init_dequant_tables(H264Context *h){
  736. int i,x;
  737. init_dequant4_coeff_table(h);
  738. if(h->pps.transform_8x8_mode)
  739. init_dequant8_coeff_table(h);
  740. if(h->sps.transform_bypass){
  741. for(i=0; i<6; i++)
  742. for(x=0; x<16; x++)
  743. h->dequant4_coeff[i][0][x] = 1<<6;
  744. if(h->pps.transform_8x8_mode)
  745. for(i=0; i<2; i++)
  746. for(x=0; x<64; x++)
  747. h->dequant8_coeff[i][0][x] = 1<<6;
  748. }
  749. }
  750. int ff_h264_alloc_tables(H264Context *h){
  751. MpegEncContext * const s = &h->s;
  752. const int big_mb_num= s->mb_stride * (s->mb_height+1);
  753. const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
  754. int x,y;
  755. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8 * sizeof(uint8_t), fail)
  756. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count , big_mb_num * 32 * sizeof(uint8_t), fail)
  757. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
  758. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
  759. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
  760. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
  761. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
  762. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
  763. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
  764. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base));
  765. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  766. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy , big_mb_num * sizeof(uint32_t), fail);
  767. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
  768. for(y=0; y<s->mb_height; y++){
  769. for(x=0; x<s->mb_width; x++){
  770. const int mb_xy= x + y*s->mb_stride;
  771. const int b_xy = 4*x + 4*y*h->b_stride;
  772. h->mb2b_xy [mb_xy]= b_xy;
  773. h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
  774. }
  775. }
  776. s->obmc_scratchpad = NULL;
  777. if(!h->dequant4_coeff[0])
  778. init_dequant_tables(h);
  779. return 0;
  780. fail:
  781. free_tables(h, 1);
  782. return -1;
  783. }
  784. /**
  785. * Mimic alloc_tables(), but for every context thread.
  786. */
  787. static void clone_tables(H264Context *dst, H264Context *src, int i){
  788. MpegEncContext * const s = &src->s;
  789. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
  790. dst->non_zero_count = src->non_zero_count;
  791. dst->slice_table = src->slice_table;
  792. dst->cbp_table = src->cbp_table;
  793. dst->mb2b_xy = src->mb2b_xy;
  794. dst->mb2br_xy = src->mb2br_xy;
  795. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  796. dst->mvd_table[0] = src->mvd_table[0] + i*8*2*s->mb_stride;
  797. dst->mvd_table[1] = src->mvd_table[1] + i*8*2*s->mb_stride;
  798. dst->direct_table = src->direct_table;
  799. dst->list_counts = src->list_counts;
  800. dst->s.obmc_scratchpad = NULL;
  801. ff_h264_pred_init(&dst->hpc, src->s.codec_id);
  802. }
  803. /**
  804. * Init context
  805. * Allocate buffers which are not shared amongst multiple threads.
  806. */
  807. static int context_init(H264Context *h){
  808. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
  809. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
  810. h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
  811. h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
  812. return 0;
  813. fail:
  814. return -1; // free_tables will clean up for us
  815. }
  816. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
  817. static av_cold void common_init(H264Context *h){
  818. MpegEncContext * const s = &h->s;
  819. s->width = s->avctx->width;
  820. s->height = s->avctx->height;
  821. s->codec_id= s->avctx->codec->id;
  822. ff_h264dsp_init(&h->h264dsp);
  823. ff_h264_pred_init(&h->hpc, s->codec_id);
  824. h->dequant_coeff_pps= -1;
  825. s->unrestricted_mv=1;
  826. s->decode=1; //FIXME
  827. dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
  828. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  829. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  830. }
  831. int ff_h264_decode_extradata(H264Context *h)
  832. {
  833. AVCodecContext *avctx = h->s.avctx;
  834. if(*(char *)avctx->extradata == 1){
  835. int i, cnt, nalsize;
  836. unsigned char *p = avctx->extradata;
  837. h->is_avc = 1;
  838. if(avctx->extradata_size < 7) {
  839. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  840. return -1;
  841. }
  842. /* sps and pps in the avcC always have length coded with 2 bytes,
  843. so put a fake nal_length_size = 2 while parsing them */
  844. h->nal_length_size = 2;
  845. // Decode sps from avcC
  846. cnt = *(p+5) & 0x1f; // Number of sps
  847. p += 6;
  848. for (i = 0; i < cnt; i++) {
  849. nalsize = AV_RB16(p) + 2;
  850. if(decode_nal_units(h, p, nalsize) < 0) {
  851. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  852. return -1;
  853. }
  854. p += nalsize;
  855. }
  856. // Decode pps from avcC
  857. cnt = *(p++); // Number of pps
  858. for (i = 0; i < cnt; i++) {
  859. nalsize = AV_RB16(p) + 2;
  860. if(decode_nal_units(h, p, nalsize) < 0) {
  861. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  862. return -1;
  863. }
  864. p += nalsize;
  865. }
  866. // Now store right nal length size, that will be use to parse all other nals
  867. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  868. } else {
  869. h->is_avc = 0;
  870. if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
  871. return -1;
  872. }
  873. return 0;
  874. }
  875. av_cold int ff_h264_decode_init(AVCodecContext *avctx){
  876. H264Context *h= avctx->priv_data;
  877. MpegEncContext * const s = &h->s;
  878. MPV_decode_defaults(s);
  879. s->avctx = avctx;
  880. common_init(h);
  881. s->out_format = FMT_H264;
  882. s->workaround_bugs= avctx->workaround_bugs;
  883. // set defaults
  884. // s->decode_mb= ff_h263_decode_mb;
  885. s->quarter_sample = 1;
  886. if(!avctx->has_b_frames)
  887. s->low_delay= 1;
  888. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  889. ff_h264_decode_init_vlc();
  890. h->thread_context[0] = h;
  891. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  892. h->prev_poc_msb= 1<<16;
  893. h->x264_build = -1;
  894. ff_h264_reset_sei(h);
  895. if(avctx->codec_id == CODEC_ID_H264){
  896. if(avctx->ticks_per_frame == 1){
  897. s->avctx->time_base.den *=2;
  898. }
  899. avctx->ticks_per_frame = 2;
  900. }
  901. if(avctx->extradata_size > 0 && avctx->extradata &&
  902. ff_h264_decode_extradata(h))
  903. return -1;
  904. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  905. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  906. s->low_delay = 0;
  907. }
  908. return 0;
  909. }
  910. static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
  911. {
  912. int i;
  913. for (i=0; i<count; i++){
  914. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  915. }
  916. }
  917. static void copy_parameter_set(void **to, void **from, int count, int size)
  918. {
  919. int i;
  920. for (i=0; i<count; i++){
  921. if (to[i] && !from[i]) av_freep(&to[i]);
  922. else if (from[i] && !to[i]) to[i] = av_malloc(size);
  923. if (from[i]) memcpy(to[i], from[i], size);
  924. }
  925. }
  926. static int decode_init_thread_copy(AVCodecContext *avctx){
  927. H264Context *h= avctx->priv_data;
  928. if (!avctx->is_copy) return 0;
  929. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  930. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  931. return 0;
  932. }
  933. #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
  934. static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
  935. H264Context *h= dst->priv_data, *h1= src->priv_data;
  936. MpegEncContext * const s = &h->s, * const s1 = &h1->s;
  937. int inited = s->context_initialized, err;
  938. int i;
  939. if(dst == src || !s1->context_initialized) return 0;
  940. err = ff_mpeg_update_thread_context(dst, src);
  941. if(err) return err;
  942. //FIXME handle width/height changing
  943. if(!inited){
  944. for(i = 0; i < MAX_SPS_COUNT; i++)
  945. av_freep(h->sps_buffers + i);
  946. for(i = 0; i < MAX_PPS_COUNT; i++)
  947. av_freep(h->pps_buffers + i);
  948. memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
  949. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  950. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  951. ff_h264_alloc_tables(h);
  952. context_init(h);
  953. for(i=0; i<2; i++){
  954. h->rbsp_buffer[i] = NULL;
  955. h->rbsp_buffer_size[i] = 0;
  956. }
  957. h->thread_context[0] = h;
  958. // frame_start may not be called for the next thread (if it's decoding a bottom field)
  959. // so this has to be allocated here
  960. h->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  961. s->dsp.clear_blocks(h->mb);
  962. }
  963. //extradata/NAL handling
  964. h->is_avc = h1->is_avc;
  965. //SPS/PPS
  966. copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
  967. h->sps = h1->sps;
  968. copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
  969. h->pps = h1->pps;
  970. //Dequantization matrices
  971. //FIXME these are big - can they be only copied when PPS changes?
  972. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  973. for(i=0; i<6; i++)
  974. h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  975. for(i=0; i<2; i++)
  976. h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  977. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  978. //POC timing
  979. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  980. //reference lists
  981. copy_fields(h, h1, ref_count, intra_gb);
  982. copy_fields(h, h1, short_ref, cabac_init_idc);
  983. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  984. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  985. copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
  986. h->last_slice_type = h1->last_slice_type;
  987. if(!s->current_picture_ptr) return 0;
  988. if(!s->dropable) {
  989. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  990. h->prev_poc_msb = h->poc_msb;
  991. h->prev_poc_lsb = h->poc_lsb;
  992. }
  993. h->prev_frame_num_offset= h->frame_num_offset;
  994. h->prev_frame_num = h->frame_num;
  995. h->outputed_poc = h->next_outputed_poc;
  996. return 0;
  997. }
  998. int ff_h264_frame_start(H264Context *h){
  999. MpegEncContext * const s = &h->s;
  1000. int i;
  1001. if(MPV_frame_start(s, s->avctx) < 0)
  1002. return -1;
  1003. ff_er_frame_start(s);
  1004. /*
  1005. * MPV_frame_start uses pict_type to derive key_frame.
  1006. * This is incorrect for H.264; IDR markings must be used.
  1007. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1008. * See decode_nal_units().
  1009. */
  1010. s->current_picture_ptr->key_frame= 0;
  1011. s->current_picture_ptr->mmco_reset= 0;
  1012. assert(s->linesize && s->uvlinesize);
  1013. for(i=0; i<16; i++){
  1014. h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1015. h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1016. }
  1017. for(i=0; i<4; i++){
  1018. h->block_offset[16+i]=
  1019. h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1020. h->block_offset[24+16+i]=
  1021. h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1022. }
  1023. /* can't be in alloc_tables because linesize isn't known there.
  1024. * FIXME: redo bipred weight to not require extra buffer? */
  1025. for(i = 0; i < s->avctx->thread_count; i++)
  1026. if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
  1027. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  1028. /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
  1029. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
  1030. // s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
  1031. // We mark the current picture as non-reference after allocating it, so
  1032. // that if we break out due to an error it can be released automatically
  1033. // in the next MPV_frame_start().
  1034. // SVQ3 as well as most other codecs have only last/next/current and thus
  1035. // get released even with set reference, besides SVQ3 and others do not
  1036. // mark frames as reference later "naturally".
  1037. if(s->codec_id != CODEC_ID_SVQ3)
  1038. s->current_picture_ptr->reference= 0;
  1039. s->current_picture_ptr->field_poc[0]=
  1040. s->current_picture_ptr->field_poc[1]= INT_MAX;
  1041. h->next_output_pic = NULL;
  1042. assert(s->current_picture_ptr->long_ref==0);
  1043. return 0;
  1044. }
  1045. /**
  1046. * Run setup operations that must be run after slice header decoding.
  1047. * This includes finding the next displayed frame.
  1048. *
  1049. * @param h h264 master context
  1050. */
  1051. static void decode_postinit(H264Context *h){
  1052. MpegEncContext * const s = &h->s;
  1053. Picture *out = s->current_picture_ptr;
  1054. Picture *cur = s->current_picture_ptr;
  1055. int i, pics, out_of_order, out_idx;
  1056. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  1057. s->current_picture_ptr->pict_type= s->pict_type;
  1058. if (h->next_output_pic) return;
  1059. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  1060. //FIXME this allows the next thread to start once we encounter the first field of a PAFF packet
  1061. //This works if the next packet contains the second field. It does not work if both fields are
  1062. //in the same packet.
  1063. //ff_thread_finish_setup(s->avctx);
  1064. return;
  1065. }
  1066. cur->interlaced_frame = 0;
  1067. cur->repeat_pict = 0;
  1068. /* Signal interlacing information externally. */
  1069. /* Prioritize picture timing SEI information over used decoding process if it exists. */
  1070. if(h->sps.pic_struct_present_flag){
  1071. switch (h->sei_pic_struct)
  1072. {
  1073. case SEI_PIC_STRUCT_FRAME:
  1074. break;
  1075. case SEI_PIC_STRUCT_TOP_FIELD:
  1076. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1077. cur->interlaced_frame = 1;
  1078. break;
  1079. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1080. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1081. if (FIELD_OR_MBAFF_PICTURE)
  1082. cur->interlaced_frame = 1;
  1083. else
  1084. // try to flag soft telecine progressive
  1085. cur->interlaced_frame = h->prev_interlaced_frame;
  1086. break;
  1087. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1088. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1089. // Signal the possibility of telecined film externally (pic_struct 5,6)
  1090. // From these hints, let the applications decide if they apply deinterlacing.
  1091. cur->repeat_pict = 1;
  1092. break;
  1093. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1094. // Force progressive here, as doubling interlaced frame is a bad idea.
  1095. cur->repeat_pict = 2;
  1096. break;
  1097. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1098. cur->repeat_pict = 4;
  1099. break;
  1100. }
  1101. if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1102. cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
  1103. }else{
  1104. /* Derive interlacing flag from used decoding process. */
  1105. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1106. }
  1107. h->prev_interlaced_frame = cur->interlaced_frame;
  1108. if (cur->field_poc[0] != cur->field_poc[1]){
  1109. /* Derive top_field_first from field pocs. */
  1110. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1111. }else{
  1112. if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
  1113. /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
  1114. if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
  1115. || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1116. cur->top_field_first = 1;
  1117. else
  1118. cur->top_field_first = 0;
  1119. }else{
  1120. /* Most likely progressive */
  1121. cur->top_field_first = 0;
  1122. }
  1123. }
  1124. //FIXME do something with unavailable reference frames
  1125. /* Sort B-frames into display order */
  1126. if(h->sps.bitstream_restriction_flag
  1127. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  1128. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1129. s->low_delay = 0;
  1130. }
  1131. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  1132. && !h->sps.bitstream_restriction_flag){
  1133. s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
  1134. s->low_delay= 0;
  1135. }
  1136. pics = 0;
  1137. while(h->delayed_pic[pics]) pics++;
  1138. assert(pics <= MAX_DELAYED_PIC_COUNT);
  1139. h->delayed_pic[pics++] = cur;
  1140. if(cur->reference == 0)
  1141. cur->reference = DELAYED_PIC_REF;
  1142. out = h->delayed_pic[0];
  1143. out_idx = 0;
  1144. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  1145. if(h->delayed_pic[i]->poc < out->poc){
  1146. out = h->delayed_pic[i];
  1147. out_idx = i;
  1148. }
  1149. if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
  1150. h->next_outputed_poc= INT_MIN;
  1151. out_of_order = out->poc < h->next_outputed_poc;
  1152. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  1153. { }
  1154. else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
  1155. || (s->low_delay &&
  1156. ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
  1157. || cur->pict_type == FF_B_TYPE)))
  1158. {
  1159. s->low_delay = 0;
  1160. s->avctx->has_b_frames++;
  1161. }
  1162. if(out_of_order || pics > s->avctx->has_b_frames){
  1163. out->reference &= ~DELAYED_PIC_REF;
  1164. for(i=out_idx; h->delayed_pic[i]; i++)
  1165. h->delayed_pic[i] = h->delayed_pic[i+1];
  1166. }
  1167. if(!out_of_order && pics > s->avctx->has_b_frames){
  1168. h->next_output_pic = out;
  1169. if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
  1170. h->next_outputed_poc = INT_MIN;
  1171. } else
  1172. h->next_outputed_poc = out->poc;
  1173. }else{
  1174. av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
  1175. }
  1176. ff_thread_finish_setup(s->avctx);
  1177. }
  1178. static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
  1179. MpegEncContext * const s = &h->s;
  1180. uint8_t *top_border;
  1181. int top_idx = 1;
  1182. src_y -= linesize;
  1183. src_cb -= uvlinesize;
  1184. src_cr -= uvlinesize;
  1185. if(!simple && FRAME_MBAFF){
  1186. if(s->mb_y&1){
  1187. if(!MB_MBAFF){
  1188. top_border = h->top_borders[0][s->mb_x];
  1189. AV_COPY128(top_border, src_y + 15*linesize);
  1190. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1191. AV_COPY64(top_border+16, src_cb+7*uvlinesize);
  1192. AV_COPY64(top_border+24, src_cr+7*uvlinesize);
  1193. }
  1194. }
  1195. }else if(MB_MBAFF){
  1196. top_idx = 0;
  1197. }else
  1198. return;
  1199. }
  1200. top_border = h->top_borders[top_idx][s->mb_x];
  1201. // There are two lines saved, the line above the the top macroblock of a pair,
  1202. // and the line above the bottom macroblock
  1203. AV_COPY128(top_border, src_y + 16*linesize);
  1204. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1205. AV_COPY64(top_border+16, src_cb+8*uvlinesize);
  1206. AV_COPY64(top_border+24, src_cr+8*uvlinesize);
  1207. }
  1208. }
  1209. static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){
  1210. MpegEncContext * const s = &h->s;
  1211. int deblock_left;
  1212. int deblock_top;
  1213. int top_idx = 1;
  1214. uint8_t *top_border_m1;
  1215. uint8_t *top_border;
  1216. if(!simple && FRAME_MBAFF){
  1217. if(s->mb_y&1){
  1218. if(!MB_MBAFF)
  1219. return;
  1220. }else{
  1221. top_idx = MB_MBAFF ? 0 : 1;
  1222. }
  1223. }
  1224. if(h->deblocking_filter == 2) {
  1225. deblock_left = h->left_type[0];
  1226. deblock_top = h->top_type;
  1227. } else {
  1228. deblock_left = (s->mb_x > 0);
  1229. deblock_top = (s->mb_y > !!MB_FIELD);
  1230. }
  1231. src_y -= linesize + 1;
  1232. src_cb -= uvlinesize + 1;
  1233. src_cr -= uvlinesize + 1;
  1234. top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
  1235. top_border = h->top_borders[top_idx][s->mb_x];
  1236. #define XCHG(a,b,xchg)\
  1237. if (xchg) AV_SWAP64(b,a);\
  1238. else AV_COPY64(b,a);
  1239. if(deblock_top){
  1240. if(deblock_left){
  1241. XCHG(top_border_m1+8, src_y -7, 1);
  1242. }
  1243. XCHG(top_border+0, src_y +1, xchg);
  1244. XCHG(top_border+8, src_y +9, 1);
  1245. if(s->mb_x+1 < s->mb_width){
  1246. XCHG(h->top_borders[top_idx][s->mb_x+1], src_y +17, 1);
  1247. }
  1248. }
  1249. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1250. if(deblock_top){
  1251. if(deblock_left){
  1252. XCHG(top_border_m1+16, src_cb -7, 1);
  1253. XCHG(top_border_m1+24, src_cr -7, 1);
  1254. }
  1255. XCHG(top_border+16, src_cb+1, 1);
  1256. XCHG(top_border+24, src_cr+1, 1);
  1257. }
  1258. }
  1259. }
  1260. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
  1261. MpegEncContext * const s = &h->s;
  1262. const int mb_x= s->mb_x;
  1263. const int mb_y= s->mb_y;
  1264. const int mb_xy= h->mb_xy;
  1265. const int mb_type= s->current_picture.mb_type[mb_xy];
  1266. uint8_t *dest_y, *dest_cb, *dest_cr;
  1267. int linesize, uvlinesize /*dct_offset*/;
  1268. int i;
  1269. int *block_offset = &h->block_offset[0];
  1270. const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
  1271. /* is_h264 should always be true if SVQ3 is disabled. */
  1272. const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
  1273. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1274. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1275. dest_y = s->current_picture.data[0] + (mb_x + mb_y * s->linesize ) * 16;
  1276. dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
  1277. dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
  1278. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
  1279. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
  1280. h->list_counts[mb_xy]= h->list_count;
  1281. if (!simple && MB_FIELD) {
  1282. linesize = h->mb_linesize = s->linesize * 2;
  1283. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  1284. block_offset = &h->block_offset[24];
  1285. if(mb_y&1){ //FIXME move out of this function?
  1286. dest_y -= s->linesize*15;
  1287. dest_cb-= s->uvlinesize*7;
  1288. dest_cr-= s->uvlinesize*7;
  1289. }
  1290. if(FRAME_MBAFF) {
  1291. int list;
  1292. for(list=0; list<h->list_count; list++){
  1293. if(!USES_LIST(mb_type, list))
  1294. continue;
  1295. if(IS_16X16(mb_type)){
  1296. int8_t *ref = &h->ref_cache[list][scan8[0]];
  1297. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  1298. }else{
  1299. for(i=0; i<16; i+=4){
  1300. int ref = h->ref_cache[list][scan8[i]];
  1301. if(ref >= 0)
  1302. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  1303. }
  1304. }
  1305. }
  1306. }
  1307. } else {
  1308. linesize = h->mb_linesize = s->linesize;
  1309. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  1310. // dct_offset = s->linesize * 16;
  1311. }
  1312. if (!simple && IS_INTRA_PCM(mb_type)) {
  1313. for (i=0; i<16; i++) {
  1314. memcpy(dest_y + i* linesize, h->mb + i*8, 16);
  1315. }
  1316. for (i=0; i<8; i++) {
  1317. memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4, 8);
  1318. memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4, 8);
  1319. }
  1320. } else {
  1321. if(IS_INTRA(mb_type)){
  1322. if(h->deblocking_filter)
  1323. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
  1324. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1325. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  1326. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  1327. }
  1328. if(IS_INTRA4x4(mb_type)){
  1329. if(simple || !s->encoding){
  1330. if(IS_8x8DCT(mb_type)){
  1331. if(transform_bypass){
  1332. idct_dc_add =
  1333. idct_add = s->dsp.add_pixels8;
  1334. }else{
  1335. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1336. idct_add = h->h264dsp.h264_idct8_add;
  1337. }
  1338. for(i=0; i<16; i+=4){
  1339. uint8_t * const ptr= dest_y + block_offset[i];
  1340. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1341. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1342. h->hpc.pred8x8l_add[dir](ptr, h->mb + i*16, linesize);
  1343. }else{
  1344. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  1345. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  1346. (h->topright_samples_available<<i)&0x4000, linesize);
  1347. if(nnz){
  1348. if(nnz == 1 && h->mb[i*16])
  1349. idct_dc_add(ptr, h->mb + i*16, linesize);
  1350. else
  1351. idct_add (ptr, h->mb + i*16, linesize);
  1352. }
  1353. }
  1354. }
  1355. }else{
  1356. if(transform_bypass){
  1357. idct_dc_add =
  1358. idct_add = s->dsp.add_pixels4;
  1359. }else{
  1360. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1361. idct_add = h->h264dsp.h264_idct_add;
  1362. }
  1363. for(i=0; i<16; i++){
  1364. uint8_t * const ptr= dest_y + block_offset[i];
  1365. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1366. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1367. h->hpc.pred4x4_add[dir](ptr, h->mb + i*16, linesize);
  1368. }else{
  1369. uint8_t *topright;
  1370. int nnz, tr;
  1371. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  1372. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  1373. assert(mb_y || linesize <= block_offset[i]);
  1374. if(!topright_avail){
  1375. tr= ptr[3 - linesize]*0x01010101;
  1376. topright= (uint8_t*) &tr;
  1377. }else
  1378. topright= ptr + 4 - linesize;
  1379. }else
  1380. topright= NULL;
  1381. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  1382. nnz = h->non_zero_count_cache[ scan8[i] ];
  1383. if(nnz){
  1384. if(is_h264){
  1385. if(nnz == 1 && h->mb[i*16])
  1386. idct_dc_add(ptr, h->mb + i*16, linesize);
  1387. else
  1388. idct_add (ptr, h->mb + i*16, linesize);
  1389. }
  1390. #if CONFIG_SVQ3_DECODER
  1391. else
  1392. ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  1393. #endif
  1394. }
  1395. }
  1396. }
  1397. }
  1398. }
  1399. }else{
  1400. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  1401. if(is_h264){
  1402. if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
  1403. if(!transform_bypass)
  1404. h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
  1405. else{
  1406. static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
  1407. 8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
  1408. for(i = 0; i < 16; i++)
  1409. h->mb[dc_mapping[i]] = h->mb_luma_dc[i];
  1410. }
  1411. }
  1412. }
  1413. #if CONFIG_SVQ3_DECODER
  1414. else
  1415. ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
  1416. #endif
  1417. }
  1418. if(h->deblocking_filter)
  1419. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
  1420. }else if(is_h264){
  1421. hl_motion(h, dest_y, dest_cb, dest_cr,
  1422. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1423. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1424. h->h264dsp.weight_h264_pixels_tab, h->h264dsp.biweight_h264_pixels_tab);
  1425. }
  1426. if(!IS_INTRA4x4(mb_type)){
  1427. if(is_h264){
  1428. if(IS_INTRA16x16(mb_type)){
  1429. if(transform_bypass){
  1430. if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
  1431. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
  1432. }else{
  1433. for(i=0; i<16; i++){
  1434. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
  1435. s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + i*16, linesize);
  1436. }
  1437. }
  1438. }else{
  1439. h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1440. }
  1441. }else if(h->cbp&15){
  1442. if(transform_bypass){
  1443. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1444. idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  1445. for(i=0; i<16; i+=di){
  1446. if(h->non_zero_count_cache[ scan8[i] ]){
  1447. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  1448. }
  1449. }
  1450. }else{
  1451. if(IS_8x8DCT(mb_type)){
  1452. h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1453. }else{
  1454. h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1455. }
  1456. }
  1457. }
  1458. }
  1459. #if CONFIG_SVQ3_DECODER
  1460. else{
  1461. for(i=0; i<16; i++){
  1462. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  1463. uint8_t * const ptr= dest_y + block_offset[i];
  1464. ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1465. }
  1466. }
  1467. }
  1468. #endif
  1469. }
  1470. if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
  1471. uint8_t *dest[2] = {dest_cb, dest_cr};
  1472. if(transform_bypass){
  1473. if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
  1474. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + 16*16, uvlinesize);
  1475. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + 20*16, uvlinesize);
  1476. }else{
  1477. idct_add = s->dsp.add_pixels4;
  1478. for(i=16; i<16+8; i++){
  1479. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
  1480. idct_add (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  1481. }
  1482. }
  1483. }else{
  1484. if(is_h264){
  1485. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
  1486. chroma_dc_dequant_idct_c(h->mb + 16*16 , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  1487. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
  1488. chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  1489. h->h264dsp.h264_idct_add8(dest, block_offset,
  1490. h->mb, uvlinesize,
  1491. h->non_zero_count_cache);
  1492. }
  1493. #if CONFIG_SVQ3_DECODER
  1494. else{
  1495. chroma_dc_dequant_idct_c(h->mb + 16*16 , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  1496. chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  1497. for(i=16; i<16+8; i++){
  1498. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  1499. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  1500. ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[s->qscale + 12] - 12, 2);
  1501. }
  1502. }
  1503. }
  1504. #endif
  1505. }
  1506. }
  1507. }
  1508. if(h->cbp || IS_INTRA(mb_type))
  1509. s->dsp.clear_blocks(h->mb);
  1510. }
  1511. /**
  1512. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  1513. */
  1514. static void hl_decode_mb_simple(H264Context *h){
  1515. hl_decode_mb_internal(h, 1);
  1516. }
  1517. /**
  1518. * Process a macroblock; this handles edge cases, such as interlacing.
  1519. */
  1520. static void av_noinline hl_decode_mb_complex(H264Context *h){
  1521. hl_decode_mb_internal(h, 0);
  1522. }
  1523. void ff_h264_hl_decode_mb(H264Context *h){
  1524. MpegEncContext * const s = &h->s;
  1525. const int mb_xy= h->mb_xy;
  1526. const int mb_type= s->current_picture.mb_type[mb_xy];
  1527. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
  1528. if (is_complex)
  1529. hl_decode_mb_complex(h);
  1530. else hl_decode_mb_simple(h);
  1531. }
  1532. static int pred_weight_table(H264Context *h){
  1533. MpegEncContext * const s = &h->s;
  1534. int list, i;
  1535. int luma_def, chroma_def;
  1536. h->use_weight= 0;
  1537. h->use_weight_chroma= 0;
  1538. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  1539. if(CHROMA)
  1540. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  1541. luma_def = 1<<h->luma_log2_weight_denom;
  1542. chroma_def = 1<<h->chroma_log2_weight_denom;
  1543. for(list=0; list<2; list++){
  1544. h->luma_weight_flag[list] = 0;
  1545. h->chroma_weight_flag[list] = 0;
  1546. for(i=0; i<h->ref_count[list]; i++){
  1547. int luma_weight_flag, chroma_weight_flag;
  1548. luma_weight_flag= get_bits1(&s->gb);
  1549. if(luma_weight_flag){
  1550. h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
  1551. h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
  1552. if( h->luma_weight[i][list][0] != luma_def
  1553. || h->luma_weight[i][list][1] != 0) {
  1554. h->use_weight= 1;
  1555. h->luma_weight_flag[list]= 1;
  1556. }
  1557. }else{
  1558. h->luma_weight[i][list][0]= luma_def;
  1559. h->luma_weight[i][list][1]= 0;
  1560. }
  1561. if(CHROMA){
  1562. chroma_weight_flag= get_bits1(&s->gb);
  1563. if(chroma_weight_flag){
  1564. int j;
  1565. for(j=0; j<2; j++){
  1566. h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
  1567. h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
  1568. if( h->chroma_weight[i][list][j][0] != chroma_def
  1569. || h->chroma_weight[i][list][j][1] != 0) {
  1570. h->use_weight_chroma= 1;
  1571. h->chroma_weight_flag[list]= 1;
  1572. }
  1573. }
  1574. }else{
  1575. int j;
  1576. for(j=0; j<2; j++){
  1577. h->chroma_weight[i][list][j][0]= chroma_def;
  1578. h->chroma_weight[i][list][j][1]= 0;
  1579. }
  1580. }
  1581. }
  1582. }
  1583. if(h->slice_type_nos != FF_B_TYPE) break;
  1584. }
  1585. h->use_weight= h->use_weight || h->use_weight_chroma;
  1586. return 0;
  1587. }
  1588. /**
  1589. * Initialize implicit_weight table.
  1590. * @param field 0/1 initialize the weight for interlaced MBAFF
  1591. * -1 initializes the rest
  1592. */
  1593. static void implicit_weight_table(H264Context *h, int field){
  1594. MpegEncContext * const s = &h->s;
  1595. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  1596. for (i = 0; i < 2; i++) {
  1597. h->luma_weight_flag[i] = 0;
  1598. h->chroma_weight_flag[i] = 0;
  1599. }
  1600. if(field < 0){
  1601. cur_poc = s->current_picture_ptr->poc;
  1602. if( h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
  1603. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  1604. h->use_weight= 0;
  1605. h->use_weight_chroma= 0;
  1606. return;
  1607. }
  1608. ref_start= 0;
  1609. ref_count0= h->ref_count[0];
  1610. ref_count1= h->ref_count[1];
  1611. }else{
  1612. cur_poc = s->current_picture_ptr->field_poc[field];
  1613. ref_start= 16;
  1614. ref_count0= 16+2*h->ref_count[0];
  1615. ref_count1= 16+2*h->ref_count[1];
  1616. }
  1617. h->use_weight= 2;
  1618. h->use_weight_chroma= 2;
  1619. h->luma_log2_weight_denom= 5;
  1620. h->chroma_log2_weight_denom= 5;
  1621. for(ref0=ref_start; ref0 < ref_count0; ref0++){
  1622. int poc0 = h->ref_list[0][ref0].poc;
  1623. for(ref1=ref_start; ref1 < ref_count1; ref1++){
  1624. int poc1 = h->ref_list[1][ref1].poc;
  1625. int td = av_clip(poc1 - poc0, -128, 127);
  1626. int w= 32;
  1627. if(td){
  1628. int tb = av_clip(cur_poc - poc0, -128, 127);
  1629. int tx = (16384 + (FFABS(td) >> 1)) / td;
  1630. int dist_scale_factor = (tb*tx + 32) >> 8;
  1631. if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
  1632. w = 64 - dist_scale_factor;
  1633. }
  1634. if(field<0){
  1635. h->implicit_weight[ref0][ref1][0]=
  1636. h->implicit_weight[ref0][ref1][1]= w;
  1637. }else{
  1638. h->implicit_weight[ref0][ref1][field]=w;
  1639. }
  1640. }
  1641. }
  1642. }
  1643. /**
  1644. * instantaneous decoder refresh.
  1645. */
  1646. static void idr(H264Context *h){
  1647. ff_h264_remove_all_refs(h);
  1648. h->prev_frame_num= 0;
  1649. h->prev_frame_num_offset= 0;
  1650. h->prev_poc_msb=
  1651. h->prev_poc_lsb= 0;
  1652. }
  1653. /* forget old pics after a seek */
  1654. static void flush_dpb(AVCodecContext *avctx){
  1655. H264Context *h= avctx->priv_data;
  1656. int i;
  1657. for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
  1658. if(h->delayed_pic[i])
  1659. h->delayed_pic[i]->reference= 0;
  1660. h->delayed_pic[i]= NULL;
  1661. }
  1662. h->outputed_poc=h->next_outputed_poc= INT_MIN;
  1663. h->prev_interlaced_frame = 1;
  1664. idr(h);
  1665. if(h->s.current_picture_ptr)
  1666. h->s.current_picture_ptr->reference= 0;
  1667. h->s.first_field= 0;
  1668. ff_h264_reset_sei(h);
  1669. ff_mpeg_flush(avctx);
  1670. }
  1671. static int init_poc(H264Context *h){
  1672. MpegEncContext * const s = &h->s;
  1673. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  1674. int field_poc[2];
  1675. Picture *cur = s->current_picture_ptr;
  1676. h->frame_num_offset= h->prev_frame_num_offset;
  1677. if(h->frame_num < h->prev_frame_num)
  1678. h->frame_num_offset += max_frame_num;
  1679. if(h->sps.poc_type==0){
  1680. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  1681. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  1682. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  1683. else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  1684. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  1685. else
  1686. h->poc_msb = h->prev_poc_msb;
  1687. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  1688. field_poc[0] =
  1689. field_poc[1] = h->poc_msb + h->poc_lsb;
  1690. if(s->picture_structure == PICT_FRAME)
  1691. field_poc[1] += h->delta_poc_bottom;
  1692. }else if(h->sps.poc_type==1){
  1693. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1694. int i;
  1695. if(h->sps.poc_cycle_length != 0)
  1696. abs_frame_num = h->frame_num_offset + h->frame_num;
  1697. else
  1698. abs_frame_num = 0;
  1699. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  1700. abs_frame_num--;
  1701. expected_delta_per_poc_cycle = 0;
  1702. for(i=0; i < h->sps.poc_cycle_length; i++)
  1703. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  1704. if(abs_frame_num > 0){
  1705. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1706. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1707. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1708. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  1709. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  1710. } else
  1711. expectedpoc = 0;
  1712. if(h->nal_ref_idc == 0)
  1713. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1714. field_poc[0] = expectedpoc + h->delta_poc[0];
  1715. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1716. if(s->picture_structure == PICT_FRAME)
  1717. field_poc[1] += h->delta_poc[1];
  1718. }else{
  1719. int poc= 2*(h->frame_num_offset + h->frame_num);
  1720. if(!h->nal_ref_idc)
  1721. poc--;
  1722. field_poc[0]= poc;
  1723. field_poc[1]= poc;
  1724. }
  1725. if(s->picture_structure != PICT_BOTTOM_FIELD)
  1726. s->current_picture_ptr->field_poc[0]= field_poc[0];
  1727. if(s->picture_structure != PICT_TOP_FIELD)
  1728. s->current_picture_ptr->field_poc[1]= field_poc[1];
  1729. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  1730. return 0;
  1731. }
  1732. /**
  1733. * initialize scan tables
  1734. */
  1735. static void init_scan_tables(H264Context *h){
  1736. int i;
  1737. for(i=0; i<16; i++){
  1738. #define T(x) (x>>2) | ((x<<2) & 0xF)
  1739. h->zigzag_scan[i] = T(zigzag_scan[i]);
  1740. h-> field_scan[i] = T( field_scan[i]);
  1741. #undef T
  1742. }
  1743. for(i=0; i<64; i++){
  1744. #define T(x) (x>>3) | ((x&7)<<3)
  1745. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  1746. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  1747. h->field_scan8x8[i] = T(field_scan8x8[i]);
  1748. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  1749. #undef T
  1750. }
  1751. if(h->sps.transform_bypass){ //FIXME same ugly
  1752. h->zigzag_scan_q0 = zigzag_scan;
  1753. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  1754. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  1755. h->field_scan_q0 = field_scan;
  1756. h->field_scan8x8_q0 = field_scan8x8;
  1757. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  1758. }else{
  1759. h->zigzag_scan_q0 = h->zigzag_scan;
  1760. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  1761. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  1762. h->field_scan_q0 = h->field_scan;
  1763. h->field_scan8x8_q0 = h->field_scan8x8;
  1764. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  1765. }
  1766. }
  1767. static void field_end(H264Context *h, int in_setup){
  1768. MpegEncContext * const s = &h->s;
  1769. AVCodecContext * const avctx= s->avctx;
  1770. s->mb_y= 0;
  1771. if (!in_setup && !s->dropable)
  1772. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
  1773. s->picture_structure==PICT_BOTTOM_FIELD);
  1774. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  1775. ff_vdpau_h264_set_reference_frames(s);
  1776. if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
  1777. if(!s->dropable) {
  1778. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1779. h->prev_poc_msb= h->poc_msb;
  1780. h->prev_poc_lsb= h->poc_lsb;
  1781. }
  1782. h->prev_frame_num_offset= h->frame_num_offset;
  1783. h->prev_frame_num= h->frame_num;
  1784. h->outputed_poc = h->next_outputed_poc;
  1785. }
  1786. if (avctx->hwaccel) {
  1787. if (avctx->hwaccel->end_frame(avctx) < 0)
  1788. av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
  1789. }
  1790. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  1791. ff_vdpau_h264_picture_complete(s);
  1792. /*
  1793. * FIXME: Error handling code does not seem to support interlaced
  1794. * when slices span multiple rows
  1795. * The ff_er_add_slice calls don't work right for bottom
  1796. * fields; they cause massive erroneous error concealing
  1797. * Error marking covers both fields (top and bottom).
  1798. * This causes a mismatched s->error_count
  1799. * and a bad error table. Further, the error count goes to
  1800. * INT_MAX when called for bottom field, because mb_y is
  1801. * past end by one (callers fault) and resync_mb_y != 0
  1802. * causes problems for the first MB line, too.
  1803. */
  1804. if (!FIELD_PICTURE)
  1805. ff_er_frame_end(s);
  1806. MPV_frame_end(s);
  1807. h->current_slice=0;
  1808. }
  1809. /**
  1810. * Replicate H264 "master" context to thread contexts.
  1811. */
  1812. static void clone_slice(H264Context *dst, H264Context *src)
  1813. {
  1814. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  1815. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  1816. dst->s.current_picture = src->s.current_picture;
  1817. dst->s.linesize = src->s.linesize;
  1818. dst->s.uvlinesize = src->s.uvlinesize;
  1819. dst->s.first_field = src->s.first_field;
  1820. dst->prev_poc_msb = src->prev_poc_msb;
  1821. dst->prev_poc_lsb = src->prev_poc_lsb;
  1822. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  1823. dst->prev_frame_num = src->prev_frame_num;
  1824. dst->short_ref_count = src->short_ref_count;
  1825. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  1826. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  1827. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  1828. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  1829. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  1830. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  1831. }
  1832. /**
  1833. * computes profile from profile_idc and constraint_set?_flags
  1834. *
  1835. * @param sps SPS
  1836. *
  1837. * @return profile as defined by FF_PROFILE_H264_*
  1838. */
  1839. int ff_h264_get_profile(SPS *sps)
  1840. {
  1841. int profile = sps->profile_idc;
  1842. switch(sps->profile_idc) {
  1843. case FF_PROFILE_H264_BASELINE:
  1844. // constraint_set1_flag set to 1
  1845. profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1846. break;
  1847. case FF_PROFILE_H264_HIGH_10:
  1848. case FF_PROFILE_H264_HIGH_422:
  1849. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1850. // constraint_set3_flag set to 1
  1851. profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
  1852. break;
  1853. }
  1854. return profile;
  1855. }
  1856. /**
  1857. * decodes a slice header.
  1858. * This will also call MPV_common_init() and frame_start() as needed.
  1859. *
  1860. * @param h h264context
  1861. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  1862. *
  1863. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  1864. */
  1865. static int decode_slice_header(H264Context *h, H264Context *h0){
  1866. MpegEncContext * const s = &h->s;
  1867. MpegEncContext * const s0 = &h0->s;
  1868. unsigned int first_mb_in_slice;
  1869. unsigned int pps_id;
  1870. int num_ref_idx_active_override_flag;
  1871. unsigned int slice_type, tmp, i, j;
  1872. int default_ref_list_done = 0;
  1873. int last_pic_structure;
  1874. s->dropable= h->nal_ref_idc == 0;
  1875. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  1876. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  1877. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  1878. }else{
  1879. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  1880. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  1881. }
  1882. first_mb_in_slice= get_ue_golomb(&s->gb);
  1883. if(first_mb_in_slice == 0){ //FIXME better field boundary detection
  1884. if(h0->current_slice && FIELD_PICTURE){
  1885. field_end(h, 1);
  1886. }
  1887. h0->current_slice = 0;
  1888. if (!s0->first_field)
  1889. s->current_picture_ptr= NULL;
  1890. }
  1891. slice_type= get_ue_golomb_31(&s->gb);
  1892. if(slice_type > 9){
  1893. 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);
  1894. return -1;
  1895. }
  1896. if(slice_type > 4){
  1897. slice_type -= 5;
  1898. h->slice_type_fixed=1;
  1899. }else
  1900. h->slice_type_fixed=0;
  1901. slice_type= golomb_to_pict_type[ slice_type ];
  1902. if (slice_type == FF_I_TYPE
  1903. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  1904. default_ref_list_done = 1;
  1905. }
  1906. h->slice_type= slice_type;
  1907. h->slice_type_nos= slice_type & 3;
  1908. s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
  1909. pps_id= get_ue_golomb(&s->gb);
  1910. if(pps_id>=MAX_PPS_COUNT){
  1911. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  1912. return -1;
  1913. }
  1914. if(!h0->pps_buffers[pps_id]) {
  1915. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
  1916. return -1;
  1917. }
  1918. h->pps= *h0->pps_buffers[pps_id];
  1919. if(!h0->sps_buffers[h->pps.sps_id]) {
  1920. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
  1921. return -1;
  1922. }
  1923. h->sps = *h0->sps_buffers[h->pps.sps_id];
  1924. s->avctx->profile = ff_h264_get_profile(&h->sps);
  1925. s->avctx->level = h->sps.level_idc;
  1926. s->avctx->refs = h->sps.ref_frame_count;
  1927. if(h == h0 && h->dequant_coeff_pps != pps_id){
  1928. h->dequant_coeff_pps = pps_id;
  1929. init_dequant_tables(h);
  1930. }
  1931. s->mb_width= h->sps.mb_width;
  1932. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  1933. h->b_stride= s->mb_width*4;
  1934. s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
  1935. if(h->sps.frame_mbs_only_flag)
  1936. s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
  1937. else
  1938. s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
  1939. if (s->context_initialized
  1940. && ( s->width != s->avctx->width || s->height != s->avctx->height
  1941. || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
  1942. if(h != h0) {
  1943. av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
  1944. return -1; // width / height changed during parallelized decoding
  1945. }
  1946. free_tables(h, 0);
  1947. flush_dpb(s->avctx);
  1948. MPV_common_end(s);
  1949. }
  1950. if (!s->context_initialized) {
  1951. if(h != h0){
  1952. av_log(h->s.avctx, AV_LOG_ERROR, "we cant (re-)initialize context during parallel decoding\n");
  1953. return -1;
  1954. }
  1955. avcodec_set_dimensions(s->avctx, s->width, s->height);
  1956. s->avctx->sample_aspect_ratio= h->sps.sar;
  1957. av_assert0(s->avctx->sample_aspect_ratio.den);
  1958. if(h->sps.video_signal_type_present_flag){
  1959. s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  1960. if(h->sps.colour_description_present_flag){
  1961. s->avctx->color_primaries = h->sps.color_primaries;
  1962. s->avctx->color_trc = h->sps.color_trc;
  1963. s->avctx->colorspace = h->sps.colorspace;
  1964. }
  1965. }
  1966. if(h->sps.timing_info_present_flag){
  1967. int64_t den= h->sps.time_scale;
  1968. if(h->x264_build < 44U)
  1969. den *= 2;
  1970. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  1971. h->sps.num_units_in_tick, den, 1<<30);
  1972. }
  1973. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  1974. s->avctx->codec->pix_fmts ?
  1975. s->avctx->codec->pix_fmts :
  1976. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  1977. hwaccel_pixfmt_list_h264_jpeg_420 :
  1978. ff_hwaccel_pixfmt_list_420);
  1979. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  1980. if (MPV_common_init(s) < 0){
  1981. av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
  1982. return -1;
  1983. }
  1984. s->first_field = 0;
  1985. h->prev_interlaced_frame = 1;
  1986. init_scan_tables(h);
  1987. ff_h264_alloc_tables(h);
  1988. if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
  1989. if (context_init(h) < 0){
  1990. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
  1991. return -1;
  1992. }
  1993. } else {
  1994. for(i = 1; i < s->avctx->thread_count; i++) {
  1995. H264Context *c;
  1996. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  1997. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  1998. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  1999. c->h264dsp = h->h264dsp;
  2000. c->sps = h->sps;
  2001. c->pps = h->pps;
  2002. init_scan_tables(c);
  2003. clone_tables(c, h, i);
  2004. }
  2005. for(i = 0; i < s->avctx->thread_count; i++)
  2006. if(context_init(h->thread_context[i]) < 0){
  2007. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
  2008. return -1;
  2009. }
  2010. }
  2011. }
  2012. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  2013. h->mb_mbaff = 0;
  2014. h->mb_aff_frame = 0;
  2015. last_pic_structure = s0->picture_structure;
  2016. if(h->sps.frame_mbs_only_flag){
  2017. s->picture_structure= PICT_FRAME;
  2018. }else{
  2019. if(get_bits1(&s->gb)) { //field_pic_flag
  2020. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  2021. } else {
  2022. s->picture_structure= PICT_FRAME;
  2023. h->mb_aff_frame = h->sps.mb_aff;
  2024. }
  2025. }
  2026. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  2027. if(h0->current_slice == 0){
  2028. if(h->frame_num != h->prev_frame_num &&
  2029. (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
  2030. h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
  2031. while(h->frame_num != h->prev_frame_num &&
  2032. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  2033. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2034. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  2035. if (ff_h264_frame_start(h) < 0)
  2036. return -1;
  2037. h->prev_frame_num++;
  2038. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  2039. s->current_picture_ptr->frame_num= h->prev_frame_num;
  2040. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
  2041. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
  2042. ff_generate_sliding_window_mmcos(h);
  2043. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2044. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2045. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2046. * about there being no actual duplicates.
  2047. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2048. * concealing a lost frame, this probably isn't noticable by comparison, but it should
  2049. * be fixed. */
  2050. if (h->short_ref_count) {
  2051. if (prev) {
  2052. av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
  2053. (const uint8_t**)prev->data, prev->linesize,
  2054. s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
  2055. h->short_ref[0]->poc = prev->poc+2;
  2056. }
  2057. h->short_ref[0]->frame_num = h->prev_frame_num;
  2058. }
  2059. }
  2060. /* See if we have a decoded first field looking for a pair... */
  2061. if (s0->first_field) {
  2062. assert(s0->current_picture_ptr);
  2063. assert(s0->current_picture_ptr->data[0]);
  2064. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  2065. /* figure out if we have a complementary field pair */
  2066. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2067. /*
  2068. * Previous field is unmatched. Don't display it, but let it
  2069. * remain for reference if marked as such.
  2070. */
  2071. s0->current_picture_ptr = NULL;
  2072. s0->first_field = FIELD_PICTURE;
  2073. } else {
  2074. if (h->nal_ref_idc &&
  2075. s0->current_picture_ptr->reference &&
  2076. s0->current_picture_ptr->frame_num != h->frame_num) {
  2077. /*
  2078. * This and previous field were reference, but had
  2079. * different frame_nums. Consider this field first in
  2080. * pair. Throw away previous field except for reference
  2081. * purposes.
  2082. */
  2083. s0->first_field = 1;
  2084. s0->current_picture_ptr = NULL;
  2085. } else {
  2086. /* Second field in complementary pair */
  2087. s0->first_field = 0;
  2088. }
  2089. }
  2090. } else {
  2091. /* Frame or first field in a potentially complementary pair */
  2092. assert(!s0->current_picture_ptr);
  2093. s0->first_field = FIELD_PICTURE;
  2094. }
  2095. if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
  2096. s0->first_field = 0;
  2097. return -1;
  2098. }
  2099. }
  2100. if(h != h0)
  2101. clone_slice(h, h0);
  2102. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  2103. assert(s->mb_num == s->mb_width * s->mb_height);
  2104. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2105. first_mb_in_slice >= s->mb_num){
  2106. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2107. return -1;
  2108. }
  2109. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2110. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2111. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2112. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2113. assert(s->mb_y < s->mb_height);
  2114. if(s->picture_structure==PICT_FRAME){
  2115. h->curr_pic_num= h->frame_num;
  2116. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  2117. }else{
  2118. h->curr_pic_num= 2*h->frame_num + 1;
  2119. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  2120. }
  2121. if(h->nal_unit_type == NAL_IDR_SLICE){
  2122. get_ue_golomb(&s->gb); /* idr_pic_id */
  2123. }
  2124. if(h->sps.poc_type==0){
  2125. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2126. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  2127. h->delta_poc_bottom= get_se_golomb(&s->gb);
  2128. }
  2129. }
  2130. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  2131. h->delta_poc[0]= get_se_golomb(&s->gb);
  2132. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  2133. h->delta_poc[1]= get_se_golomb(&s->gb);
  2134. }
  2135. init_poc(h);
  2136. if(h->pps.redundant_pic_cnt_present){
  2137. h->redundant_pic_count= get_ue_golomb(&s->gb);
  2138. }
  2139. //set defaults, might be overridden a few lines later
  2140. h->ref_count[0]= h->pps.ref_count[0];
  2141. h->ref_count[1]= h->pps.ref_count[1];
  2142. if(h->slice_type_nos != FF_I_TYPE){
  2143. if(h->slice_type_nos == FF_B_TYPE){
  2144. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  2145. }
  2146. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  2147. if(num_ref_idx_active_override_flag){
  2148. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  2149. if(h->slice_type_nos==FF_B_TYPE)
  2150. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  2151. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  2152. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  2153. h->ref_count[0]= h->ref_count[1]= 1;
  2154. return -1;
  2155. }
  2156. }
  2157. if(h->slice_type_nos == FF_B_TYPE)
  2158. h->list_count= 2;
  2159. else
  2160. h->list_count= 1;
  2161. }else
  2162. h->list_count= 0;
  2163. if(!default_ref_list_done){
  2164. ff_h264_fill_default_ref_list(h);
  2165. }
  2166. if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
  2167. return -1;
  2168. if(h->slice_type_nos!=FF_I_TYPE){
  2169. s->last_picture_ptr= &h->ref_list[0][0];
  2170. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2171. }
  2172. if(h->slice_type_nos==FF_B_TYPE){
  2173. s->next_picture_ptr= &h->ref_list[1][0];
  2174. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2175. }
  2176. if( (h->pps.weighted_pred && h->slice_type_nos == FF_P_TYPE )
  2177. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
  2178. pred_weight_table(h);
  2179. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  2180. implicit_weight_table(h, -1);
  2181. }else {
  2182. h->use_weight = 0;
  2183. for (i = 0; i < 2; i++) {
  2184. h->luma_weight_flag[i] = 0;
  2185. h->chroma_weight_flag[i] = 0;
  2186. }
  2187. }
  2188. if(h->nal_ref_idc)
  2189. ff_h264_decode_ref_pic_marking(h0, &s->gb);
  2190. if(FRAME_MBAFF){
  2191. ff_h264_fill_mbaff_ref_list(h);
  2192. if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  2193. implicit_weight_table(h, 0);
  2194. implicit_weight_table(h, 1);
  2195. }
  2196. }
  2197. if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
  2198. ff_h264_direct_dist_scale_factor(h);
  2199. ff_h264_direct_ref_list_init(h);
  2200. if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
  2201. tmp = get_ue_golomb_31(&s->gb);
  2202. if(tmp > 2){
  2203. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2204. return -1;
  2205. }
  2206. h->cabac_init_idc= tmp;
  2207. }
  2208. h->last_qscale_diff = 0;
  2209. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2210. if(tmp>51){
  2211. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2212. return -1;
  2213. }
  2214. s->qscale= tmp;
  2215. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2216. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2217. //FIXME qscale / qp ... stuff
  2218. if(h->slice_type == FF_SP_TYPE){
  2219. get_bits1(&s->gb); /* sp_for_switch_flag */
  2220. }
  2221. if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
  2222. get_se_golomb(&s->gb); /* slice_qs_delta */
  2223. }
  2224. h->deblocking_filter = 1;
  2225. h->slice_alpha_c0_offset = 52;
  2226. h->slice_beta_offset = 52;
  2227. if( h->pps.deblocking_filter_parameters_present ) {
  2228. tmp= get_ue_golomb_31(&s->gb);
  2229. if(tmp > 2){
  2230. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  2231. return -1;
  2232. }
  2233. h->deblocking_filter= tmp;
  2234. if(h->deblocking_filter < 2)
  2235. h->deblocking_filter^= 1; // 1<->0
  2236. if( h->deblocking_filter ) {
  2237. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2238. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2239. if( h->slice_alpha_c0_offset > 104U
  2240. || h->slice_beta_offset > 104U){
  2241. 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);
  2242. return -1;
  2243. }
  2244. }
  2245. }
  2246. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  2247. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
  2248. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == FF_B_TYPE)
  2249. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2250. h->deblocking_filter= 0;
  2251. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2252. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2253. /* Cheat slightly for speed:
  2254. Do not bother to deblock across slices. */
  2255. h->deblocking_filter = 2;
  2256. } else {
  2257. h0->max_contexts = 1;
  2258. if(!h0->single_decode_warning) {
  2259. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2260. h0->single_decode_warning = 1;
  2261. }
  2262. if(h != h0){
  2263. av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
  2264. return 1;
  2265. }
  2266. }
  2267. }
  2268. h->qp_thresh= 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]);
  2269. #if 0 //FMO
  2270. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  2271. slice_group_change_cycle= get_bits(&s->gb, ?);
  2272. #endif
  2273. h0->last_slice_type = slice_type;
  2274. h->slice_num = ++h0->current_slice;
  2275. if(h->slice_num >= MAX_SLICES){
  2276. av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
  2277. }
  2278. for(j=0; j<2; j++){
  2279. int id_list[16];
  2280. int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
  2281. for(i=0; i<16; i++){
  2282. id_list[i]= 60;
  2283. if(h->ref_list[j][i].data[0]){
  2284. int k;
  2285. uint8_t *base= h->ref_list[j][i].base[0];
  2286. for(k=0; k<h->short_ref_count; k++)
  2287. if(h->short_ref[k]->base[0] == base){
  2288. id_list[i]= k;
  2289. break;
  2290. }
  2291. for(k=0; k<h->long_ref_count; k++)
  2292. if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
  2293. id_list[i]= h->short_ref_count + k;
  2294. break;
  2295. }
  2296. }
  2297. }
  2298. ref2frm[0]=
  2299. ref2frm[1]= -1;
  2300. for(i=0; i<16; i++)
  2301. ref2frm[i+2]= 4*id_list[i]
  2302. +(h->ref_list[j][i].reference&3);
  2303. ref2frm[18+0]=
  2304. ref2frm[18+1]= -1;
  2305. for(i=16; i<48; i++)
  2306. ref2frm[i+4]= 4*id_list[(i-16)>>1]
  2307. +(h->ref_list[j][i].reference&3);
  2308. }
  2309. //FIXME: fix draw_edges+PAFF+frame threads
  2310. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type&FF_THREAD_FRAME)) ? 0 : 16;
  2311. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2312. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  2313. 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",
  2314. h->slice_num,
  2315. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  2316. first_mb_in_slice,
  2317. av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2318. pps_id, h->frame_num,
  2319. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  2320. h->ref_count[0], h->ref_count[1],
  2321. s->qscale,
  2322. h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
  2323. h->use_weight,
  2324. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  2325. h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  2326. );
  2327. }
  2328. return 0;
  2329. }
  2330. int ff_h264_get_slice_type(const H264Context *h)
  2331. {
  2332. switch (h->slice_type) {
  2333. case FF_P_TYPE: return 0;
  2334. case FF_B_TYPE: return 1;
  2335. case FF_I_TYPE: return 2;
  2336. case FF_SP_TYPE: return 3;
  2337. case FF_SI_TYPE: return 4;
  2338. default: return -1;
  2339. }
  2340. }
  2341. /**
  2342. *
  2343. * @return non zero if the loop filter can be skiped
  2344. */
  2345. static int fill_filter_caches(H264Context *h, int mb_type){
  2346. MpegEncContext * const s = &h->s;
  2347. const int mb_xy= h->mb_xy;
  2348. int top_xy, left_xy[2];
  2349. int top_type, left_type[2];
  2350. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2351. //FIXME deblocking could skip the intra and nnz parts.
  2352. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2353. * stuff, I can't imagine that these complex rules are worth it. */
  2354. left_xy[1] = left_xy[0] = mb_xy-1;
  2355. if(FRAME_MBAFF){
  2356. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
  2357. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2358. if(s->mb_y&1){
  2359. if (left_mb_field_flag != curr_mb_field_flag) {
  2360. left_xy[0] -= s->mb_stride;
  2361. }
  2362. }else{
  2363. if(curr_mb_field_flag){
  2364. top_xy += s->mb_stride & (((s->current_picture.mb_type[top_xy ]>>7)&1)-1);
  2365. }
  2366. if (left_mb_field_flag != curr_mb_field_flag) {
  2367. left_xy[1] += s->mb_stride;
  2368. }
  2369. }
  2370. }
  2371. h->top_mb_xy = top_xy;
  2372. h->left_mb_xy[0] = left_xy[0];
  2373. h->left_mb_xy[1] = left_xy[1];
  2374. {
  2375. //for sufficiently low qp, filtering wouldn't do anything
  2376. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  2377. int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
  2378. int qp = s->current_picture.qscale_table[mb_xy];
  2379. if(qp <= qp_thresh
  2380. && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
  2381. && (top_xy < 0 || ((qp + s->current_picture.qscale_table[top_xy ] + 1)>>1) <= qp_thresh)){
  2382. if(!FRAME_MBAFF)
  2383. return 1;
  2384. if( (left_xy[0]< 0 || ((qp + s->current_picture.qscale_table[left_xy[1] ] + 1)>>1) <= qp_thresh)
  2385. && (top_xy < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy -s->mb_stride] + 1)>>1) <= qp_thresh))
  2386. return 1;
  2387. }
  2388. }
  2389. top_type = s->current_picture.mb_type[top_xy] ;
  2390. left_type[0] = s->current_picture.mb_type[left_xy[0]];
  2391. left_type[1] = s->current_picture.mb_type[left_xy[1]];
  2392. if(h->deblocking_filter == 2){
  2393. if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
  2394. if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
  2395. }else{
  2396. if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
  2397. if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
  2398. }
  2399. h->top_type = top_type ;
  2400. h->left_type[0]= left_type[0];
  2401. h->left_type[1]= left_type[1];
  2402. if(IS_INTRA(mb_type))
  2403. return 0;
  2404. AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
  2405. AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
  2406. AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
  2407. AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
  2408. AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
  2409. h->cbp= h->cbp_table[mb_xy];
  2410. {
  2411. int list;
  2412. for(list=0; list<h->list_count; list++){
  2413. int8_t *ref;
  2414. int y, b_stride;
  2415. int16_t (*mv_dst)[2];
  2416. int16_t (*mv_src)[2];
  2417. if(!USES_LIST(mb_type, list)){
  2418. fill_rectangle( h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
  2419. AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2420. AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2421. AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2422. AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2423. continue;
  2424. }
  2425. ref = &s->current_picture.ref_index[list][4*mb_xy];
  2426. {
  2427. int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2428. AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2429. AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2430. ref += 2;
  2431. AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2432. AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2433. }
  2434. b_stride = h->b_stride;
  2435. mv_dst = &h->mv_cache[list][scan8[0]];
  2436. mv_src = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
  2437. for(y=0; y<4; y++){
  2438. AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
  2439. }
  2440. }
  2441. }
  2442. /*
  2443. 0 . T T. T T T T
  2444. 1 L . .L . . . .
  2445. 2 L . .L . . . .
  2446. 3 . T TL . . . .
  2447. 4 L . .L . . . .
  2448. 5 L . .. . . . .
  2449. */
  2450. //FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
  2451. if(top_type){
  2452. AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
  2453. }
  2454. if(left_type[0]){
  2455. h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
  2456. h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
  2457. h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
  2458. h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
  2459. }
  2460. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  2461. if(!CABAC && h->pps.transform_8x8_mode){
  2462. if(IS_8x8DCT(top_type)){
  2463. h->non_zero_count_cache[4+8*0]=
  2464. h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
  2465. h->non_zero_count_cache[6+8*0]=
  2466. h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
  2467. }
  2468. if(IS_8x8DCT(left_type[0])){
  2469. h->non_zero_count_cache[3+8*1]=
  2470. h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
  2471. }
  2472. if(IS_8x8DCT(left_type[1])){
  2473. h->non_zero_count_cache[3+8*3]=
  2474. h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
  2475. }
  2476. if(IS_8x8DCT(mb_type)){
  2477. h->non_zero_count_cache[scan8[0 ]]= h->non_zero_count_cache[scan8[1 ]]=
  2478. h->non_zero_count_cache[scan8[2 ]]= h->non_zero_count_cache[scan8[3 ]]= h->cbp & 1;
  2479. h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
  2480. h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
  2481. h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
  2482. h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
  2483. h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
  2484. h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
  2485. }
  2486. }
  2487. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  2488. int list;
  2489. for(list=0; list<h->list_count; list++){
  2490. if(USES_LIST(top_type, list)){
  2491. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  2492. const int b8_xy= 4*top_xy + 2;
  2493. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2494. AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
  2495. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  2496. h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
  2497. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  2498. h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
  2499. }else{
  2500. AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
  2501. AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2502. }
  2503. if(!IS_INTERLACED(mb_type^left_type[0])){
  2504. if(USES_LIST(left_type[0], list)){
  2505. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  2506. const int b8_xy= 4*left_xy[0] + 1;
  2507. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2508. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
  2509. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
  2510. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
  2511. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
  2512. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2513. h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
  2514. h->ref_cache[list][scan8[0] - 1 +16 ]=
  2515. h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
  2516. }else{
  2517. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
  2518. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
  2519. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
  2520. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
  2521. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2522. h->ref_cache[list][scan8[0] - 1 + 8 ]=
  2523. h->ref_cache[list][scan8[0] - 1 + 16 ]=
  2524. h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
  2525. }
  2526. }
  2527. }
  2528. }
  2529. return 0;
  2530. }
  2531. static void loop_filter(H264Context *h){
  2532. MpegEncContext * const s = &h->s;
  2533. uint8_t *dest_y, *dest_cb, *dest_cr;
  2534. int linesize, uvlinesize, mb_x, mb_y;
  2535. const int end_mb_y= s->mb_y + FRAME_MBAFF;
  2536. const int old_slice_type= h->slice_type;
  2537. const int end_mb_x = s->mb_x;
  2538. if(h->deblocking_filter) {
  2539. int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
  2540. for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
  2541. for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
  2542. int mb_xy, mb_type;
  2543. mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
  2544. h->slice_num= h->slice_table[mb_xy];
  2545. mb_type= s->current_picture.mb_type[mb_xy];
  2546. h->list_count= h->list_counts[mb_xy];
  2547. if(FRAME_MBAFF)
  2548. h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2549. s->mb_x= mb_x;
  2550. s->mb_y= mb_y;
  2551. dest_y = s->current_picture.data[0] + (mb_x + mb_y * s->linesize ) * 16;
  2552. dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
  2553. dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
  2554. //FIXME simplify above
  2555. if (MB_FIELD) {
  2556. linesize = h->mb_linesize = s->linesize * 2;
  2557. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2558. if(mb_y&1){ //FIXME move out of this function?
  2559. dest_y -= s->linesize*15;
  2560. dest_cb-= s->uvlinesize*7;
  2561. dest_cr-= s->uvlinesize*7;
  2562. }
  2563. } else {
  2564. linesize = h->mb_linesize = s->linesize;
  2565. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2566. }
  2567. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
  2568. if(fill_filter_caches(h, mb_type))
  2569. continue;
  2570. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2571. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2572. if (FRAME_MBAFF) {
  2573. ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2574. } else {
  2575. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2576. }
  2577. }
  2578. }
  2579. }
  2580. h->slice_type= old_slice_type;
  2581. s->mb_x= end_mb_x;
  2582. s->mb_y= end_mb_y - FRAME_MBAFF;
  2583. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2584. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2585. }
  2586. static void predict_field_decoding_flag(H264Context *h){
  2587. MpegEncContext * const s = &h->s;
  2588. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  2589. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  2590. ? s->current_picture.mb_type[mb_xy-1]
  2591. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  2592. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  2593. : 0;
  2594. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2595. }
  2596. /**
  2597. * Draw edges and report progress for the last MB row.
  2598. */
  2599. static void decode_finish_row(H264Context *h){
  2600. MpegEncContext * const s = &h->s;
  2601. int top = 16*(s->mb_y >> FIELD_PICTURE);
  2602. int height = 16 << FRAME_MBAFF;
  2603. int deblock_border = (16 + 4) << FRAME_MBAFF;
  2604. int pic_height = 16*s->mb_height >> FIELD_PICTURE;
  2605. if (h->deblocking_filter) {
  2606. if((top + height) >= pic_height)
  2607. height += deblock_border;
  2608. top -= deblock_border;
  2609. }
  2610. if (top >= pic_height || (top + height) < h->emu_edge_height)
  2611. return;
  2612. height = FFMIN(height, pic_height - top);
  2613. if (top < h->emu_edge_height) {
  2614. height = top+height;
  2615. top = 0;
  2616. }
  2617. ff_draw_horiz_band(s, top, height);
  2618. if (s->dropable) return;
  2619. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
  2620. s->picture_structure==PICT_BOTTOM_FIELD);
  2621. }
  2622. static int decode_slice(struct AVCodecContext *avctx, void *arg){
  2623. H264Context *h = *(void**)arg;
  2624. MpegEncContext * const s = &h->s;
  2625. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  2626. s->mb_skip_run= -1;
  2627. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
  2628. (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
  2629. if( h->pps.cabac ) {
  2630. /* realign */
  2631. align_get_bits( &s->gb );
  2632. /* init cabac */
  2633. ff_init_cabac_states( &h->cabac);
  2634. ff_init_cabac_decoder( &h->cabac,
  2635. s->gb.buffer + get_bits_count(&s->gb)/8,
  2636. (get_bits_left(&s->gb) + 7)/8);
  2637. ff_h264_init_cabac_states(h);
  2638. for(;;){
  2639. //START_TIMER
  2640. int ret = ff_h264_decode_mb_cabac(h);
  2641. int eos;
  2642. //STOP_TIMER("decode_mb_cabac")
  2643. if(ret>=0) ff_h264_hl_decode_mb(h);
  2644. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  2645. s->mb_y++;
  2646. ret = ff_h264_decode_mb_cabac(h);
  2647. if(ret>=0) ff_h264_hl_decode_mb(h);
  2648. s->mb_y--;
  2649. }
  2650. eos = get_cabac_terminate( &h->cabac );
  2651. if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
  2652. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2653. return 0;
  2654. }
  2655. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  2656. 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);
  2657. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2658. return -1;
  2659. }
  2660. if( ++s->mb_x >= s->mb_width ) {
  2661. loop_filter(h);
  2662. s->mb_x = 0;
  2663. decode_finish_row(h);
  2664. ++s->mb_y;
  2665. if(FIELD_OR_MBAFF_PICTURE) {
  2666. ++s->mb_y;
  2667. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2668. predict_field_decoding_flag(h);
  2669. }
  2670. }
  2671. if( eos || s->mb_y >= s->mb_height ) {
  2672. if(s->mb_x)
  2673. loop_filter(h);
  2674. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2675. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2676. return 0;
  2677. }
  2678. }
  2679. } else {
  2680. for(;;){
  2681. int ret = ff_h264_decode_mb_cavlc(h);
  2682. if(ret>=0) ff_h264_hl_decode_mb(h);
  2683. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  2684. s->mb_y++;
  2685. ret = ff_h264_decode_mb_cavlc(h);
  2686. if(ret>=0) ff_h264_hl_decode_mb(h);
  2687. s->mb_y--;
  2688. }
  2689. if(ret<0){
  2690. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2691. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2692. return -1;
  2693. }
  2694. if(++s->mb_x >= s->mb_width){
  2695. loop_filter(h);
  2696. s->mb_x=0;
  2697. decode_finish_row(h);
  2698. ++s->mb_y;
  2699. if(FIELD_OR_MBAFF_PICTURE) {
  2700. ++s->mb_y;
  2701. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2702. predict_field_decoding_flag(h);
  2703. }
  2704. if(s->mb_y >= s->mb_height){
  2705. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2706. if( get_bits_count(&s->gb) == s->gb.size_in_bits
  2707. || get_bits_count(&s->gb) < s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
  2708. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2709. return 0;
  2710. }else{
  2711. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2712. return -1;
  2713. }
  2714. }
  2715. }
  2716. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  2717. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2718. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  2719. if(s->mb_x)
  2720. loop_filter(h);
  2721. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2722. return 0;
  2723. }else{
  2724. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2725. return -1;
  2726. }
  2727. }
  2728. }
  2729. }
  2730. #if 0
  2731. for(;s->mb_y < s->mb_height; s->mb_y++){
  2732. for(;s->mb_x < s->mb_width; s->mb_x++){
  2733. int ret= decode_mb(h);
  2734. ff_h264_hl_decode_mb(h);
  2735. if(ret<0){
  2736. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2737. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2738. return -1;
  2739. }
  2740. if(++s->mb_x >= s->mb_width){
  2741. s->mb_x=0;
  2742. if(++s->mb_y >= s->mb_height){
  2743. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2744. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2745. return 0;
  2746. }else{
  2747. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2748. return -1;
  2749. }
  2750. }
  2751. }
  2752. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  2753. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2754. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2755. return 0;
  2756. }else{
  2757. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2758. return -1;
  2759. }
  2760. }
  2761. }
  2762. s->mb_x=0;
  2763. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2764. }
  2765. #endif
  2766. return -1; //not reached
  2767. }
  2768. /**
  2769. * Call decode_slice() for each context.
  2770. *
  2771. * @param h h264 master context
  2772. * @param context_count number of contexts to execute
  2773. */
  2774. static void execute_decode_slices(H264Context *h, int context_count){
  2775. MpegEncContext * const s = &h->s;
  2776. AVCodecContext * const avctx= s->avctx;
  2777. H264Context *hx;
  2778. int i;
  2779. if (s->avctx->hwaccel)
  2780. return;
  2781. if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2782. return;
  2783. if(context_count == 1) {
  2784. decode_slice(avctx, &h);
  2785. } else {
  2786. for(i = 1; i < context_count; i++) {
  2787. hx = h->thread_context[i];
  2788. hx->s.error_recognition = avctx->error_recognition;
  2789. hx->s.error_count = 0;
  2790. }
  2791. avctx->execute(avctx, (void *)decode_slice,
  2792. h->thread_context, NULL, context_count, sizeof(void*));
  2793. /* pull back stuff from slices to master context */
  2794. hx = h->thread_context[context_count - 1];
  2795. s->mb_x = hx->s.mb_x;
  2796. s->mb_y = hx->s.mb_y;
  2797. s->dropable = hx->s.dropable;
  2798. s->picture_structure = hx->s.picture_structure;
  2799. for(i = 1; i < context_count; i++)
  2800. h->s.error_count += h->thread_context[i]->s.error_count;
  2801. }
  2802. }
  2803. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  2804. MpegEncContext * const s = &h->s;
  2805. AVCodecContext * const avctx= s->avctx;
  2806. int buf_index=0;
  2807. H264Context *hx; ///< thread context
  2808. int context_count = 0;
  2809. int next_avc= h->is_avc ? 0 : buf_size;
  2810. h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
  2811. #if 0
  2812. int i;
  2813. for(i=0; i<50; i++){
  2814. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  2815. }
  2816. #endif
  2817. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  2818. h->current_slice = 0;
  2819. if (!s->first_field)
  2820. s->current_picture_ptr= NULL;
  2821. ff_h264_reset_sei(h);
  2822. }
  2823. for(;;){
  2824. int consumed;
  2825. int dst_length;
  2826. int bit_length;
  2827. const uint8_t *ptr;
  2828. int i, nalsize = 0;
  2829. int err;
  2830. if(buf_index >= next_avc) {
  2831. if(buf_index >= buf_size) break;
  2832. nalsize = 0;
  2833. for(i = 0; i < h->nal_length_size; i++)
  2834. nalsize = (nalsize << 8) | buf[buf_index++];
  2835. if(nalsize <= 0 || nalsize > buf_size - buf_index){
  2836. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  2837. break;
  2838. }
  2839. next_avc= buf_index + nalsize;
  2840. } else {
  2841. // start code prefix search
  2842. for(; buf_index + 3 < next_avc; buf_index++){
  2843. // This should always succeed in the first iteration.
  2844. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  2845. break;
  2846. }
  2847. if(buf_index+3 >= buf_size) break;
  2848. buf_index+=3;
  2849. if(buf_index >= next_avc) continue;
  2850. }
  2851. hx = h->thread_context[context_count];
  2852. ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
  2853. if (ptr==NULL || dst_length < 0){
  2854. return -1;
  2855. }
  2856. i= buf_index + consumed;
  2857. if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
  2858. buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
  2859. s->workaround_bugs |= FF_BUG_TRUNCATED;
  2860. if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
  2861. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  2862. dst_length--;
  2863. }
  2864. bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
  2865. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  2866. av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length);
  2867. }
  2868. if (h->is_avc && (nalsize != consumed) && nalsize){
  2869. av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  2870. }
  2871. buf_index += consumed;
  2872. //FIXME do not discard SEI id
  2873. if(
  2874. #if FF_API_HURRY_UP
  2875. (s->hurry_up == 1 && h->nal_ref_idc == 0) ||
  2876. #endif
  2877. (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2878. continue;
  2879. again:
  2880. err = 0;
  2881. switch(hx->nal_unit_type){
  2882. case NAL_IDR_SLICE:
  2883. if (h->nal_unit_type != NAL_IDR_SLICE) {
  2884. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  2885. return -1;
  2886. }
  2887. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  2888. case NAL_SLICE:
  2889. init_get_bits(&hx->s.gb, ptr, bit_length);
  2890. hx->intra_gb_ptr=
  2891. hx->inter_gb_ptr= &hx->s.gb;
  2892. hx->s.data_partitioning = 0;
  2893. if((err = decode_slice_header(hx, h)))
  2894. break;
  2895. s->current_picture_ptr->key_frame |=
  2896. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  2897. (h->sei_recovery_frame_cnt >= 0);
  2898. if (h->current_slice == 1) {
  2899. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  2900. decode_postinit(h);
  2901. }
  2902. if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  2903. return -1;
  2904. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2905. ff_vdpau_h264_picture_start(s);
  2906. }
  2907. if(hx->redundant_pic_count==0
  2908. #if FF_API_HURRY_UP
  2909. && hx->s.hurry_up < 5
  2910. #endif
  2911. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2912. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2913. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2914. && avctx->skip_frame < AVDISCARD_ALL){
  2915. if(avctx->hwaccel) {
  2916. if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
  2917. return -1;
  2918. }else
  2919. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
  2920. static const uint8_t start_code[] = {0x00, 0x00, 0x01};
  2921. ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
  2922. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
  2923. }else
  2924. context_count++;
  2925. }
  2926. break;
  2927. case NAL_DPA:
  2928. init_get_bits(&hx->s.gb, ptr, bit_length);
  2929. hx->intra_gb_ptr=
  2930. hx->inter_gb_ptr= NULL;
  2931. if ((err = decode_slice_header(hx, h)) < 0)
  2932. break;
  2933. hx->s.data_partitioning = 1;
  2934. break;
  2935. case NAL_DPB:
  2936. init_get_bits(&hx->intra_gb, ptr, bit_length);
  2937. hx->intra_gb_ptr= &hx->intra_gb;
  2938. break;
  2939. case NAL_DPC:
  2940. init_get_bits(&hx->inter_gb, ptr, bit_length);
  2941. hx->inter_gb_ptr= &hx->inter_gb;
  2942. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  2943. && s->context_initialized
  2944. #if FF_API_HURRY_UP
  2945. && s->hurry_up < 5
  2946. #endif
  2947. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2948. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2949. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2950. && avctx->skip_frame < AVDISCARD_ALL)
  2951. context_count++;
  2952. break;
  2953. case NAL_SEI:
  2954. init_get_bits(&s->gb, ptr, bit_length);
  2955. ff_h264_decode_sei(h);
  2956. break;
  2957. case NAL_SPS:
  2958. init_get_bits(&s->gb, ptr, bit_length);
  2959. ff_h264_decode_seq_parameter_set(h);
  2960. if(s->flags& CODEC_FLAG_LOW_DELAY)
  2961. s->low_delay=1;
  2962. if(avctx->has_b_frames < 2)
  2963. avctx->has_b_frames= !s->low_delay;
  2964. break;
  2965. case NAL_PPS:
  2966. init_get_bits(&s->gb, ptr, bit_length);
  2967. ff_h264_decode_picture_parameter_set(h, bit_length);
  2968. break;
  2969. case NAL_AUD:
  2970. case NAL_END_SEQUENCE:
  2971. case NAL_END_STREAM:
  2972. case NAL_FILLER_DATA:
  2973. case NAL_SPS_EXT:
  2974. case NAL_AUXILIARY_SLICE:
  2975. break;
  2976. default:
  2977. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
  2978. }
  2979. if(context_count == h->max_contexts) {
  2980. execute_decode_slices(h, context_count);
  2981. context_count = 0;
  2982. }
  2983. if (err < 0)
  2984. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  2985. else if(err == 1) {
  2986. /* Slice could not be decoded in parallel mode, copy down
  2987. * NAL unit stuff to context 0 and restart. Note that
  2988. * rbsp_buffer is not transferred, but since we no longer
  2989. * run in parallel mode this should not be an issue. */
  2990. h->nal_unit_type = hx->nal_unit_type;
  2991. h->nal_ref_idc = hx->nal_ref_idc;
  2992. hx = h;
  2993. goto again;
  2994. }
  2995. }
  2996. if(context_count)
  2997. execute_decode_slices(h, context_count);
  2998. return buf_index;
  2999. }
  3000. /**
  3001. * returns the number of bytes consumed for building the current frame
  3002. */
  3003. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  3004. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  3005. if(pos+10>buf_size) pos=buf_size; // oops ;)
  3006. return pos;
  3007. }
  3008. static int decode_frame(AVCodecContext *avctx,
  3009. void *data, int *data_size,
  3010. AVPacket *avpkt)
  3011. {
  3012. const uint8_t *buf = avpkt->data;
  3013. int buf_size = avpkt->size;
  3014. H264Context *h = avctx->priv_data;
  3015. MpegEncContext *s = &h->s;
  3016. AVFrame *pict = data;
  3017. int buf_index;
  3018. s->flags= avctx->flags;
  3019. s->flags2= avctx->flags2;
  3020. /* end of stream, output what is still in the buffers */
  3021. out:
  3022. if (buf_size == 0) {
  3023. Picture *out;
  3024. int i, out_idx;
  3025. s->current_picture_ptr = NULL;
  3026. //FIXME factorize this with the output code below
  3027. out = h->delayed_pic[0];
  3028. out_idx = 0;
  3029. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  3030. if(h->delayed_pic[i]->poc < out->poc){
  3031. out = h->delayed_pic[i];
  3032. out_idx = i;
  3033. }
  3034. for(i=out_idx; h->delayed_pic[i]; i++)
  3035. h->delayed_pic[i] = h->delayed_pic[i+1];
  3036. if(out){
  3037. *data_size = sizeof(AVFrame);
  3038. *pict= *(AVFrame*)out;
  3039. }
  3040. return 0;
  3041. }
  3042. buf_index=decode_nal_units(h, buf, buf_size);
  3043. if(buf_index < 0)
  3044. return -1;
  3045. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3046. buf_size = 0;
  3047. goto out;
  3048. }
  3049. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  3050. if (avctx->skip_frame >= AVDISCARD_NONREF
  3051. #if FF_API_HURRY_UP
  3052. || s->hurry_up
  3053. #endif
  3054. )
  3055. return 0;
  3056. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3057. return -1;
  3058. }
  3059. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  3060. if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
  3061. field_end(h, 0);
  3062. if (!h->next_output_pic) {
  3063. /* Wait for second field. */
  3064. *data_size = 0;
  3065. } else {
  3066. *data_size = sizeof(AVFrame);
  3067. *pict = *(AVFrame*)h->next_output_pic;
  3068. }
  3069. }
  3070. assert(pict->data[0] || !*data_size);
  3071. ff_print_debug_info(s, pict);
  3072. //printf("out %d\n", (int)pict->data[0]);
  3073. return get_consumed_bytes(s, buf_index, buf_size);
  3074. }
  3075. #if 0
  3076. static inline void fill_mb_avail(H264Context *h){
  3077. MpegEncContext * const s = &h->s;
  3078. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3079. if(s->mb_y){
  3080. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  3081. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  3082. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  3083. }else{
  3084. h->mb_avail[0]=
  3085. h->mb_avail[1]=
  3086. h->mb_avail[2]= 0;
  3087. }
  3088. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  3089. h->mb_avail[4]= 1; //FIXME move out
  3090. h->mb_avail[5]= 0; //FIXME move out
  3091. }
  3092. #endif
  3093. #ifdef TEST
  3094. #undef printf
  3095. #undef random
  3096. #define COUNT 8000
  3097. #define SIZE (COUNT*40)
  3098. int main(void){
  3099. int i;
  3100. uint8_t temp[SIZE];
  3101. PutBitContext pb;
  3102. GetBitContext gb;
  3103. // int int_temp[10000];
  3104. DSPContext dsp;
  3105. AVCodecContext avctx;
  3106. dsputil_init(&dsp, &avctx);
  3107. init_put_bits(&pb, temp, SIZE);
  3108. printf("testing unsigned exp golomb\n");
  3109. for(i=0; i<COUNT; i++){
  3110. START_TIMER
  3111. set_ue_golomb(&pb, i);
  3112. STOP_TIMER("set_ue_golomb");
  3113. }
  3114. flush_put_bits(&pb);
  3115. init_get_bits(&gb, temp, 8*SIZE);
  3116. for(i=0; i<COUNT; i++){
  3117. int j, s;
  3118. s= show_bits(&gb, 24);
  3119. START_TIMER
  3120. j= get_ue_golomb(&gb);
  3121. if(j != i){
  3122. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3123. // return -1;
  3124. }
  3125. STOP_TIMER("get_ue_golomb");
  3126. }
  3127. init_put_bits(&pb, temp, SIZE);
  3128. printf("testing signed exp golomb\n");
  3129. for(i=0; i<COUNT; i++){
  3130. START_TIMER
  3131. set_se_golomb(&pb, i - COUNT/2);
  3132. STOP_TIMER("set_se_golomb");
  3133. }
  3134. flush_put_bits(&pb);
  3135. init_get_bits(&gb, temp, 8*SIZE);
  3136. for(i=0; i<COUNT; i++){
  3137. int j, s;
  3138. s= show_bits(&gb, 24);
  3139. START_TIMER
  3140. j= get_se_golomb(&gb);
  3141. if(j != i - COUNT/2){
  3142. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3143. // return -1;
  3144. }
  3145. STOP_TIMER("get_se_golomb");
  3146. }
  3147. #if 0
  3148. printf("testing 4x4 (I)DCT\n");
  3149. DCTELEM block[16];
  3150. uint8_t src[16], ref[16];
  3151. uint64_t error= 0, max_error=0;
  3152. for(i=0; i<COUNT; i++){
  3153. int j;
  3154. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  3155. for(j=0; j<16; j++){
  3156. ref[j]= random()%255;
  3157. src[j]= random()%255;
  3158. }
  3159. h264_diff_dct_c(block, src, ref, 4);
  3160. //normalize
  3161. for(j=0; j<16; j++){
  3162. // printf("%d ", block[j]);
  3163. block[j]= block[j]*4;
  3164. if(j&1) block[j]= (block[j]*4 + 2)/5;
  3165. if(j&4) block[j]= (block[j]*4 + 2)/5;
  3166. }
  3167. // printf("\n");
  3168. h->h264dsp.h264_idct_add(ref, block, 4);
  3169. /* for(j=0; j<16; j++){
  3170. printf("%d ", ref[j]);
  3171. }
  3172. printf("\n");*/
  3173. for(j=0; j<16; j++){
  3174. int diff= FFABS(src[j] - ref[j]);
  3175. error+= diff*diff;
  3176. max_error= FFMAX(max_error, diff);
  3177. }
  3178. }
  3179. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  3180. printf("testing quantizer\n");
  3181. for(qp=0; qp<52; qp++){
  3182. for(i=0; i<16; i++)
  3183. src1_block[i]= src2_block[i]= random()%255;
  3184. }
  3185. printf("Testing NAL layer\n");
  3186. uint8_t bitstream[COUNT];
  3187. uint8_t nal[COUNT*2];
  3188. H264Context h;
  3189. memset(&h, 0, sizeof(H264Context));
  3190. for(i=0; i<COUNT; i++){
  3191. int zeros= i;
  3192. int nal_length;
  3193. int consumed;
  3194. int out_length;
  3195. uint8_t *out;
  3196. int j;
  3197. for(j=0; j<COUNT; j++){
  3198. bitstream[j]= (random() % 255) + 1;
  3199. }
  3200. for(j=0; j<zeros; j++){
  3201. int pos= random() % COUNT;
  3202. while(bitstream[pos] == 0){
  3203. pos++;
  3204. pos %= COUNT;
  3205. }
  3206. bitstream[pos]=0;
  3207. }
  3208. START_TIMER
  3209. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  3210. if(nal_length<0){
  3211. printf("encoding failed\n");
  3212. return -1;
  3213. }
  3214. out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
  3215. STOP_TIMER("NAL")
  3216. if(out_length != COUNT){
  3217. printf("incorrect length %d %d\n", out_length, COUNT);
  3218. return -1;
  3219. }
  3220. if(consumed != nal_length){
  3221. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  3222. return -1;
  3223. }
  3224. if(memcmp(bitstream, out, COUNT)){
  3225. printf("mismatch\n");
  3226. return -1;
  3227. }
  3228. }
  3229. #endif
  3230. printf("Testing RBSP\n");
  3231. return 0;
  3232. }
  3233. #endif /* TEST */
  3234. av_cold void ff_h264_free_context(H264Context *h)
  3235. {
  3236. int i;
  3237. free_tables(h, 1); //FIXME cleanup init stuff perhaps
  3238. for(i = 0; i < MAX_SPS_COUNT; i++)
  3239. av_freep(h->sps_buffers + i);
  3240. for(i = 0; i < MAX_PPS_COUNT; i++)
  3241. av_freep(h->pps_buffers + i);
  3242. }
  3243. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  3244. {
  3245. H264Context *h = avctx->priv_data;
  3246. MpegEncContext *s = &h->s;
  3247. ff_h264_free_context(h);
  3248. MPV_common_end(s);
  3249. // memset(h, 0, sizeof(H264Context));
  3250. return 0;
  3251. }
  3252. static const AVProfile profiles[] = {
  3253. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3254. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3255. { FF_PROFILE_H264_MAIN, "Main" },
  3256. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3257. { FF_PROFILE_H264_HIGH, "High" },
  3258. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3259. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3260. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3261. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3262. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3263. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3264. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3265. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3266. { FF_PROFILE_UNKNOWN },
  3267. };
  3268. AVCodec ff_h264_decoder = {
  3269. "h264",
  3270. AVMEDIA_TYPE_VIDEO,
  3271. CODEC_ID_H264,
  3272. sizeof(H264Context),
  3273. ff_h264_decode_init,
  3274. NULL,
  3275. ff_h264_decode_end,
  3276. decode_frame,
  3277. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
  3278. .flush= flush_dpb,
  3279. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3280. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3281. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3282. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3283. };
  3284. #if CONFIG_H264_VDPAU_DECODER
  3285. AVCodec ff_h264_vdpau_decoder = {
  3286. "h264_vdpau",
  3287. AVMEDIA_TYPE_VIDEO,
  3288. CODEC_ID_H264,
  3289. sizeof(H264Context),
  3290. ff_h264_decode_init,
  3291. NULL,
  3292. ff_h264_decode_end,
  3293. decode_frame,
  3294. CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3295. .flush= flush_dpb,
  3296. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3297. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  3298. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3299. };
  3300. #endif