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.

4958 lines
185KB

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