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.

4807 lines
178KB

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