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.

3804 lines
140KB

  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) != nalsize) {
  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. return -1; // we cant (re-)initialize context during parallel decoding
  1953. avcodec_set_dimensions(s->avctx, s->width, s->height);
  1954. s->avctx->sample_aspect_ratio= h->sps.sar;
  1955. av_assert0(s->avctx->sample_aspect_ratio.den);
  1956. if(h->sps.video_signal_type_present_flag){
  1957. s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  1958. if(h->sps.colour_description_present_flag){
  1959. s->avctx->color_primaries = h->sps.color_primaries;
  1960. s->avctx->color_trc = h->sps.color_trc;
  1961. s->avctx->colorspace = h->sps.colorspace;
  1962. }
  1963. }
  1964. if(h->sps.timing_info_present_flag){
  1965. int64_t den= h->sps.time_scale;
  1966. if(h->x264_build < 44U)
  1967. den *= 2;
  1968. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  1969. h->sps.num_units_in_tick, den, 1<<30);
  1970. }
  1971. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  1972. s->avctx->codec->pix_fmts ?
  1973. s->avctx->codec->pix_fmts :
  1974. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  1975. hwaccel_pixfmt_list_h264_jpeg_420 :
  1976. ff_hwaccel_pixfmt_list_420);
  1977. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  1978. if (MPV_common_init(s) < 0)
  1979. return -1;
  1980. s->first_field = 0;
  1981. h->prev_interlaced_frame = 1;
  1982. init_scan_tables(h);
  1983. ff_h264_alloc_tables(h);
  1984. if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
  1985. if (context_init(h) < 0)
  1986. return -1;
  1987. } else {
  1988. for(i = 1; i < s->avctx->thread_count; i++) {
  1989. H264Context *c;
  1990. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  1991. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  1992. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  1993. c->h264dsp = h->h264dsp;
  1994. c->sps = h->sps;
  1995. c->pps = h->pps;
  1996. init_scan_tables(c);
  1997. clone_tables(c, h, i);
  1998. }
  1999. for(i = 0; i < s->avctx->thread_count; i++)
  2000. if(context_init(h->thread_context[i]) < 0)
  2001. return -1;
  2002. }
  2003. }
  2004. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  2005. h->mb_mbaff = 0;
  2006. h->mb_aff_frame = 0;
  2007. last_pic_structure = s0->picture_structure;
  2008. if(h->sps.frame_mbs_only_flag){
  2009. s->picture_structure= PICT_FRAME;
  2010. }else{
  2011. if(get_bits1(&s->gb)) { //field_pic_flag
  2012. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  2013. } else {
  2014. s->picture_structure= PICT_FRAME;
  2015. h->mb_aff_frame = h->sps.mb_aff;
  2016. }
  2017. }
  2018. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  2019. if(h0->current_slice == 0){
  2020. if(h->frame_num != h->prev_frame_num &&
  2021. (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
  2022. h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
  2023. while(h->frame_num != h->prev_frame_num &&
  2024. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  2025. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2026. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  2027. if (ff_h264_frame_start(h) < 0)
  2028. return -1;
  2029. h->prev_frame_num++;
  2030. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  2031. s->current_picture_ptr->frame_num= h->prev_frame_num;
  2032. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
  2033. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
  2034. ff_generate_sliding_window_mmcos(h);
  2035. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2036. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2037. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2038. * about there being no actual duplicates.
  2039. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2040. * concealing a lost frame, this probably isn't noticable by comparison, but it should
  2041. * be fixed. */
  2042. if (h->short_ref_count) {
  2043. if (prev) {
  2044. av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
  2045. (const uint8_t**)prev->data, prev->linesize,
  2046. s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
  2047. h->short_ref[0]->poc = prev->poc+2;
  2048. }
  2049. h->short_ref[0]->frame_num = h->prev_frame_num;
  2050. }
  2051. }
  2052. /* See if we have a decoded first field looking for a pair... */
  2053. if (s0->first_field) {
  2054. assert(s0->current_picture_ptr);
  2055. assert(s0->current_picture_ptr->data[0]);
  2056. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  2057. /* figure out if we have a complementary field pair */
  2058. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2059. /*
  2060. * Previous field is unmatched. Don't display it, but let it
  2061. * remain for reference if marked as such.
  2062. */
  2063. s0->current_picture_ptr = NULL;
  2064. s0->first_field = FIELD_PICTURE;
  2065. } else {
  2066. if (h->nal_ref_idc &&
  2067. s0->current_picture_ptr->reference &&
  2068. s0->current_picture_ptr->frame_num != h->frame_num) {
  2069. /*
  2070. * This and previous field were reference, but had
  2071. * different frame_nums. Consider this field first in
  2072. * pair. Throw away previous field except for reference
  2073. * purposes.
  2074. */
  2075. s0->first_field = 1;
  2076. s0->current_picture_ptr = NULL;
  2077. } else {
  2078. /* Second field in complementary pair */
  2079. s0->first_field = 0;
  2080. }
  2081. }
  2082. } else {
  2083. /* Frame or first field in a potentially complementary pair */
  2084. assert(!s0->current_picture_ptr);
  2085. s0->first_field = FIELD_PICTURE;
  2086. }
  2087. if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
  2088. s0->first_field = 0;
  2089. return -1;
  2090. }
  2091. }
  2092. if(h != h0)
  2093. clone_slice(h, h0);
  2094. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  2095. assert(s->mb_num == s->mb_width * s->mb_height);
  2096. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2097. first_mb_in_slice >= s->mb_num){
  2098. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2099. return -1;
  2100. }
  2101. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2102. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2103. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2104. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2105. assert(s->mb_y < s->mb_height);
  2106. if(s->picture_structure==PICT_FRAME){
  2107. h->curr_pic_num= h->frame_num;
  2108. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  2109. }else{
  2110. h->curr_pic_num= 2*h->frame_num + 1;
  2111. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  2112. }
  2113. if(h->nal_unit_type == NAL_IDR_SLICE){
  2114. get_ue_golomb(&s->gb); /* idr_pic_id */
  2115. }
  2116. if(h->sps.poc_type==0){
  2117. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2118. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  2119. h->delta_poc_bottom= get_se_golomb(&s->gb);
  2120. }
  2121. }
  2122. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  2123. h->delta_poc[0]= get_se_golomb(&s->gb);
  2124. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  2125. h->delta_poc[1]= get_se_golomb(&s->gb);
  2126. }
  2127. init_poc(h);
  2128. if(h->pps.redundant_pic_cnt_present){
  2129. h->redundant_pic_count= get_ue_golomb(&s->gb);
  2130. }
  2131. //set defaults, might be overridden a few lines later
  2132. h->ref_count[0]= h->pps.ref_count[0];
  2133. h->ref_count[1]= h->pps.ref_count[1];
  2134. if(h->slice_type_nos != FF_I_TYPE){
  2135. if(h->slice_type_nos == FF_B_TYPE){
  2136. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  2137. }
  2138. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  2139. if(num_ref_idx_active_override_flag){
  2140. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  2141. if(h->slice_type_nos==FF_B_TYPE)
  2142. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  2143. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  2144. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  2145. h->ref_count[0]= h->ref_count[1]= 1;
  2146. return -1;
  2147. }
  2148. }
  2149. if(h->slice_type_nos == FF_B_TYPE)
  2150. h->list_count= 2;
  2151. else
  2152. h->list_count= 1;
  2153. }else
  2154. h->list_count= 0;
  2155. if(!default_ref_list_done){
  2156. ff_h264_fill_default_ref_list(h);
  2157. }
  2158. if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
  2159. return -1;
  2160. //FIXME mt gives valgrind warnings and crashes if this is uncommented
  2161. /*
  2162. if(h->slice_type_nos!=FF_I_TYPE){
  2163. s->last_picture_ptr= &h->ref_list[0][0];
  2164. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2165. }
  2166. if(h->slice_type_nos==FF_B_TYPE){
  2167. s->next_picture_ptr= &h->ref_list[1][0];
  2168. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2169. }
  2170. */
  2171. if( (h->pps.weighted_pred && h->slice_type_nos == FF_P_TYPE )
  2172. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
  2173. pred_weight_table(h);
  2174. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  2175. implicit_weight_table(h, -1);
  2176. }else {
  2177. h->use_weight = 0;
  2178. for (i = 0; i < 2; i++) {
  2179. h->luma_weight_flag[i] = 0;
  2180. h->chroma_weight_flag[i] = 0;
  2181. }
  2182. }
  2183. if(h->nal_ref_idc)
  2184. ff_h264_decode_ref_pic_marking(h0, &s->gb);
  2185. if(FRAME_MBAFF){
  2186. ff_h264_fill_mbaff_ref_list(h);
  2187. if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  2188. implicit_weight_table(h, 0);
  2189. implicit_weight_table(h, 1);
  2190. }
  2191. }
  2192. if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
  2193. ff_h264_direct_dist_scale_factor(h);
  2194. ff_h264_direct_ref_list_init(h);
  2195. if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
  2196. tmp = get_ue_golomb_31(&s->gb);
  2197. if(tmp > 2){
  2198. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2199. return -1;
  2200. }
  2201. h->cabac_init_idc= tmp;
  2202. }
  2203. h->last_qscale_diff = 0;
  2204. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2205. if(tmp>51){
  2206. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2207. return -1;
  2208. }
  2209. s->qscale= tmp;
  2210. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2211. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2212. //FIXME qscale / qp ... stuff
  2213. if(h->slice_type == FF_SP_TYPE){
  2214. get_bits1(&s->gb); /* sp_for_switch_flag */
  2215. }
  2216. if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
  2217. get_se_golomb(&s->gb); /* slice_qs_delta */
  2218. }
  2219. h->deblocking_filter = 1;
  2220. h->slice_alpha_c0_offset = 52;
  2221. h->slice_beta_offset = 52;
  2222. if( h->pps.deblocking_filter_parameters_present ) {
  2223. tmp= get_ue_golomb_31(&s->gb);
  2224. if(tmp > 2){
  2225. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  2226. return -1;
  2227. }
  2228. h->deblocking_filter= tmp;
  2229. if(h->deblocking_filter < 2)
  2230. h->deblocking_filter^= 1; // 1<->0
  2231. if( h->deblocking_filter ) {
  2232. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2233. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2234. if( h->slice_alpha_c0_offset > 104U
  2235. || h->slice_beta_offset > 104U){
  2236. 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);
  2237. return -1;
  2238. }
  2239. }
  2240. }
  2241. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  2242. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
  2243. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == FF_B_TYPE)
  2244. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2245. h->deblocking_filter= 0;
  2246. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2247. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2248. /* Cheat slightly for speed:
  2249. Do not bother to deblock across slices. */
  2250. h->deblocking_filter = 2;
  2251. } else {
  2252. h0->max_contexts = 1;
  2253. if(!h0->single_decode_warning) {
  2254. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2255. h0->single_decode_warning = 1;
  2256. }
  2257. if(h != h0)
  2258. return 1; // deblocking switched inside frame
  2259. }
  2260. }
  2261. 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]);
  2262. #if 0 //FMO
  2263. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  2264. slice_group_change_cycle= get_bits(&s->gb, ?);
  2265. #endif
  2266. h0->last_slice_type = slice_type;
  2267. h->slice_num = ++h0->current_slice;
  2268. if(h->slice_num >= MAX_SLICES){
  2269. av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
  2270. }
  2271. for(j=0; j<2; j++){
  2272. int id_list[16];
  2273. int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
  2274. for(i=0; i<16; i++){
  2275. id_list[i]= 60;
  2276. if(h->ref_list[j][i].data[0]){
  2277. int k;
  2278. uint8_t *base= h->ref_list[j][i].base[0];
  2279. for(k=0; k<h->short_ref_count; k++)
  2280. if(h->short_ref[k]->base[0] == base){
  2281. id_list[i]= k;
  2282. break;
  2283. }
  2284. for(k=0; k<h->long_ref_count; k++)
  2285. if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
  2286. id_list[i]= h->short_ref_count + k;
  2287. break;
  2288. }
  2289. }
  2290. }
  2291. ref2frm[0]=
  2292. ref2frm[1]= -1;
  2293. for(i=0; i<16; i++)
  2294. ref2frm[i+2]= 4*id_list[i]
  2295. +(h->ref_list[j][i].reference&3);
  2296. ref2frm[18+0]=
  2297. ref2frm[18+1]= -1;
  2298. for(i=16; i<48; i++)
  2299. ref2frm[i+4]= 4*id_list[(i-16)>>1]
  2300. +(h->ref_list[j][i].reference&3);
  2301. }
  2302. //FIXME: fix draw_edges+PAFF+frame threads
  2303. 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;
  2304. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2305. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  2306. 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",
  2307. h->slice_num,
  2308. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  2309. first_mb_in_slice,
  2310. av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2311. pps_id, h->frame_num,
  2312. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  2313. h->ref_count[0], h->ref_count[1],
  2314. s->qscale,
  2315. h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
  2316. h->use_weight,
  2317. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  2318. h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  2319. );
  2320. }
  2321. return 0;
  2322. }
  2323. int ff_h264_get_slice_type(const H264Context *h)
  2324. {
  2325. switch (h->slice_type) {
  2326. case FF_P_TYPE: return 0;
  2327. case FF_B_TYPE: return 1;
  2328. case FF_I_TYPE: return 2;
  2329. case FF_SP_TYPE: return 3;
  2330. case FF_SI_TYPE: return 4;
  2331. default: return -1;
  2332. }
  2333. }
  2334. /**
  2335. *
  2336. * @return non zero if the loop filter can be skiped
  2337. */
  2338. static int fill_filter_caches(H264Context *h, int mb_type){
  2339. MpegEncContext * const s = &h->s;
  2340. const int mb_xy= h->mb_xy;
  2341. int top_xy, left_xy[2];
  2342. int top_type, left_type[2];
  2343. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2344. //FIXME deblocking could skip the intra and nnz parts.
  2345. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2346. * stuff, I can't imagine that these complex rules are worth it. */
  2347. left_xy[1] = left_xy[0] = mb_xy-1;
  2348. if(FRAME_MBAFF){
  2349. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
  2350. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2351. if(s->mb_y&1){
  2352. if (left_mb_field_flag != curr_mb_field_flag) {
  2353. left_xy[0] -= s->mb_stride;
  2354. }
  2355. }else{
  2356. if(curr_mb_field_flag){
  2357. top_xy += s->mb_stride & (((s->current_picture.mb_type[top_xy ]>>7)&1)-1);
  2358. }
  2359. if (left_mb_field_flag != curr_mb_field_flag) {
  2360. left_xy[1] += s->mb_stride;
  2361. }
  2362. }
  2363. }
  2364. h->top_mb_xy = top_xy;
  2365. h->left_mb_xy[0] = left_xy[0];
  2366. h->left_mb_xy[1] = left_xy[1];
  2367. {
  2368. //for sufficiently low qp, filtering wouldn't do anything
  2369. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  2370. int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
  2371. int qp = s->current_picture.qscale_table[mb_xy];
  2372. if(qp <= qp_thresh
  2373. && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
  2374. && (top_xy < 0 || ((qp + s->current_picture.qscale_table[top_xy ] + 1)>>1) <= qp_thresh)){
  2375. if(!FRAME_MBAFF)
  2376. return 1;
  2377. if( (left_xy[0]< 0 || ((qp + s->current_picture.qscale_table[left_xy[1] ] + 1)>>1) <= qp_thresh)
  2378. && (top_xy < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy -s->mb_stride] + 1)>>1) <= qp_thresh))
  2379. return 1;
  2380. }
  2381. }
  2382. top_type = s->current_picture.mb_type[top_xy] ;
  2383. left_type[0] = s->current_picture.mb_type[left_xy[0]];
  2384. left_type[1] = s->current_picture.mb_type[left_xy[1]];
  2385. if(h->deblocking_filter == 2){
  2386. if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
  2387. if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
  2388. }else{
  2389. if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
  2390. if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
  2391. }
  2392. h->top_type = top_type ;
  2393. h->left_type[0]= left_type[0];
  2394. h->left_type[1]= left_type[1];
  2395. if(IS_INTRA(mb_type))
  2396. return 0;
  2397. AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
  2398. AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
  2399. AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
  2400. AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
  2401. AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
  2402. h->cbp= h->cbp_table[mb_xy];
  2403. {
  2404. int list;
  2405. for(list=0; list<h->list_count; list++){
  2406. int8_t *ref;
  2407. int y, b_stride;
  2408. int16_t (*mv_dst)[2];
  2409. int16_t (*mv_src)[2];
  2410. if(!USES_LIST(mb_type, list)){
  2411. fill_rectangle( h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
  2412. AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2413. AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2414. AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2415. AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2416. continue;
  2417. }
  2418. ref = &s->current_picture.ref_index[list][4*mb_xy];
  2419. {
  2420. int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2421. AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2422. AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2423. ref += 2;
  2424. AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2425. AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2426. }
  2427. b_stride = h->b_stride;
  2428. mv_dst = &h->mv_cache[list][scan8[0]];
  2429. mv_src = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
  2430. for(y=0; y<4; y++){
  2431. AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
  2432. }
  2433. }
  2434. }
  2435. /*
  2436. 0 . T T. T T T T
  2437. 1 L . .L . . . .
  2438. 2 L . .L . . . .
  2439. 3 . T TL . . . .
  2440. 4 L . .L . . . .
  2441. 5 L . .. . . . .
  2442. */
  2443. //FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
  2444. if(top_type){
  2445. AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
  2446. }
  2447. if(left_type[0]){
  2448. h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
  2449. h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
  2450. h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
  2451. h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
  2452. }
  2453. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  2454. if(!CABAC && h->pps.transform_8x8_mode){
  2455. if(IS_8x8DCT(top_type)){
  2456. h->non_zero_count_cache[4+8*0]=
  2457. h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
  2458. h->non_zero_count_cache[6+8*0]=
  2459. h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
  2460. }
  2461. if(IS_8x8DCT(left_type[0])){
  2462. h->non_zero_count_cache[3+8*1]=
  2463. h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
  2464. }
  2465. if(IS_8x8DCT(left_type[1])){
  2466. h->non_zero_count_cache[3+8*3]=
  2467. h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
  2468. }
  2469. if(IS_8x8DCT(mb_type)){
  2470. h->non_zero_count_cache[scan8[0 ]]= h->non_zero_count_cache[scan8[1 ]]=
  2471. h->non_zero_count_cache[scan8[2 ]]= h->non_zero_count_cache[scan8[3 ]]= h->cbp & 1;
  2472. h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
  2473. h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
  2474. h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
  2475. h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
  2476. h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
  2477. h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
  2478. }
  2479. }
  2480. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  2481. int list;
  2482. for(list=0; list<h->list_count; list++){
  2483. if(USES_LIST(top_type, list)){
  2484. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  2485. const int b8_xy= 4*top_xy + 2;
  2486. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2487. AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
  2488. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  2489. h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
  2490. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  2491. h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
  2492. }else{
  2493. AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
  2494. AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2495. }
  2496. if(!IS_INTERLACED(mb_type^left_type[0])){
  2497. if(USES_LIST(left_type[0], list)){
  2498. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  2499. const int b8_xy= 4*left_xy[0] + 1;
  2500. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2501. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
  2502. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
  2503. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
  2504. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
  2505. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2506. h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
  2507. h->ref_cache[list][scan8[0] - 1 +16 ]=
  2508. h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
  2509. }else{
  2510. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
  2511. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
  2512. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
  2513. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
  2514. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2515. h->ref_cache[list][scan8[0] - 1 + 8 ]=
  2516. h->ref_cache[list][scan8[0] - 1 + 16 ]=
  2517. h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
  2518. }
  2519. }
  2520. }
  2521. }
  2522. return 0;
  2523. }
  2524. static void loop_filter(H264Context *h){
  2525. MpegEncContext * const s = &h->s;
  2526. uint8_t *dest_y, *dest_cb, *dest_cr;
  2527. int linesize, uvlinesize, mb_x, mb_y;
  2528. const int end_mb_y= s->mb_y + FRAME_MBAFF;
  2529. const int old_slice_type= h->slice_type;
  2530. if(h->deblocking_filter) {
  2531. for(mb_x= 0; mb_x<s->mb_width; mb_x++){
  2532. for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
  2533. int mb_xy, mb_type;
  2534. mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
  2535. h->slice_num= h->slice_table[mb_xy];
  2536. mb_type= s->current_picture.mb_type[mb_xy];
  2537. h->list_count= h->list_counts[mb_xy];
  2538. if(FRAME_MBAFF)
  2539. h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2540. s->mb_x= mb_x;
  2541. s->mb_y= mb_y;
  2542. dest_y = s->current_picture.data[0] + (mb_x + mb_y * s->linesize ) * 16;
  2543. dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
  2544. dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
  2545. //FIXME simplify above
  2546. if (MB_FIELD) {
  2547. linesize = h->mb_linesize = s->linesize * 2;
  2548. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2549. if(mb_y&1){ //FIXME move out of this function?
  2550. dest_y -= s->linesize*15;
  2551. dest_cb-= s->uvlinesize*7;
  2552. dest_cr-= s->uvlinesize*7;
  2553. }
  2554. } else {
  2555. linesize = h->mb_linesize = s->linesize;
  2556. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2557. }
  2558. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
  2559. if(fill_filter_caches(h, mb_type))
  2560. continue;
  2561. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2562. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2563. if (FRAME_MBAFF) {
  2564. ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2565. } else {
  2566. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2567. }
  2568. }
  2569. }
  2570. }
  2571. h->slice_type= old_slice_type;
  2572. s->mb_x= 0;
  2573. s->mb_y= end_mb_y - FRAME_MBAFF;
  2574. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2575. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2576. }
  2577. static void predict_field_decoding_flag(H264Context *h){
  2578. MpegEncContext * const s = &h->s;
  2579. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  2580. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  2581. ? s->current_picture.mb_type[mb_xy-1]
  2582. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  2583. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  2584. : 0;
  2585. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2586. }
  2587. /**
  2588. * Draw edges and report progress for the last MB row.
  2589. */
  2590. static void decode_finish_row(H264Context *h){
  2591. MpegEncContext * const s = &h->s;
  2592. int top = 16*(s->mb_y >> FIELD_PICTURE);
  2593. int height = 16 << FRAME_MBAFF;
  2594. int deblock_border = (16 + 4) << FRAME_MBAFF;
  2595. int pic_height = 16*s->mb_height >> FIELD_PICTURE;
  2596. if (h->deblocking_filter) {
  2597. if((top + height) >= pic_height)
  2598. height += deblock_border;
  2599. top -= deblock_border;
  2600. }
  2601. if (top >= pic_height || (top + height) < h->emu_edge_height)
  2602. return;
  2603. height = FFMIN(height, pic_height - top);
  2604. if (top < h->emu_edge_height) {
  2605. height = top+height;
  2606. top = 0;
  2607. }
  2608. ff_draw_horiz_band(s, top, height);
  2609. if (s->dropable) return;
  2610. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
  2611. s->picture_structure==PICT_BOTTOM_FIELD);
  2612. }
  2613. static int decode_slice(struct AVCodecContext *avctx, void *arg){
  2614. H264Context *h = *(void**)arg;
  2615. MpegEncContext * const s = &h->s;
  2616. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  2617. s->mb_skip_run= -1;
  2618. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
  2619. (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
  2620. if( h->pps.cabac ) {
  2621. /* realign */
  2622. align_get_bits( &s->gb );
  2623. /* init cabac */
  2624. ff_init_cabac_states( &h->cabac);
  2625. ff_init_cabac_decoder( &h->cabac,
  2626. s->gb.buffer + get_bits_count(&s->gb)/8,
  2627. (get_bits_left(&s->gb) + 7)/8);
  2628. ff_h264_init_cabac_states(h);
  2629. for(;;){
  2630. //START_TIMER
  2631. int ret = ff_h264_decode_mb_cabac(h);
  2632. int eos;
  2633. //STOP_TIMER("decode_mb_cabac")
  2634. if(ret>=0) ff_h264_hl_decode_mb(h);
  2635. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  2636. s->mb_y++;
  2637. ret = ff_h264_decode_mb_cabac(h);
  2638. if(ret>=0) ff_h264_hl_decode_mb(h);
  2639. s->mb_y--;
  2640. }
  2641. eos = get_cabac_terminate( &h->cabac );
  2642. if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
  2643. 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);
  2644. return 0;
  2645. }
  2646. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  2647. 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);
  2648. 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);
  2649. return -1;
  2650. }
  2651. if( ++s->mb_x >= s->mb_width ) {
  2652. s->mb_x = 0;
  2653. loop_filter(h);
  2654. decode_finish_row(h);
  2655. ++s->mb_y;
  2656. if(FIELD_OR_MBAFF_PICTURE) {
  2657. ++s->mb_y;
  2658. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2659. predict_field_decoding_flag(h);
  2660. }
  2661. }
  2662. if( eos || s->mb_y >= s->mb_height ) {
  2663. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2664. 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);
  2665. return 0;
  2666. }
  2667. }
  2668. } else {
  2669. for(;;){
  2670. int ret = ff_h264_decode_mb_cavlc(h);
  2671. if(ret>=0) ff_h264_hl_decode_mb(h);
  2672. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  2673. s->mb_y++;
  2674. ret = ff_h264_decode_mb_cavlc(h);
  2675. if(ret>=0) ff_h264_hl_decode_mb(h);
  2676. s->mb_y--;
  2677. }
  2678. if(ret<0){
  2679. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2680. 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);
  2681. return -1;
  2682. }
  2683. if(++s->mb_x >= s->mb_width){
  2684. s->mb_x=0;
  2685. loop_filter(h);
  2686. decode_finish_row(h);
  2687. ++s->mb_y;
  2688. if(FIELD_OR_MBAFF_PICTURE) {
  2689. ++s->mb_y;
  2690. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2691. predict_field_decoding_flag(h);
  2692. }
  2693. if(s->mb_y >= s->mb_height){
  2694. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2695. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  2696. 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);
  2697. return 0;
  2698. }else{
  2699. 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);
  2700. return -1;
  2701. }
  2702. }
  2703. }
  2704. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  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. 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);
  2708. return 0;
  2709. }else{
  2710. 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);
  2711. return -1;
  2712. }
  2713. }
  2714. }
  2715. }
  2716. #if 0
  2717. for(;s->mb_y < s->mb_height; s->mb_y++){
  2718. for(;s->mb_x < s->mb_width; s->mb_x++){
  2719. int ret= decode_mb(h);
  2720. ff_h264_hl_decode_mb(h);
  2721. if(ret<0){
  2722. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2723. 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);
  2724. return -1;
  2725. }
  2726. if(++s->mb_x >= s->mb_width){
  2727. s->mb_x=0;
  2728. if(++s->mb_y >= s->mb_height){
  2729. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2730. 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);
  2731. return 0;
  2732. }else{
  2733. 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);
  2734. return -1;
  2735. }
  2736. }
  2737. }
  2738. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  2739. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2740. 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);
  2741. return 0;
  2742. }else{
  2743. 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);
  2744. return -1;
  2745. }
  2746. }
  2747. }
  2748. s->mb_x=0;
  2749. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2750. }
  2751. #endif
  2752. return -1; //not reached
  2753. }
  2754. /**
  2755. * Call decode_slice() for each context.
  2756. *
  2757. * @param h h264 master context
  2758. * @param context_count number of contexts to execute
  2759. */
  2760. static void execute_decode_slices(H264Context *h, int context_count){
  2761. MpegEncContext * const s = &h->s;
  2762. AVCodecContext * const avctx= s->avctx;
  2763. H264Context *hx;
  2764. int i;
  2765. if (s->avctx->hwaccel)
  2766. return;
  2767. if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2768. return;
  2769. if(context_count == 1) {
  2770. decode_slice(avctx, &h);
  2771. } else {
  2772. for(i = 1; i < context_count; i++) {
  2773. hx = h->thread_context[i];
  2774. hx->s.error_recognition = avctx->error_recognition;
  2775. hx->s.error_count = 0;
  2776. }
  2777. avctx->execute(avctx, (void *)decode_slice,
  2778. h->thread_context, NULL, context_count, sizeof(void*));
  2779. /* pull back stuff from slices to master context */
  2780. hx = h->thread_context[context_count - 1];
  2781. s->mb_x = hx->s.mb_x;
  2782. s->mb_y = hx->s.mb_y;
  2783. s->dropable = hx->s.dropable;
  2784. s->picture_structure = hx->s.picture_structure;
  2785. for(i = 1; i < context_count; i++)
  2786. h->s.error_count += h->thread_context[i]->s.error_count;
  2787. }
  2788. }
  2789. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  2790. MpegEncContext * const s = &h->s;
  2791. AVCodecContext * const avctx= s->avctx;
  2792. int buf_index=0;
  2793. H264Context *hx; ///< thread context
  2794. int context_count = 0;
  2795. int next_avc= h->is_avc ? 0 : buf_size;
  2796. h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
  2797. #if 0
  2798. int i;
  2799. for(i=0; i<50; i++){
  2800. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  2801. }
  2802. #endif
  2803. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  2804. h->current_slice = 0;
  2805. if (!s->first_field)
  2806. s->current_picture_ptr= NULL;
  2807. ff_h264_reset_sei(h);
  2808. }
  2809. for(;;){
  2810. int consumed;
  2811. int dst_length;
  2812. int bit_length;
  2813. const uint8_t *ptr;
  2814. int i, nalsize = 0;
  2815. int err;
  2816. if(buf_index >= next_avc) {
  2817. if(buf_index >= buf_size) break;
  2818. nalsize = 0;
  2819. for(i = 0; i < h->nal_length_size; i++)
  2820. nalsize = (nalsize << 8) | buf[buf_index++];
  2821. if(nalsize <= 0 || nalsize > buf_size - buf_index){
  2822. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  2823. break;
  2824. }
  2825. next_avc= buf_index + nalsize;
  2826. } else {
  2827. // start code prefix search
  2828. for(; buf_index + 3 < next_avc; buf_index++){
  2829. // This should always succeed in the first iteration.
  2830. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  2831. break;
  2832. }
  2833. if(buf_index+3 >= buf_size) break;
  2834. buf_index+=3;
  2835. if(buf_index >= next_avc) continue;
  2836. }
  2837. hx = h->thread_context[context_count];
  2838. ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
  2839. if (ptr==NULL || dst_length < 0){
  2840. return -1;
  2841. }
  2842. i= buf_index + consumed;
  2843. if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
  2844. buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
  2845. s->workaround_bugs |= FF_BUG_TRUNCATED;
  2846. if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
  2847. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  2848. dst_length--;
  2849. }
  2850. bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
  2851. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  2852. 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);
  2853. }
  2854. if (h->is_avc && (nalsize != consumed) && nalsize){
  2855. av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  2856. }
  2857. buf_index += consumed;
  2858. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  2859. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2860. continue;
  2861. again:
  2862. err = 0;
  2863. switch(hx->nal_unit_type){
  2864. case NAL_IDR_SLICE:
  2865. if (h->nal_unit_type != NAL_IDR_SLICE) {
  2866. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  2867. return -1;
  2868. }
  2869. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  2870. case NAL_SLICE:
  2871. init_get_bits(&hx->s.gb, ptr, bit_length);
  2872. hx->intra_gb_ptr=
  2873. hx->inter_gb_ptr= &hx->s.gb;
  2874. hx->s.data_partitioning = 0;
  2875. if((err = decode_slice_header(hx, h)))
  2876. break;
  2877. s->current_picture_ptr->key_frame |=
  2878. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  2879. (h->sei_recovery_frame_cnt >= 0);
  2880. if (h->current_slice == 1) {
  2881. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  2882. decode_postinit(h);
  2883. }
  2884. if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  2885. return -1;
  2886. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2887. ff_vdpau_h264_picture_start(s);
  2888. }
  2889. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  2890. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2891. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2892. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2893. && avctx->skip_frame < AVDISCARD_ALL){
  2894. if(avctx->hwaccel) {
  2895. if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
  2896. return -1;
  2897. }else
  2898. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
  2899. static const uint8_t start_code[] = {0x00, 0x00, 0x01};
  2900. ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
  2901. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
  2902. }else
  2903. context_count++;
  2904. }
  2905. break;
  2906. case NAL_DPA:
  2907. init_get_bits(&hx->s.gb, ptr, bit_length);
  2908. hx->intra_gb_ptr=
  2909. hx->inter_gb_ptr= NULL;
  2910. if ((err = decode_slice_header(hx, h)) < 0)
  2911. break;
  2912. hx->s.data_partitioning = 1;
  2913. break;
  2914. case NAL_DPB:
  2915. init_get_bits(&hx->intra_gb, ptr, bit_length);
  2916. hx->intra_gb_ptr= &hx->intra_gb;
  2917. break;
  2918. case NAL_DPC:
  2919. init_get_bits(&hx->inter_gb, ptr, bit_length);
  2920. hx->inter_gb_ptr= &hx->inter_gb;
  2921. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  2922. && s->context_initialized
  2923. && s->hurry_up < 5
  2924. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2925. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2926. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2927. && avctx->skip_frame < AVDISCARD_ALL)
  2928. context_count++;
  2929. break;
  2930. case NAL_SEI:
  2931. init_get_bits(&s->gb, ptr, bit_length);
  2932. ff_h264_decode_sei(h);
  2933. break;
  2934. case NAL_SPS:
  2935. init_get_bits(&s->gb, ptr, bit_length);
  2936. ff_h264_decode_seq_parameter_set(h);
  2937. if(s->flags& CODEC_FLAG_LOW_DELAY)
  2938. s->low_delay=1;
  2939. if(avctx->has_b_frames < 2)
  2940. avctx->has_b_frames= !s->low_delay;
  2941. break;
  2942. case NAL_PPS:
  2943. init_get_bits(&s->gb, ptr, bit_length);
  2944. ff_h264_decode_picture_parameter_set(h, bit_length);
  2945. break;
  2946. case NAL_AUD:
  2947. case NAL_END_SEQUENCE:
  2948. case NAL_END_STREAM:
  2949. case NAL_FILLER_DATA:
  2950. case NAL_SPS_EXT:
  2951. case NAL_AUXILIARY_SLICE:
  2952. break;
  2953. default:
  2954. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
  2955. }
  2956. if(context_count == h->max_contexts) {
  2957. execute_decode_slices(h, context_count);
  2958. context_count = 0;
  2959. }
  2960. if (err < 0)
  2961. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  2962. else if(err == 1) {
  2963. /* Slice could not be decoded in parallel mode, copy down
  2964. * NAL unit stuff to context 0 and restart. Note that
  2965. * rbsp_buffer is not transferred, but since we no longer
  2966. * run in parallel mode this should not be an issue. */
  2967. h->nal_unit_type = hx->nal_unit_type;
  2968. h->nal_ref_idc = hx->nal_ref_idc;
  2969. hx = h;
  2970. goto again;
  2971. }
  2972. }
  2973. if(context_count)
  2974. execute_decode_slices(h, context_count);
  2975. return buf_index;
  2976. }
  2977. /**
  2978. * returns the number of bytes consumed for building the current frame
  2979. */
  2980. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  2981. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  2982. if(pos+10>buf_size) pos=buf_size; // oops ;)
  2983. return pos;
  2984. }
  2985. static int decode_frame(AVCodecContext *avctx,
  2986. void *data, int *data_size,
  2987. AVPacket *avpkt)
  2988. {
  2989. const uint8_t *buf = avpkt->data;
  2990. int buf_size = avpkt->size;
  2991. H264Context *h = avctx->priv_data;
  2992. MpegEncContext *s = &h->s;
  2993. AVFrame *pict = data;
  2994. int buf_index;
  2995. s->flags= avctx->flags;
  2996. s->flags2= avctx->flags2;
  2997. /* end of stream, output what is still in the buffers */
  2998. out:
  2999. if (buf_size == 0) {
  3000. Picture *out;
  3001. int i, out_idx;
  3002. s->current_picture_ptr = NULL;
  3003. //FIXME factorize this with the output code below
  3004. out = h->delayed_pic[0];
  3005. out_idx = 0;
  3006. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  3007. if(h->delayed_pic[i]->poc < out->poc){
  3008. out = h->delayed_pic[i];
  3009. out_idx = i;
  3010. }
  3011. for(i=out_idx; h->delayed_pic[i]; i++)
  3012. h->delayed_pic[i] = h->delayed_pic[i+1];
  3013. if(out){
  3014. *data_size = sizeof(AVFrame);
  3015. *pict= *(AVFrame*)out;
  3016. }
  3017. return 0;
  3018. }
  3019. buf_index=decode_nal_units(h, buf, buf_size);
  3020. if(buf_index < 0)
  3021. return -1;
  3022. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3023. buf_size = 0;
  3024. goto out;
  3025. }
  3026. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  3027. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  3028. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3029. return -1;
  3030. }
  3031. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  3032. if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
  3033. field_end(h, 0);
  3034. if (!h->next_output_pic) {
  3035. /* Wait for second field. */
  3036. *data_size = 0;
  3037. } else {
  3038. *data_size = sizeof(AVFrame);
  3039. *pict = *(AVFrame*)h->next_output_pic;
  3040. }
  3041. }
  3042. assert(pict->data[0] || !*data_size);
  3043. ff_print_debug_info(s, pict);
  3044. //printf("out %d\n", (int)pict->data[0]);
  3045. return get_consumed_bytes(s, buf_index, buf_size);
  3046. }
  3047. #if 0
  3048. static inline void fill_mb_avail(H264Context *h){
  3049. MpegEncContext * const s = &h->s;
  3050. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3051. if(s->mb_y){
  3052. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  3053. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  3054. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  3055. }else{
  3056. h->mb_avail[0]=
  3057. h->mb_avail[1]=
  3058. h->mb_avail[2]= 0;
  3059. }
  3060. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  3061. h->mb_avail[4]= 1; //FIXME move out
  3062. h->mb_avail[5]= 0; //FIXME move out
  3063. }
  3064. #endif
  3065. #ifdef TEST
  3066. #undef printf
  3067. #undef random
  3068. #define COUNT 8000
  3069. #define SIZE (COUNT*40)
  3070. int main(void){
  3071. int i;
  3072. uint8_t temp[SIZE];
  3073. PutBitContext pb;
  3074. GetBitContext gb;
  3075. // int int_temp[10000];
  3076. DSPContext dsp;
  3077. AVCodecContext avctx;
  3078. dsputil_init(&dsp, &avctx);
  3079. init_put_bits(&pb, temp, SIZE);
  3080. printf("testing unsigned exp golomb\n");
  3081. for(i=0; i<COUNT; i++){
  3082. START_TIMER
  3083. set_ue_golomb(&pb, i);
  3084. STOP_TIMER("set_ue_golomb");
  3085. }
  3086. flush_put_bits(&pb);
  3087. init_get_bits(&gb, temp, 8*SIZE);
  3088. for(i=0; i<COUNT; i++){
  3089. int j, s;
  3090. s= show_bits(&gb, 24);
  3091. START_TIMER
  3092. j= get_ue_golomb(&gb);
  3093. if(j != i){
  3094. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3095. // return -1;
  3096. }
  3097. STOP_TIMER("get_ue_golomb");
  3098. }
  3099. init_put_bits(&pb, temp, SIZE);
  3100. printf("testing signed exp golomb\n");
  3101. for(i=0; i<COUNT; i++){
  3102. START_TIMER
  3103. set_se_golomb(&pb, i - COUNT/2);
  3104. STOP_TIMER("set_se_golomb");
  3105. }
  3106. flush_put_bits(&pb);
  3107. init_get_bits(&gb, temp, 8*SIZE);
  3108. for(i=0; i<COUNT; i++){
  3109. int j, s;
  3110. s= show_bits(&gb, 24);
  3111. START_TIMER
  3112. j= get_se_golomb(&gb);
  3113. if(j != i - COUNT/2){
  3114. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3115. // return -1;
  3116. }
  3117. STOP_TIMER("get_se_golomb");
  3118. }
  3119. #if 0
  3120. printf("testing 4x4 (I)DCT\n");
  3121. DCTELEM block[16];
  3122. uint8_t src[16], ref[16];
  3123. uint64_t error= 0, max_error=0;
  3124. for(i=0; i<COUNT; i++){
  3125. int j;
  3126. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  3127. for(j=0; j<16; j++){
  3128. ref[j]= random()%255;
  3129. src[j]= random()%255;
  3130. }
  3131. h264_diff_dct_c(block, src, ref, 4);
  3132. //normalize
  3133. for(j=0; j<16; j++){
  3134. // printf("%d ", block[j]);
  3135. block[j]= block[j]*4;
  3136. if(j&1) block[j]= (block[j]*4 + 2)/5;
  3137. if(j&4) block[j]= (block[j]*4 + 2)/5;
  3138. }
  3139. // printf("\n");
  3140. h->h264dsp.h264_idct_add(ref, block, 4);
  3141. /* for(j=0; j<16; j++){
  3142. printf("%d ", ref[j]);
  3143. }
  3144. printf("\n");*/
  3145. for(j=0; j<16; j++){
  3146. int diff= FFABS(src[j] - ref[j]);
  3147. error+= diff*diff;
  3148. max_error= FFMAX(max_error, diff);
  3149. }
  3150. }
  3151. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  3152. printf("testing quantizer\n");
  3153. for(qp=0; qp<52; qp++){
  3154. for(i=0; i<16; i++)
  3155. src1_block[i]= src2_block[i]= random()%255;
  3156. }
  3157. printf("Testing NAL layer\n");
  3158. uint8_t bitstream[COUNT];
  3159. uint8_t nal[COUNT*2];
  3160. H264Context h;
  3161. memset(&h, 0, sizeof(H264Context));
  3162. for(i=0; i<COUNT; i++){
  3163. int zeros= i;
  3164. int nal_length;
  3165. int consumed;
  3166. int out_length;
  3167. uint8_t *out;
  3168. int j;
  3169. for(j=0; j<COUNT; j++){
  3170. bitstream[j]= (random() % 255) + 1;
  3171. }
  3172. for(j=0; j<zeros; j++){
  3173. int pos= random() % COUNT;
  3174. while(bitstream[pos] == 0){
  3175. pos++;
  3176. pos %= COUNT;
  3177. }
  3178. bitstream[pos]=0;
  3179. }
  3180. START_TIMER
  3181. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  3182. if(nal_length<0){
  3183. printf("encoding failed\n");
  3184. return -1;
  3185. }
  3186. out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
  3187. STOP_TIMER("NAL")
  3188. if(out_length != COUNT){
  3189. printf("incorrect length %d %d\n", out_length, COUNT);
  3190. return -1;
  3191. }
  3192. if(consumed != nal_length){
  3193. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  3194. return -1;
  3195. }
  3196. if(memcmp(bitstream, out, COUNT)){
  3197. printf("mismatch\n");
  3198. return -1;
  3199. }
  3200. }
  3201. #endif
  3202. printf("Testing RBSP\n");
  3203. return 0;
  3204. }
  3205. #endif /* TEST */
  3206. av_cold void ff_h264_free_context(H264Context *h)
  3207. {
  3208. int i;
  3209. free_tables(h, 1); //FIXME cleanup init stuff perhaps
  3210. for(i = 0; i < MAX_SPS_COUNT; i++)
  3211. av_freep(h->sps_buffers + i);
  3212. for(i = 0; i < MAX_PPS_COUNT; i++)
  3213. av_freep(h->pps_buffers + i);
  3214. }
  3215. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  3216. {
  3217. H264Context *h = avctx->priv_data;
  3218. MpegEncContext *s = &h->s;
  3219. ff_h264_free_context(h);
  3220. MPV_common_end(s);
  3221. // memset(h, 0, sizeof(H264Context));
  3222. return 0;
  3223. }
  3224. static const AVProfile profiles[] = {
  3225. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3226. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3227. { FF_PROFILE_H264_MAIN, "Main" },
  3228. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3229. { FF_PROFILE_H264_HIGH, "High" },
  3230. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3231. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3232. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3233. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3234. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3235. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3236. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3237. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3238. { FF_PROFILE_UNKNOWN },
  3239. };
  3240. AVCodec ff_h264_decoder = {
  3241. "h264",
  3242. AVMEDIA_TYPE_VIDEO,
  3243. CODEC_ID_H264,
  3244. sizeof(H264Context),
  3245. ff_h264_decode_init,
  3246. NULL,
  3247. ff_h264_decode_end,
  3248. decode_frame,
  3249. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
  3250. .flush= flush_dpb,
  3251. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3252. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3253. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3254. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3255. };
  3256. #if CONFIG_H264_VDPAU_DECODER
  3257. AVCodec ff_h264_vdpau_decoder = {
  3258. "h264_vdpau",
  3259. AVMEDIA_TYPE_VIDEO,
  3260. CODEC_ID_H264,
  3261. sizeof(H264Context),
  3262. ff_h264_decode_init,
  3263. NULL,
  3264. ff_h264_decode_end,
  3265. decode_frame,
  3266. CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3267. .flush= flush_dpb,
  3268. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3269. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  3270. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3271. };
  3272. #endif