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.

1638 lines
53KB

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