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.

3893 lines
145KB

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