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.

1537 lines
50KB

  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/display.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/stereo3d.h"
  31. #include "libavutil/timer.h"
  32. #include "internal.h"
  33. #include "bytestream.h"
  34. #include "cabac.h"
  35. #include "cabac_functions.h"
  36. #include "error_resilience.h"
  37. #include "avcodec.h"
  38. #include "h264.h"
  39. #include "h2645_parse.h"
  40. #include "h264data.h"
  41. #include "h264chroma.h"
  42. #include "h264_mvpred.h"
  43. #include "golomb.h"
  44. #include "mathops.h"
  45. #include "me_cmp.h"
  46. #include "mpegutils.h"
  47. #include "profiles.h"
  48. #include "rectangle.h"
  49. #include "thread.h"
  50. #include <assert.h>
  51. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  52. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  53. int (*mv)[2][4][2],
  54. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  55. {
  56. H264Context *h = opaque;
  57. H264SliceContext *sl = &h->slice_ctx[0];
  58. sl->mb_x = mb_x;
  59. sl->mb_y = mb_y;
  60. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  61. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  62. assert(ref >= 0);
  63. /* FIXME: It is possible albeit uncommon that slice references
  64. * differ between slices. We take the easy approach and ignore
  65. * it for now. If this turns out to have any relevance in
  66. * practice then correct remapping should be added. */
  67. if (ref >= sl->ref_count[0])
  68. ref = 0;
  69. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  70. 2, 2, 2, ref, 1);
  71. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  72. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  73. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  74. assert(!FRAME_MBAFF(h));
  75. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  76. }
  77. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  78. int y, int height)
  79. {
  80. AVCodecContext *avctx = h->avctx;
  81. const AVFrame *src = h->cur_pic.f;
  82. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  83. int vshift = desc->log2_chroma_h;
  84. const int field_pic = h->picture_structure != PICT_FRAME;
  85. if (field_pic) {
  86. height <<= 1;
  87. y <<= 1;
  88. }
  89. height = FFMIN(height, avctx->height - y);
  90. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  91. return;
  92. if (avctx->draw_horiz_band) {
  93. int offset[AV_NUM_DATA_POINTERS];
  94. int i;
  95. offset[0] = y * src->linesize[0];
  96. offset[1] =
  97. offset[2] = (y >> vshift) * src->linesize[1];
  98. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  99. offset[i] = 0;
  100. emms_c();
  101. avctx->draw_horiz_band(avctx, src, offset,
  102. y, h->picture_structure, height);
  103. }
  104. }
  105. const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
  106. const uint8_t *src,
  107. int *dst_length, int *consumed, int length)
  108. {
  109. int i, si, di;
  110. uint8_t *dst;
  111. // src[0]&0x80; // forbidden bit
  112. h->nal_ref_idc = src[0] >> 5;
  113. h->nal_unit_type = src[0] & 0x1F;
  114. src++;
  115. length--;
  116. #define STARTCODE_TEST \
  117. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  118. if (src[i + 2] != 3) { \
  119. /* startcode, so we must be past the end */ \
  120. length = i; \
  121. } \
  122. break; \
  123. }
  124. #if HAVE_FAST_UNALIGNED
  125. #define FIND_FIRST_ZERO \
  126. if (i > 0 && !src[i]) \
  127. i--; \
  128. while (src[i]) \
  129. i++
  130. #if HAVE_FAST_64BIT
  131. for (i = 0; i + 1 < length; i += 9) {
  132. if (!((~AV_RN64A(src + i) &
  133. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  134. 0x8000800080008080ULL))
  135. continue;
  136. FIND_FIRST_ZERO;
  137. STARTCODE_TEST;
  138. i -= 7;
  139. }
  140. #else
  141. for (i = 0; i + 1 < length; i += 5) {
  142. if (!((~AV_RN32A(src + i) &
  143. (AV_RN32A(src + i) - 0x01000101U)) &
  144. 0x80008080U))
  145. continue;
  146. FIND_FIRST_ZERO;
  147. STARTCODE_TEST;
  148. i -= 3;
  149. }
  150. #endif
  151. #else
  152. for (i = 0; i + 1 < length; i += 2) {
  153. if (src[i])
  154. continue;
  155. if (i > 0 && src[i - 1] == 0)
  156. i--;
  157. STARTCODE_TEST;
  158. }
  159. #endif
  160. if (i >= length - 1) { // no escaped 0
  161. *dst_length = length;
  162. *consumed = length + 1; // +1 for the header
  163. return src;
  164. }
  165. av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
  166. length + AV_INPUT_BUFFER_PADDING_SIZE);
  167. dst = sl->rbsp_buffer;
  168. if (!dst)
  169. return NULL;
  170. memcpy(dst, src, i);
  171. si = di = i;
  172. while (si + 2 < length) {
  173. // remove escapes (very rare 1:2^22)
  174. if (src[si + 2] > 3) {
  175. dst[di++] = src[si++];
  176. dst[di++] = src[si++];
  177. } else if (src[si] == 0 && src[si + 1] == 0) {
  178. if (src[si + 2] == 3) { // escape
  179. dst[di++] = 0;
  180. dst[di++] = 0;
  181. si += 3;
  182. continue;
  183. } else // next start code
  184. goto nsc;
  185. }
  186. dst[di++] = src[si++];
  187. }
  188. while (si < length)
  189. dst[di++] = src[si++];
  190. nsc:
  191. memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  192. *dst_length = di;
  193. *consumed = si + 1; // +1 for the header
  194. /* FIXME store exact number of bits in the getbitcontext
  195. * (it is needed for decoding) */
  196. return dst;
  197. }
  198. void ff_h264_free_tables(H264Context *h)
  199. {
  200. int i;
  201. av_freep(&h->intra4x4_pred_mode);
  202. av_freep(&h->chroma_pred_mode_table);
  203. av_freep(&h->cbp_table);
  204. av_freep(&h->mvd_table[0]);
  205. av_freep(&h->mvd_table[1]);
  206. av_freep(&h->direct_table);
  207. av_freep(&h->non_zero_count);
  208. av_freep(&h->slice_table_base);
  209. h->slice_table = NULL;
  210. av_freep(&h->list_counts);
  211. av_freep(&h->mb2b_xy);
  212. av_freep(&h->mb2br_xy);
  213. av_buffer_pool_uninit(&h->qscale_table_pool);
  214. av_buffer_pool_uninit(&h->mb_type_pool);
  215. av_buffer_pool_uninit(&h->motion_val_pool);
  216. av_buffer_pool_uninit(&h->ref_index_pool);
  217. for (i = 0; i < h->nb_slice_ctx; i++) {
  218. H264SliceContext *sl = &h->slice_ctx[i];
  219. av_freep(&sl->dc_val_base);
  220. av_freep(&sl->er.mb_index2xy);
  221. av_freep(&sl->er.error_status_table);
  222. av_freep(&sl->er.er_temp_buffer);
  223. av_freep(&sl->bipred_scratchpad);
  224. av_freep(&sl->edge_emu_buffer);
  225. av_freep(&sl->top_borders[0]);
  226. av_freep(&sl->top_borders[1]);
  227. sl->bipred_scratchpad_allocated = 0;
  228. sl->edge_emu_buffer_allocated = 0;
  229. sl->top_borders_allocated[0] = 0;
  230. sl->top_borders_allocated[1] = 0;
  231. }
  232. }
  233. int ff_h264_alloc_tables(H264Context *h)
  234. {
  235. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  236. const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
  237. int x, y;
  238. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  239. row_mb_num * 8 * sizeof(uint8_t), fail)
  240. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  241. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  242. big_mb_num * 48 * sizeof(uint8_t), fail)
  243. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  244. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  245. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  246. big_mb_num * sizeof(uint16_t), fail)
  247. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  248. big_mb_num * sizeof(uint8_t), fail)
  249. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  250. 16 * row_mb_num * sizeof(uint8_t), fail);
  251. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  252. 16 * row_mb_num * sizeof(uint8_t), fail);
  253. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  254. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  255. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  256. 4 * big_mb_num * sizeof(uint8_t), fail);
  257. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  258. big_mb_num * sizeof(uint8_t), fail)
  259. memset(h->slice_table_base, -1,
  260. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  261. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  262. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  263. big_mb_num * sizeof(uint32_t), fail);
  264. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  265. big_mb_num * sizeof(uint32_t), fail);
  266. for (y = 0; y < h->mb_height; y++)
  267. for (x = 0; x < h->mb_width; x++) {
  268. const int mb_xy = x + y * h->mb_stride;
  269. const int b_xy = 4 * x + 4 * y * h->b_stride;
  270. h->mb2b_xy[mb_xy] = b_xy;
  271. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  272. }
  273. if (!h->dequant4_coeff[0])
  274. ff_h264_init_dequant_tables(h);
  275. return 0;
  276. fail:
  277. ff_h264_free_tables(h);
  278. return AVERROR(ENOMEM);
  279. }
  280. /**
  281. * Init context
  282. * Allocate buffers which are not shared amongst multiple threads.
  283. */
  284. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  285. {
  286. ERContext *er = &sl->er;
  287. int mb_array_size = h->mb_height * h->mb_stride;
  288. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  289. int c_size = h->mb_stride * (h->mb_height + 1);
  290. int yc_size = y_size + 2 * c_size;
  291. int x, y, i;
  292. sl->ref_cache[0][scan8[5] + 1] =
  293. sl->ref_cache[0][scan8[7] + 1] =
  294. sl->ref_cache[0][scan8[13] + 1] =
  295. sl->ref_cache[1][scan8[5] + 1] =
  296. sl->ref_cache[1][scan8[7] + 1] =
  297. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  298. if (CONFIG_ERROR_RESILIENCE) {
  299. /* init ER */
  300. er->avctx = h->avctx;
  301. er->decode_mb = h264_er_decode_mb;
  302. er->opaque = h;
  303. er->quarter_sample = 1;
  304. er->mb_num = h->mb_num;
  305. er->mb_width = h->mb_width;
  306. er->mb_height = h->mb_height;
  307. er->mb_stride = h->mb_stride;
  308. er->b8_stride = h->mb_width * 2 + 1;
  309. // error resilience code looks cleaner with this
  310. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  311. (h->mb_num + 1) * sizeof(int), fail);
  312. for (y = 0; y < h->mb_height; y++)
  313. for (x = 0; x < h->mb_width; x++)
  314. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  315. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  316. h->mb_stride + h->mb_width;
  317. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  318. mb_array_size * sizeof(uint8_t), fail);
  319. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  320. h->mb_height * h->mb_stride, fail);
  321. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  322. yc_size * sizeof(int16_t), fail);
  323. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  324. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  325. er->dc_val[2] = er->dc_val[1] + c_size;
  326. for (i = 0; i < yc_size; i++)
  327. sl->dc_val_base[i] = 1024;
  328. }
  329. return 0;
  330. fail:
  331. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  332. }
  333. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  334. int parse_extradata);
  335. /* There are (invalid) samples in the wild with mp4-style extradata, where the
  336. * parameter sets are stored unescaped (i.e. as RBSP).
  337. * This function catches the parameter set decoding failure and tries again
  338. * after escaping it */
  339. static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
  340. {
  341. int ret;
  342. ret = decode_nal_units(h, buf, buf_size, 1);
  343. if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
  344. GetByteContext gbc;
  345. PutByteContext pbc;
  346. uint8_t *escaped_buf;
  347. int escaped_buf_size;
  348. av_log(h->avctx, AV_LOG_WARNING,
  349. "SPS decoding failure, trying again after escaping the NAL\n");
  350. if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
  351. return AVERROR(ERANGE);
  352. escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
  353. escaped_buf = av_mallocz(escaped_buf_size);
  354. if (!escaped_buf)
  355. return AVERROR(ENOMEM);
  356. bytestream2_init(&gbc, buf, buf_size);
  357. bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
  358. while (bytestream2_get_bytes_left(&gbc)) {
  359. if (bytestream2_get_bytes_left(&gbc) >= 3 &&
  360. bytestream2_peek_be24(&gbc) <= 3) {
  361. bytestream2_put_be24(&pbc, 3);
  362. bytestream2_skip(&gbc, 2);
  363. } else
  364. bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
  365. }
  366. escaped_buf_size = bytestream2_tell_p(&pbc);
  367. AV_WB16(escaped_buf, escaped_buf_size - 2);
  368. ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
  369. av_freep(&escaped_buf);
  370. if (ret < 0)
  371. return ret;
  372. }
  373. return 0;
  374. }
  375. int ff_h264_decode_extradata(H264Context *h)
  376. {
  377. AVCodecContext *avctx = h->avctx;
  378. int ret;
  379. if (avctx->extradata[0] == 1) {
  380. int i, cnt, nalsize;
  381. unsigned char *p = avctx->extradata;
  382. h->is_avc = 1;
  383. if (avctx->extradata_size < 7) {
  384. av_log(avctx, AV_LOG_ERROR,
  385. "avcC %d too short\n", avctx->extradata_size);
  386. return AVERROR_INVALIDDATA;
  387. }
  388. /* sps and pps in the avcC always have length coded with 2 bytes,
  389. * so put a fake nal_length_size = 2 while parsing them */
  390. h->nal_length_size = 2;
  391. // Decode sps from avcC
  392. cnt = *(p + 5) & 0x1f; // Number of sps
  393. p += 6;
  394. for (i = 0; i < cnt; i++) {
  395. nalsize = AV_RB16(p) + 2;
  396. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  397. return AVERROR_INVALIDDATA;
  398. ret = decode_extradata_ps_mp4(h, p, nalsize);
  399. if (ret < 0) {
  400. av_log(avctx, AV_LOG_ERROR,
  401. "Decoding sps %d from avcC failed\n", i);
  402. return ret;
  403. }
  404. p += nalsize;
  405. }
  406. // Decode pps from avcC
  407. cnt = *(p++); // Number of pps
  408. for (i = 0; i < cnt; i++) {
  409. nalsize = AV_RB16(p) + 2;
  410. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  411. return AVERROR_INVALIDDATA;
  412. ret = decode_extradata_ps_mp4(h, p, nalsize);
  413. if (ret < 0) {
  414. av_log(avctx, AV_LOG_ERROR,
  415. "Decoding pps %d from avcC failed\n", i);
  416. return ret;
  417. }
  418. p += nalsize;
  419. }
  420. // Store right nal length size that will be used to parse all other nals
  421. h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
  422. } else {
  423. h->is_avc = 0;
  424. ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
  425. if (ret < 0)
  426. return ret;
  427. }
  428. return 0;
  429. }
  430. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  431. {
  432. int i;
  433. h->avctx = avctx;
  434. h->dequant_coeff_pps = -1;
  435. h->picture_structure = PICT_FRAME;
  436. h->slice_context_count = 1;
  437. h->workaround_bugs = avctx->workaround_bugs;
  438. h->flags = avctx->flags;
  439. h->prev_poc_msb = 1 << 16;
  440. h->x264_build = -1;
  441. h->recovery_frame = -1;
  442. h->frame_recovered = 0;
  443. h->next_outputed_poc = INT_MIN;
  444. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  445. h->last_pocs[i] = INT_MIN;
  446. ff_h264_reset_sei(h);
  447. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  448. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  449. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  450. if (!h->slice_ctx) {
  451. h->nb_slice_ctx = 0;
  452. return AVERROR(ENOMEM);
  453. }
  454. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  455. h->DPB[i].f = av_frame_alloc();
  456. if (!h->DPB[i].f)
  457. return AVERROR(ENOMEM);
  458. }
  459. h->cur_pic.f = av_frame_alloc();
  460. if (!h->cur_pic.f)
  461. return AVERROR(ENOMEM);
  462. for (i = 0; i < h->nb_slice_ctx; i++)
  463. h->slice_ctx[i].h264 = h;
  464. return 0;
  465. }
  466. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  467. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  468. {
  469. H264Context *h = avctx->priv_data;
  470. int ret;
  471. ret = h264_init_context(avctx, h);
  472. if (ret < 0)
  473. return ret;
  474. /* set defaults */
  475. if (!avctx->has_b_frames)
  476. h->low_delay = 1;
  477. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  478. if (ret != 0) {
  479. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  480. return AVERROR_UNKNOWN;
  481. }
  482. if (avctx->codec_id == AV_CODEC_ID_H264) {
  483. if (avctx->ticks_per_frame == 1)
  484. h->avctx->framerate.num *= 2;
  485. avctx->ticks_per_frame = 2;
  486. }
  487. if (avctx->extradata_size > 0 && avctx->extradata) {
  488. ret = ff_h264_decode_extradata(h);
  489. if (ret < 0) {
  490. ff_h264_free_context(h);
  491. return ret;
  492. }
  493. }
  494. if (h->sps.bitstream_restriction_flag &&
  495. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  496. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  497. h->low_delay = 0;
  498. }
  499. avctx->internal->allocate_progress = 1;
  500. if (h->enable_er) {
  501. av_log(avctx, AV_LOG_WARNING,
  502. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  503. "Use it at your own risk\n");
  504. }
  505. return 0;
  506. }
  507. static int decode_init_thread_copy(AVCodecContext *avctx)
  508. {
  509. H264Context *h = avctx->priv_data;
  510. int ret;
  511. if (!avctx->internal->is_copy)
  512. return 0;
  513. memset(h, 0, sizeof(*h));
  514. ret = h264_init_context(avctx, h);
  515. if (ret < 0)
  516. return ret;
  517. h->context_initialized = 0;
  518. return 0;
  519. }
  520. /**
  521. * Run setup operations that must be run after slice header decoding.
  522. * This includes finding the next displayed frame.
  523. *
  524. * @param h h264 master context
  525. * @param setup_finished enough NALs have been read that we can call
  526. * ff_thread_finish_setup()
  527. */
  528. static void decode_postinit(H264Context *h, int setup_finished)
  529. {
  530. H264Picture *out = h->cur_pic_ptr;
  531. H264Picture *cur = h->cur_pic_ptr;
  532. int i, pics, out_of_order, out_idx;
  533. int invalid = 0, cnt = 0;
  534. h->cur_pic_ptr->f->pict_type = h->pict_type;
  535. if (h->next_output_pic)
  536. return;
  537. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  538. /* FIXME: if we have two PAFF fields in one packet, we can't start
  539. * the next thread here. If we have one field per packet, we can.
  540. * The check in decode_nal_units() is not good enough to find this
  541. * yet, so we assume the worst for now. */
  542. // if (setup_finished)
  543. // ff_thread_finish_setup(h->avctx);
  544. return;
  545. }
  546. cur->f->interlaced_frame = 0;
  547. cur->f->repeat_pict = 0;
  548. /* Signal interlacing information externally. */
  549. /* Prioritize picture timing SEI information over used
  550. * decoding process if it exists. */
  551. if (h->sps.pic_struct_present_flag) {
  552. switch (h->sei_pic_struct) {
  553. case SEI_PIC_STRUCT_FRAME:
  554. break;
  555. case SEI_PIC_STRUCT_TOP_FIELD:
  556. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  557. cur->f->interlaced_frame = 1;
  558. break;
  559. case SEI_PIC_STRUCT_TOP_BOTTOM:
  560. case SEI_PIC_STRUCT_BOTTOM_TOP:
  561. if (FIELD_OR_MBAFF_PICTURE(h))
  562. cur->f->interlaced_frame = 1;
  563. else
  564. // try to flag soft telecine progressive
  565. cur->f->interlaced_frame = h->prev_interlaced_frame;
  566. break;
  567. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  568. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  569. /* Signal the possibility of telecined film externally
  570. * (pic_struct 5,6). From these hints, let the applications
  571. * decide if they apply deinterlacing. */
  572. cur->f->repeat_pict = 1;
  573. break;
  574. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  575. cur->f->repeat_pict = 2;
  576. break;
  577. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  578. cur->f->repeat_pict = 4;
  579. break;
  580. }
  581. if ((h->sei_ct_type & 3) &&
  582. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  583. cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  584. } else {
  585. /* Derive interlacing flag from used decoding process. */
  586. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  587. }
  588. h->prev_interlaced_frame = cur->f->interlaced_frame;
  589. if (cur->field_poc[0] != cur->field_poc[1]) {
  590. /* Derive top_field_first from field pocs. */
  591. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  592. } else {
  593. if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
  594. /* Use picture timing SEI information. Even if it is a
  595. * information of a past frame, better than nothing. */
  596. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  597. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  598. cur->f->top_field_first = 1;
  599. else
  600. cur->f->top_field_first = 0;
  601. } else {
  602. /* Most likely progressive */
  603. cur->f->top_field_first = 0;
  604. }
  605. }
  606. if (h->sei_frame_packing_present &&
  607. h->frame_packing_arrangement_type >= 0 &&
  608. h->frame_packing_arrangement_type <= 6 &&
  609. h->content_interpretation_type > 0 &&
  610. h->content_interpretation_type < 3) {
  611. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  612. if (!stereo)
  613. return;
  614. switch (h->frame_packing_arrangement_type) {
  615. case 0:
  616. stereo->type = AV_STEREO3D_CHECKERBOARD;
  617. break;
  618. case 1:
  619. stereo->type = AV_STEREO3D_COLUMNS;
  620. break;
  621. case 2:
  622. stereo->type = AV_STEREO3D_LINES;
  623. break;
  624. case 3:
  625. if (h->quincunx_subsampling)
  626. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  627. else
  628. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  629. break;
  630. case 4:
  631. stereo->type = AV_STEREO3D_TOPBOTTOM;
  632. break;
  633. case 5:
  634. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  635. break;
  636. case 6:
  637. stereo->type = AV_STEREO3D_2D;
  638. break;
  639. }
  640. if (h->content_interpretation_type == 2)
  641. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  642. }
  643. if (h->sei_display_orientation_present &&
  644. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  645. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  646. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  647. AV_FRAME_DATA_DISPLAYMATRIX,
  648. sizeof(int32_t) * 9);
  649. if (!rotation)
  650. return;
  651. av_display_rotation_set((int32_t *)rotation->data, angle);
  652. av_display_matrix_flip((int32_t *)rotation->data,
  653. h->sei_hflip, h->sei_vflip);
  654. }
  655. if (h->sei_reguserdata_afd_present) {
  656. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  657. sizeof(uint8_t));
  658. if (!sd)
  659. return;
  660. *sd->data = h->active_format_description;
  661. h->sei_reguserdata_afd_present = 0;
  662. }
  663. if (h->a53_caption) {
  664. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  665. AV_FRAME_DATA_A53_CC,
  666. h->a53_caption_size);
  667. if (!sd)
  668. return;
  669. memcpy(sd->data, h->a53_caption, h->a53_caption_size);
  670. av_freep(&h->a53_caption);
  671. h->a53_caption_size = 0;
  672. }
  673. // FIXME do something with unavailable reference frames
  674. /* Sort B-frames into display order */
  675. if (h->sps.bitstream_restriction_flag ||
  676. h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  677. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
  678. }
  679. h->low_delay = !h->avctx->has_b_frames;
  680. pics = 0;
  681. while (h->delayed_pic[pics])
  682. pics++;
  683. assert(pics <= MAX_DELAYED_PIC_COUNT);
  684. h->delayed_pic[pics++] = cur;
  685. if (cur->reference == 0)
  686. cur->reference = DELAYED_PIC_REF;
  687. /* Frame reordering. This code takes pictures from coding order and sorts
  688. * them by their incremental POC value into display order. It supports POC
  689. * gaps, MMCO reset codes and random resets.
  690. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  691. * and/or can be closed down with a MMCO reset code. In sequences where
  692. * there is no delay, we can't detect that (since the frame was already
  693. * output to the user), so we also set h->mmco_reset to detect the MMCO
  694. * reset code.
  695. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  696. * we increase the delay between input and output. All frames affected by
  697. * the lag (e.g. those that should have been output before another frame
  698. * that we already returned to the user) will be dropped. This is a bug
  699. * that we will fix later. */
  700. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  701. cnt += out->poc < h->last_pocs[i];
  702. invalid += out->poc == INT_MIN;
  703. }
  704. if (!h->mmco_reset && !cur->f->key_frame &&
  705. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  706. h->mmco_reset = 2;
  707. if (pics > 1)
  708. h->delayed_pic[pics - 2]->mmco_reset = 2;
  709. }
  710. if (h->mmco_reset || cur->f->key_frame) {
  711. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  712. h->last_pocs[i] = INT_MIN;
  713. cnt = 0;
  714. invalid = MAX_DELAYED_PIC_COUNT;
  715. }
  716. out = h->delayed_pic[0];
  717. out_idx = 0;
  718. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  719. h->delayed_pic[i] &&
  720. !h->delayed_pic[i - 1]->mmco_reset &&
  721. !h->delayed_pic[i]->f->key_frame;
  722. i++)
  723. if (h->delayed_pic[i]->poc < out->poc) {
  724. out = h->delayed_pic[i];
  725. out_idx = i;
  726. }
  727. if (h->avctx->has_b_frames == 0 &&
  728. (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
  729. h->next_outputed_poc = INT_MIN;
  730. out_of_order = !out->f->key_frame && !h->mmco_reset &&
  731. (out->poc < h->next_outputed_poc);
  732. if (h->sps.bitstream_restriction_flag &&
  733. h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
  734. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  735. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  736. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  737. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  738. }
  739. h->low_delay = 0;
  740. } else if (h->low_delay &&
  741. ((h->next_outputed_poc != INT_MIN &&
  742. out->poc > h->next_outputed_poc + 2) ||
  743. cur->f->pict_type == AV_PICTURE_TYPE_B)) {
  744. h->low_delay = 0;
  745. h->avctx->has_b_frames++;
  746. }
  747. if (pics > h->avctx->has_b_frames) {
  748. out->reference &= ~DELAYED_PIC_REF;
  749. // for frame threading, the owner must be the second field's thread or
  750. // else the first thread can release the picture and reuse it unsafely
  751. for (i = out_idx; h->delayed_pic[i]; i++)
  752. h->delayed_pic[i] = h->delayed_pic[i + 1];
  753. }
  754. memmove(h->last_pocs, &h->last_pocs[1],
  755. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  756. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  757. if (!out_of_order && pics > h->avctx->has_b_frames) {
  758. h->next_output_pic = out;
  759. if (out->mmco_reset) {
  760. if (out_idx > 0) {
  761. h->next_outputed_poc = out->poc;
  762. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  763. } else {
  764. h->next_outputed_poc = INT_MIN;
  765. }
  766. } else {
  767. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
  768. h->next_outputed_poc = INT_MIN;
  769. } else {
  770. h->next_outputed_poc = out->poc;
  771. }
  772. }
  773. h->mmco_reset = 0;
  774. } else {
  775. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  776. }
  777. if (h->next_output_pic) {
  778. if (h->next_output_pic->recovered) {
  779. // We have reached an recovery point and all frames after it in
  780. // display order are "recovered".
  781. h->frame_recovered |= FRAME_RECOVERED_SEI;
  782. }
  783. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  784. }
  785. if (setup_finished && !h->avctx->hwaccel) {
  786. ff_thread_finish_setup(h->avctx);
  787. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  788. h->setup_finished = 1;
  789. }
  790. }
  791. /**
  792. * instantaneous decoder refresh.
  793. */
  794. static void idr(H264Context *h)
  795. {
  796. ff_h264_remove_all_refs(h);
  797. h->prev_frame_num =
  798. h->prev_frame_num_offset =
  799. h->prev_poc_msb =
  800. h->prev_poc_lsb = 0;
  801. }
  802. /* forget old pics after a seek */
  803. void ff_h264_flush_change(H264Context *h)
  804. {
  805. int i;
  806. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  807. h->last_pocs[i] = INT_MIN;
  808. h->next_outputed_poc = INT_MIN;
  809. h->prev_interlaced_frame = 1;
  810. idr(h);
  811. if (h->cur_pic_ptr)
  812. h->cur_pic_ptr->reference = 0;
  813. h->first_field = 0;
  814. ff_h264_reset_sei(h);
  815. h->recovery_frame = -1;
  816. h->frame_recovered = 0;
  817. }
  818. /* forget old pics after a seek */
  819. static void flush_dpb(AVCodecContext *avctx)
  820. {
  821. H264Context *h = avctx->priv_data;
  822. int i;
  823. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  824. ff_h264_flush_change(h);
  825. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  826. ff_h264_unref_picture(h, &h->DPB[i]);
  827. h->cur_pic_ptr = NULL;
  828. ff_h264_unref_picture(h, &h->cur_pic);
  829. h->mb_y = 0;
  830. ff_h264_free_tables(h);
  831. h->context_initialized = 0;
  832. }
  833. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  834. {
  835. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  836. int field_poc[2];
  837. h->frame_num_offset = h->prev_frame_num_offset;
  838. if (h->frame_num < h->prev_frame_num)
  839. h->frame_num_offset += max_frame_num;
  840. if (h->sps.poc_type == 0) {
  841. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  842. if (h->poc_lsb < h->prev_poc_lsb &&
  843. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  844. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  845. else if (h->poc_lsb > h->prev_poc_lsb &&
  846. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  847. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  848. else
  849. h->poc_msb = h->prev_poc_msb;
  850. field_poc[0] =
  851. field_poc[1] = h->poc_msb + h->poc_lsb;
  852. if (h->picture_structure == PICT_FRAME)
  853. field_poc[1] += h->delta_poc_bottom;
  854. } else if (h->sps.poc_type == 1) {
  855. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  856. int i;
  857. if (h->sps.poc_cycle_length != 0)
  858. abs_frame_num = h->frame_num_offset + h->frame_num;
  859. else
  860. abs_frame_num = 0;
  861. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  862. abs_frame_num--;
  863. expected_delta_per_poc_cycle = 0;
  864. for (i = 0; i < h->sps.poc_cycle_length; i++)
  865. // FIXME integrate during sps parse
  866. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  867. if (abs_frame_num > 0) {
  868. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  869. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  870. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  871. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  872. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  873. } else
  874. expectedpoc = 0;
  875. if (h->nal_ref_idc == 0)
  876. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  877. field_poc[0] = expectedpoc + h->delta_poc[0];
  878. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  879. if (h->picture_structure == PICT_FRAME)
  880. field_poc[1] += h->delta_poc[1];
  881. } else {
  882. int poc = 2 * (h->frame_num_offset + h->frame_num);
  883. if (!h->nal_ref_idc)
  884. poc--;
  885. field_poc[0] = poc;
  886. field_poc[1] = poc;
  887. }
  888. if (h->picture_structure != PICT_BOTTOM_FIELD)
  889. pic_field_poc[0] = field_poc[0];
  890. if (h->picture_structure != PICT_TOP_FIELD)
  891. pic_field_poc[1] = field_poc[1];
  892. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  893. return 0;
  894. }
  895. /**
  896. * Compute profile from profile_idc and constraint_set?_flags.
  897. *
  898. * @param sps SPS
  899. *
  900. * @return profile as defined by FF_PROFILE_H264_*
  901. */
  902. int ff_h264_get_profile(SPS *sps)
  903. {
  904. int profile = sps->profile_idc;
  905. switch (sps->profile_idc) {
  906. case FF_PROFILE_H264_BASELINE:
  907. // constraint_set1_flag set to 1
  908. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  909. break;
  910. case FF_PROFILE_H264_HIGH_10:
  911. case FF_PROFILE_H264_HIGH_422:
  912. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  913. // constraint_set3_flag set to 1
  914. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  915. break;
  916. }
  917. return profile;
  918. }
  919. int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
  920. {
  921. int ref_count[2], list_count;
  922. int num_ref_idx_active_override_flag, max_refs;
  923. // set defaults, might be overridden a few lines later
  924. ref_count[0] = h->pps.ref_count[0];
  925. ref_count[1] = h->pps.ref_count[1];
  926. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  927. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  928. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  929. num_ref_idx_active_override_flag = get_bits1(&sl->gb);
  930. if (num_ref_idx_active_override_flag) {
  931. ref_count[0] = get_ue_golomb(&sl->gb) + 1;
  932. if (ref_count[0] < 1)
  933. return AVERROR_INVALIDDATA;
  934. if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  935. ref_count[1] = get_ue_golomb(&sl->gb) + 1;
  936. if (ref_count[1] < 1)
  937. return AVERROR_INVALIDDATA;
  938. }
  939. }
  940. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  941. list_count = 2;
  942. else
  943. list_count = 1;
  944. } else {
  945. list_count = 0;
  946. ref_count[0] = ref_count[1] = 0;
  947. }
  948. max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
  949. if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
  950. av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
  951. sl->ref_count[0] = sl->ref_count[1] = 0;
  952. return AVERROR_INVALIDDATA;
  953. }
  954. if (list_count != sl->list_count ||
  955. ref_count[0] != sl->ref_count[0] ||
  956. ref_count[1] != sl->ref_count[1]) {
  957. sl->ref_count[0] = ref_count[0];
  958. sl->ref_count[1] = ref_count[1];
  959. sl->list_count = list_count;
  960. return 1;
  961. }
  962. return 0;
  963. }
  964. static int get_last_needed_nal(H264Context *h)
  965. {
  966. int nals_needed = 0;
  967. int i;
  968. for (i = 0; i < h->pkt.nb_nals; i++) {
  969. H2645NAL *nal = &h->pkt.nals[i];
  970. GetBitContext gb;
  971. /* packets can sometimes contain multiple PPS/SPS,
  972. * e.g. two PAFF field pictures in one packet, or a demuxer
  973. * which splits NALs strangely if so, when frame threading we
  974. * can't start the next thread until we've read all of them */
  975. switch (nal->type) {
  976. case NAL_SPS:
  977. case NAL_PPS:
  978. nals_needed = i;
  979. break;
  980. case NAL_DPA:
  981. case NAL_IDR_SLICE:
  982. case NAL_SLICE:
  983. init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
  984. if (!get_ue_golomb(&gb))
  985. nals_needed = i;
  986. }
  987. }
  988. return nals_needed;
  989. }
  990. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  991. int parse_extradata)
  992. {
  993. AVCodecContext *const avctx = h->avctx;
  994. unsigned context_count = 0;
  995. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  996. int i, ret = 0;
  997. h->max_contexts = h->slice_context_count;
  998. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  999. h->current_slice = 0;
  1000. if (!h->first_field)
  1001. h->cur_pic_ptr = NULL;
  1002. ff_h264_reset_sei(h);
  1003. }
  1004. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  1005. h->nal_length_size, avctx->codec_id);
  1006. if (ret < 0) {
  1007. av_log(avctx, AV_LOG_ERROR,
  1008. "Error splitting the input into NAL units.\n");
  1009. return ret;
  1010. }
  1011. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1012. nals_needed = get_last_needed_nal(h);
  1013. for (i = 0; i < h->pkt.nb_nals; i++) {
  1014. H2645NAL *nal = &h->pkt.nals[i];
  1015. H264SliceContext *sl = &h->slice_ctx[context_count];
  1016. int err;
  1017. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1018. nal->ref_idc == 0 && nal->type != NAL_SEI)
  1019. continue;
  1020. again:
  1021. /* Ignore every NAL unit type except PPS and SPS during extradata
  1022. * parsing. Decoding slices is not possible in codec init
  1023. * with frame-mt */
  1024. if (parse_extradata && HAVE_THREADS &&
  1025. (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
  1026. (nal->type != NAL_PPS && nal->type != NAL_SPS)) {
  1027. if (nal->type < NAL_AUD || nal->type > NAL_AUXILIARY_SLICE)
  1028. av_log(avctx, AV_LOG_INFO,
  1029. "Ignoring NAL unit %d during extradata parsing\n",
  1030. nal->type);
  1031. nal->type = NAL_FF_IGNORE;
  1032. }
  1033. // FIXME these should stop being context-global variables
  1034. h->nal_ref_idc = nal->ref_idc;
  1035. h->nal_unit_type = nal->type;
  1036. err = 0;
  1037. switch (nal->type) {
  1038. case NAL_IDR_SLICE:
  1039. if (nal->type != NAL_IDR_SLICE) {
  1040. av_log(h->avctx, AV_LOG_ERROR,
  1041. "Invalid mix of idr and non-idr slices\n");
  1042. ret = -1;
  1043. goto end;
  1044. }
  1045. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1046. case NAL_SLICE:
  1047. sl->gb = nal->gb;
  1048. if ((err = ff_h264_decode_slice_header(h, sl)))
  1049. break;
  1050. if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
  1051. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1052. ((1 << h->sps.log2_max_frame_num) - 1);
  1053. }
  1054. h->cur_pic_ptr->f->key_frame |=
  1055. (nal->type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0);
  1056. if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->frame_num) {
  1057. h->recovery_frame = -1;
  1058. h->cur_pic_ptr->recovered = 1;
  1059. }
  1060. // If we have an IDR, all frames after it in decoded order are
  1061. // "recovered".
  1062. if (nal->type == NAL_IDR_SLICE)
  1063. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1064. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1065. if (h->current_slice == 1) {
  1066. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  1067. decode_postinit(h, i >= nals_needed);
  1068. if (h->avctx->hwaccel &&
  1069. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  1070. return ret;
  1071. }
  1072. if (sl->redundant_pic_count == 0 &&
  1073. (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
  1074. (avctx->skip_frame < AVDISCARD_BIDIR ||
  1075. sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
  1076. (avctx->skip_frame < AVDISCARD_NONKEY ||
  1077. h->cur_pic_ptr->f->key_frame) &&
  1078. avctx->skip_frame < AVDISCARD_ALL) {
  1079. if (avctx->hwaccel) {
  1080. ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
  1081. if (ret < 0)
  1082. return ret;
  1083. } else
  1084. context_count++;
  1085. }
  1086. break;
  1087. case NAL_DPA:
  1088. case NAL_DPB:
  1089. case NAL_DPC:
  1090. avpriv_request_sample(avctx, "data partitioning");
  1091. ret = AVERROR(ENOSYS);
  1092. goto end;
  1093. break;
  1094. case NAL_SEI:
  1095. h->gb = nal->gb;
  1096. ret = ff_h264_decode_sei(h);
  1097. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1098. goto end;
  1099. break;
  1100. case NAL_SPS:
  1101. h->gb = nal->gb;
  1102. ret = ff_h264_decode_seq_parameter_set(h);
  1103. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1104. goto end;
  1105. break;
  1106. case NAL_PPS:
  1107. h->gb = nal->gb;
  1108. ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
  1109. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1110. goto end;
  1111. break;
  1112. case NAL_AUD:
  1113. case NAL_END_SEQUENCE:
  1114. case NAL_END_STREAM:
  1115. case NAL_FILLER_DATA:
  1116. case NAL_SPS_EXT:
  1117. case NAL_AUXILIARY_SLICE:
  1118. break;
  1119. case NAL_FF_IGNORE:
  1120. break;
  1121. default:
  1122. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1123. nal->type, nal->size_bits);
  1124. }
  1125. if (context_count == h->max_contexts) {
  1126. ret = ff_h264_execute_decode_slices(h, context_count);
  1127. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1128. goto end;
  1129. context_count = 0;
  1130. }
  1131. if (err < 0) {
  1132. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1133. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1134. } else if (err == 1) {
  1135. /* Slice could not be decoded in parallel mode, restart. Note
  1136. * that rbsp_buffer is not transferred, but since we no longer
  1137. * run in parallel mode this should not be an issue. */
  1138. sl = &h->slice_ctx[0];
  1139. goto again;
  1140. }
  1141. }
  1142. if (context_count) {
  1143. ret = ff_h264_execute_decode_slices(h, context_count);
  1144. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1145. goto end;
  1146. }
  1147. ret = 0;
  1148. end:
  1149. /* clean up */
  1150. if (h->cur_pic_ptr && !h->droppable) {
  1151. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1152. h->picture_structure == PICT_BOTTOM_FIELD);
  1153. }
  1154. return (ret < 0) ? ret : buf_size;
  1155. }
  1156. /**
  1157. * Return the number of bytes consumed for building the current frame.
  1158. */
  1159. static int get_consumed_bytes(int pos, int buf_size)
  1160. {
  1161. if (pos == 0)
  1162. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1163. if (pos + 10 > buf_size)
  1164. pos = buf_size; // oops ;)
  1165. return pos;
  1166. }
  1167. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  1168. {
  1169. int i;
  1170. int ret = av_frame_ref(dst, src);
  1171. if (ret < 0)
  1172. return ret;
  1173. if (!h->sps.crop)
  1174. return 0;
  1175. for (i = 0; i < 3; i++) {
  1176. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  1177. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  1178. int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
  1179. (h->sps.crop_top >> vshift) * dst->linesize[i];
  1180. dst->data[i] += off;
  1181. }
  1182. return 0;
  1183. }
  1184. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1185. int *got_frame, AVPacket *avpkt)
  1186. {
  1187. const uint8_t *buf = avpkt->data;
  1188. int buf_size = avpkt->size;
  1189. H264Context *h = avctx->priv_data;
  1190. AVFrame *pict = data;
  1191. int buf_index = 0;
  1192. int ret;
  1193. h->flags = avctx->flags;
  1194. h->setup_finished = 0;
  1195. /* end of stream, output what is still in the buffers */
  1196. out:
  1197. if (buf_size == 0) {
  1198. H264Picture *out;
  1199. int i, out_idx;
  1200. h->cur_pic_ptr = NULL;
  1201. // FIXME factorize this with the output code below
  1202. out = h->delayed_pic[0];
  1203. out_idx = 0;
  1204. for (i = 1;
  1205. h->delayed_pic[i] &&
  1206. !h->delayed_pic[i]->f->key_frame &&
  1207. !h->delayed_pic[i]->mmco_reset;
  1208. i++)
  1209. if (h->delayed_pic[i]->poc < out->poc) {
  1210. out = h->delayed_pic[i];
  1211. out_idx = i;
  1212. }
  1213. for (i = out_idx; h->delayed_pic[i]; i++)
  1214. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1215. if (out) {
  1216. ret = output_frame(h, pict, out->f);
  1217. if (ret < 0)
  1218. return ret;
  1219. *got_frame = 1;
  1220. }
  1221. return buf_index;
  1222. }
  1223. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1224. if (buf_index < 0)
  1225. return AVERROR_INVALIDDATA;
  1226. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1227. buf_size = 0;
  1228. goto out;
  1229. }
  1230. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1231. if (avctx->skip_frame >= AVDISCARD_NONREF)
  1232. return 0;
  1233. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1234. return AVERROR_INVALIDDATA;
  1235. }
  1236. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1237. (h->mb_y >= h->mb_height && h->mb_height)) {
  1238. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1239. decode_postinit(h, 1);
  1240. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  1241. *got_frame = 0;
  1242. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1243. h->next_output_pic->recovered)) {
  1244. if (!h->next_output_pic->recovered)
  1245. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1246. ret = output_frame(h, pict, h->next_output_pic->f);
  1247. if (ret < 0)
  1248. return ret;
  1249. *got_frame = 1;
  1250. }
  1251. }
  1252. assert(pict->buf[0] || !*got_frame);
  1253. return get_consumed_bytes(buf_index, buf_size);
  1254. }
  1255. av_cold void ff_h264_free_context(H264Context *h)
  1256. {
  1257. int i;
  1258. ff_h264_free_tables(h);
  1259. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  1260. ff_h264_unref_picture(h, &h->DPB[i]);
  1261. av_frame_free(&h->DPB[i].f);
  1262. }
  1263. h->cur_pic_ptr = NULL;
  1264. for (i = 0; i < h->nb_slice_ctx; i++)
  1265. av_freep(&h->slice_ctx[i].rbsp_buffer);
  1266. av_freep(&h->slice_ctx);
  1267. h->nb_slice_ctx = 0;
  1268. for (i = 0; i < MAX_SPS_COUNT; i++)
  1269. av_freep(h->sps_buffers + i);
  1270. for (i = 0; i < MAX_PPS_COUNT; i++)
  1271. av_freep(h->pps_buffers + i);
  1272. ff_h2645_packet_uninit(&h->pkt);
  1273. }
  1274. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1275. {
  1276. H264Context *h = avctx->priv_data;
  1277. ff_h264_free_context(h);
  1278. ff_h264_unref_picture(h, &h->cur_pic);
  1279. av_frame_free(&h->cur_pic.f);
  1280. return 0;
  1281. }
  1282. #define OFFSET(x) offsetof(H264Context, x)
  1283. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1284. static const AVOption h264_options[] = {
  1285. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  1286. { NULL },
  1287. };
  1288. static const AVClass h264_class = {
  1289. .class_name = "h264",
  1290. .item_name = av_default_item_name,
  1291. .option = h264_options,
  1292. .version = LIBAVUTIL_VERSION_INT,
  1293. };
  1294. AVCodec ff_h264_decoder = {
  1295. .name = "h264",
  1296. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1297. .type = AVMEDIA_TYPE_VIDEO,
  1298. .id = AV_CODEC_ID_H264,
  1299. .priv_data_size = sizeof(H264Context),
  1300. .init = ff_h264_decode_init,
  1301. .close = h264_decode_end,
  1302. .decode = h264_decode_frame,
  1303. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1304. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1305. AV_CODEC_CAP_FRAME_THREADS,
  1306. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1307. .flush = flush_dpb,
  1308. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1309. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1310. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1311. .priv_class = &h264_class,
  1312. };