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.

4248 lines
164KB

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