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.

4773 lines
177KB

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