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.

4784 lines
177KB

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