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.

4183 lines
161KB

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