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.

4964 lines
186KB

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