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.

1881 lines
63KB

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