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.

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