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.

1870 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 "dsputil.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 "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 == NULL)
  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->dsp = &h->dsp;
  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. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
  443. fail); // error ressilience code looks cleaner with this
  444. for (y = 0; y < h->mb_height; y++)
  445. for (x = 0; x < h->mb_width; x++)
  446. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  447. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  448. h->mb_stride + h->mb_width;
  449. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  450. mb_array_size * sizeof(uint8_t), fail);
  451. FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
  452. memset(er->mbintra_table, 1, mb_array_size);
  453. FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
  454. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
  455. fail);
  456. FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
  457. er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
  458. er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
  459. er->dc_val[2] = er->dc_val[1] + c_size;
  460. for (i = 0; i < yc_size; i++)
  461. h->dc_val_base[i] = 1024;
  462. }
  463. return 0;
  464. fail:
  465. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  466. }
  467. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  468. int parse_extradata);
  469. int ff_h264_decode_extradata(H264Context *h)
  470. {
  471. AVCodecContext *avctx = h->avctx;
  472. int ret;
  473. if (avctx->extradata[0] == 1) {
  474. int i, cnt, nalsize;
  475. unsigned char *p = avctx->extradata;
  476. h->is_avc = 1;
  477. if (avctx->extradata_size < 7) {
  478. av_log(avctx, AV_LOG_ERROR,
  479. "avcC %d too short\n", avctx->extradata_size);
  480. return AVERROR_INVALIDDATA;
  481. }
  482. /* sps and pps in the avcC always have length coded with 2 bytes,
  483. * so put a fake nal_length_size = 2 while parsing them */
  484. h->nal_length_size = 2;
  485. // Decode sps from avcC
  486. cnt = *(p + 5) & 0x1f; // Number of sps
  487. p += 6;
  488. for (i = 0; i < cnt; i++) {
  489. nalsize = AV_RB16(p) + 2;
  490. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  491. return AVERROR_INVALIDDATA;
  492. ret = decode_nal_units(h, p, nalsize, 1);
  493. if (ret < 0) {
  494. av_log(avctx, AV_LOG_ERROR,
  495. "Decoding sps %d from avcC failed\n", i);
  496. return ret;
  497. }
  498. p += nalsize;
  499. }
  500. // Decode pps from avcC
  501. cnt = *(p++); // Number of pps
  502. for (i = 0; i < cnt; i++) {
  503. nalsize = AV_RB16(p) + 2;
  504. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  505. return AVERROR_INVALIDDATA;
  506. ret = decode_nal_units(h, p, nalsize, 1);
  507. if (ret < 0) {
  508. av_log(avctx, AV_LOG_ERROR,
  509. "Decoding pps %d from avcC failed\n", i);
  510. return ret;
  511. }
  512. p += nalsize;
  513. }
  514. // Now store right nal length size, that will be used to parse all other nals
  515. h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
  516. } else {
  517. h->is_avc = 0;
  518. ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
  519. if (ret < 0)
  520. return ret;
  521. }
  522. return 0;
  523. }
  524. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  525. {
  526. H264Context *h = avctx->priv_data;
  527. int i;
  528. int ret;
  529. h->avctx = avctx;
  530. h->bit_depth_luma = 8;
  531. h->chroma_format_idc = 1;
  532. ff_h264dsp_init(&h->h264dsp, 8, 1);
  533. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  534. ff_h264qpel_init(&h->h264qpel, 8);
  535. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
  536. h->dequant_coeff_pps = -1;
  537. /* needed so that IDCT permutation is known early */
  538. if (CONFIG_ERROR_RESILIENCE)
  539. ff_dsputil_init(&h->dsp, h->avctx);
  540. ff_videodsp_init(&h->vdsp, 8);
  541. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  542. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  543. h->picture_structure = PICT_FRAME;
  544. h->slice_context_count = 1;
  545. h->workaround_bugs = avctx->workaround_bugs;
  546. h->flags = avctx->flags;
  547. /* set defaults */
  548. // s->decode_mb = ff_h263_decode_mb;
  549. if (!avctx->has_b_frames)
  550. h->low_delay = 1;
  551. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  552. ff_h264_decode_init_vlc();
  553. ff_init_cabac_states();
  554. h->pixel_shift = 0;
  555. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  556. h->thread_context[0] = h;
  557. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  558. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  559. h->last_pocs[i] = INT_MIN;
  560. h->prev_poc_msb = 1 << 16;
  561. h->x264_build = -1;
  562. ff_h264_reset_sei(h);
  563. h->recovery_frame = -1;
  564. h->frame_recovered = 0;
  565. if (avctx->codec_id == AV_CODEC_ID_H264) {
  566. if (avctx->ticks_per_frame == 1)
  567. h->avctx->time_base.den *= 2;
  568. avctx->ticks_per_frame = 2;
  569. }
  570. if (avctx->extradata_size > 0 && avctx->extradata) {
  571. ret = ff_h264_decode_extradata(h);
  572. if (ret < 0)
  573. return ret;
  574. }
  575. if (h->sps.bitstream_restriction_flag &&
  576. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  577. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  578. h->low_delay = 0;
  579. }
  580. avctx->internal->allocate_progress = 1;
  581. return 0;
  582. }
  583. static int decode_init_thread_copy(AVCodecContext *avctx)
  584. {
  585. H264Context *h = avctx->priv_data;
  586. if (!avctx->internal->is_copy)
  587. return 0;
  588. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  589. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  590. h->context_initialized = 0;
  591. return 0;
  592. }
  593. /**
  594. * Run setup operations that must be run after slice header decoding.
  595. * This includes finding the next displayed frame.
  596. *
  597. * @param h h264 master context
  598. * @param setup_finished enough NALs have been read that we can call
  599. * ff_thread_finish_setup()
  600. */
  601. static void decode_postinit(H264Context *h, int setup_finished)
  602. {
  603. H264Picture *out = h->cur_pic_ptr;
  604. H264Picture *cur = h->cur_pic_ptr;
  605. int i, pics, out_of_order, out_idx;
  606. int invalid = 0, cnt = 0;
  607. h->cur_pic_ptr->f.pict_type = h->pict_type;
  608. if (h->next_output_pic)
  609. return;
  610. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  611. /* FIXME: if we have two PAFF fields in one packet, we can't start
  612. * the next thread here. If we have one field per packet, we can.
  613. * The check in decode_nal_units() is not good enough to find this
  614. * yet, so we assume the worst for now. */
  615. // if (setup_finished)
  616. // ff_thread_finish_setup(h->avctx);
  617. return;
  618. }
  619. cur->f.interlaced_frame = 0;
  620. cur->f.repeat_pict = 0;
  621. /* Signal interlacing information externally. */
  622. /* Prioritize picture timing SEI information over used
  623. * decoding process if it exists. */
  624. if (h->sps.pic_struct_present_flag) {
  625. switch (h->sei_pic_struct) {
  626. case SEI_PIC_STRUCT_FRAME:
  627. break;
  628. case SEI_PIC_STRUCT_TOP_FIELD:
  629. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  630. cur->f.interlaced_frame = 1;
  631. break;
  632. case SEI_PIC_STRUCT_TOP_BOTTOM:
  633. case SEI_PIC_STRUCT_BOTTOM_TOP:
  634. if (FIELD_OR_MBAFF_PICTURE(h))
  635. cur->f.interlaced_frame = 1;
  636. else
  637. // try to flag soft telecine progressive
  638. cur->f.interlaced_frame = h->prev_interlaced_frame;
  639. break;
  640. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  641. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  642. /* Signal the possibility of telecined film externally
  643. * (pic_struct 5,6). From these hints, let the applications
  644. * decide if they apply deinterlacing. */
  645. cur->f.repeat_pict = 1;
  646. break;
  647. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  648. cur->f.repeat_pict = 2;
  649. break;
  650. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  651. cur->f.repeat_pict = 4;
  652. break;
  653. }
  654. if ((h->sei_ct_type & 3) &&
  655. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  656. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  657. } else {
  658. /* Derive interlacing flag from used decoding process. */
  659. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  660. }
  661. h->prev_interlaced_frame = cur->f.interlaced_frame;
  662. if (cur->field_poc[0] != cur->field_poc[1]) {
  663. /* Derive top_field_first from field pocs. */
  664. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  665. } else {
  666. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  667. /* Use picture timing SEI information. Even if it is a
  668. * information of a past frame, better than nothing. */
  669. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  670. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  671. cur->f.top_field_first = 1;
  672. else
  673. cur->f.top_field_first = 0;
  674. } else {
  675. /* Most likely progressive */
  676. cur->f.top_field_first = 0;
  677. }
  678. }
  679. if (h->sei_frame_packing_present &&
  680. h->frame_packing_arrangement_type >= 0 &&
  681. h->frame_packing_arrangement_type <= 6 &&
  682. h->content_interpretation_type > 0 &&
  683. h->content_interpretation_type < 3) {
  684. AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
  685. if (!stereo)
  686. return;
  687. switch (h->frame_packing_arrangement_type) {
  688. case 0:
  689. stereo->type = AV_STEREO3D_CHECKERBOARD;
  690. break;
  691. case 1:
  692. stereo->type = AV_STEREO3D_LINES;
  693. break;
  694. case 2:
  695. stereo->type = AV_STEREO3D_COLUMNS;
  696. break;
  697. case 3:
  698. if (h->quincunx_subsampling)
  699. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  700. else
  701. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  702. break;
  703. case 4:
  704. stereo->type = AV_STEREO3D_TOPBOTTOM;
  705. break;
  706. case 5:
  707. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  708. break;
  709. case 6:
  710. stereo->type = AV_STEREO3D_2D;
  711. break;
  712. }
  713. if (h->content_interpretation_type == 2)
  714. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  715. }
  716. if (h->sei_display_orientation_present &&
  717. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  718. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  719. AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
  720. AV_FRAME_DATA_DISPLAYMATRIX,
  721. sizeof(int32_t) * 9);
  722. if (!rotation)
  723. return;
  724. av_display_rotation_set((int32_t *)rotation->data, angle);
  725. av_display_matrix_flip((int32_t *)rotation->data,
  726. h->sei_vflip, h->sei_hflip);
  727. }
  728. // FIXME do something with unavailable reference frames
  729. /* Sort B-frames into display order */
  730. if (h->sps.bitstream_restriction_flag &&
  731. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  732. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  733. h->low_delay = 0;
  734. }
  735. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  736. !h->sps.bitstream_restriction_flag) {
  737. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  738. h->low_delay = 0;
  739. }
  740. pics = 0;
  741. while (h->delayed_pic[pics])
  742. pics++;
  743. assert(pics <= MAX_DELAYED_PIC_COUNT);
  744. h->delayed_pic[pics++] = cur;
  745. if (cur->reference == 0)
  746. cur->reference = DELAYED_PIC_REF;
  747. /* Frame reordering. This code takes pictures from coding order and sorts
  748. * them by their incremental POC value into display order. It supports POC
  749. * gaps, MMCO reset codes and random resets.
  750. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  751. * and/or can be closed down with a MMCO reset code. In sequences where
  752. * there is no delay, we can't detect that (since the frame was already
  753. * output to the user), so we also set h->mmco_reset to detect the MMCO
  754. * reset code.
  755. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  756. * we increase the delay between input and output. All frames affected by
  757. * the lag (e.g. those that should have been output before another frame
  758. * that we already returned to the user) will be dropped. This is a bug
  759. * that we will fix later. */
  760. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  761. cnt += out->poc < h->last_pocs[i];
  762. invalid += out->poc == INT_MIN;
  763. }
  764. if (!h->mmco_reset && !cur->f.key_frame &&
  765. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  766. h->mmco_reset = 2;
  767. if (pics > 1)
  768. h->delayed_pic[pics - 2]->mmco_reset = 2;
  769. }
  770. if (h->mmco_reset || cur->f.key_frame) {
  771. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  772. h->last_pocs[i] = INT_MIN;
  773. cnt = 0;
  774. invalid = MAX_DELAYED_PIC_COUNT;
  775. }
  776. out = h->delayed_pic[0];
  777. out_idx = 0;
  778. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  779. h->delayed_pic[i] &&
  780. !h->delayed_pic[i - 1]->mmco_reset &&
  781. !h->delayed_pic[i]->f.key_frame;
  782. i++)
  783. if (h->delayed_pic[i]->poc < out->poc) {
  784. out = h->delayed_pic[i];
  785. out_idx = i;
  786. }
  787. if (h->avctx->has_b_frames == 0 &&
  788. (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
  789. h->next_outputed_poc = INT_MIN;
  790. out_of_order = !out->f.key_frame && !h->mmco_reset &&
  791. (out->poc < h->next_outputed_poc);
  792. if (h->sps.bitstream_restriction_flag &&
  793. h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
  794. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  795. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  796. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  797. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  798. }
  799. h->low_delay = 0;
  800. } else if (h->low_delay &&
  801. ((h->next_outputed_poc != INT_MIN &&
  802. out->poc > h->next_outputed_poc + 2) ||
  803. cur->f.pict_type == AV_PICTURE_TYPE_B)) {
  804. h->low_delay = 0;
  805. h->avctx->has_b_frames++;
  806. }
  807. if (pics > h->avctx->has_b_frames) {
  808. out->reference &= ~DELAYED_PIC_REF;
  809. // for frame threading, the owner must be the second field's thread or
  810. // else the first thread can release the picture and reuse it unsafely
  811. for (i = out_idx; h->delayed_pic[i]; i++)
  812. h->delayed_pic[i] = h->delayed_pic[i + 1];
  813. }
  814. memmove(h->last_pocs, &h->last_pocs[1],
  815. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  816. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  817. if (!out_of_order && pics > h->avctx->has_b_frames) {
  818. h->next_output_pic = out;
  819. if (out->mmco_reset) {
  820. if (out_idx > 0) {
  821. h->next_outputed_poc = out->poc;
  822. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  823. } else {
  824. h->next_outputed_poc = INT_MIN;
  825. }
  826. } else {
  827. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
  828. h->next_outputed_poc = INT_MIN;
  829. } else {
  830. h->next_outputed_poc = out->poc;
  831. }
  832. }
  833. h->mmco_reset = 0;
  834. } else {
  835. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  836. }
  837. if (h->next_output_pic) {
  838. if (h->next_output_pic->recovered) {
  839. // We have reached an recovery point and all frames after it in
  840. // display order are "recovered".
  841. h->frame_recovered |= FRAME_RECOVERED_SEI;
  842. }
  843. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  844. }
  845. if (setup_finished && !h->avctx->hwaccel)
  846. ff_thread_finish_setup(h->avctx);
  847. }
  848. int ff_pred_weight_table(H264Context *h)
  849. {
  850. int list, i;
  851. int luma_def, chroma_def;
  852. h->use_weight = 0;
  853. h->use_weight_chroma = 0;
  854. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  855. if (h->sps.chroma_format_idc)
  856. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  857. luma_def = 1 << h->luma_log2_weight_denom;
  858. chroma_def = 1 << h->chroma_log2_weight_denom;
  859. for (list = 0; list < 2; list++) {
  860. h->luma_weight_flag[list] = 0;
  861. h->chroma_weight_flag[list] = 0;
  862. for (i = 0; i < h->ref_count[list]; i++) {
  863. int luma_weight_flag, chroma_weight_flag;
  864. luma_weight_flag = get_bits1(&h->gb);
  865. if (luma_weight_flag) {
  866. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  867. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  868. if (h->luma_weight[i][list][0] != luma_def ||
  869. h->luma_weight[i][list][1] != 0) {
  870. h->use_weight = 1;
  871. h->luma_weight_flag[list] = 1;
  872. }
  873. } else {
  874. h->luma_weight[i][list][0] = luma_def;
  875. h->luma_weight[i][list][1] = 0;
  876. }
  877. if (h->sps.chroma_format_idc) {
  878. chroma_weight_flag = get_bits1(&h->gb);
  879. if (chroma_weight_flag) {
  880. int j;
  881. for (j = 0; j < 2; j++) {
  882. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  883. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  884. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  885. h->chroma_weight[i][list][j][1] != 0) {
  886. h->use_weight_chroma = 1;
  887. h->chroma_weight_flag[list] = 1;
  888. }
  889. }
  890. } else {
  891. int j;
  892. for (j = 0; j < 2; j++) {
  893. h->chroma_weight[i][list][j][0] = chroma_def;
  894. h->chroma_weight[i][list][j][1] = 0;
  895. }
  896. }
  897. }
  898. }
  899. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  900. break;
  901. }
  902. h->use_weight = h->use_weight || h->use_weight_chroma;
  903. return 0;
  904. }
  905. /**
  906. * instantaneous decoder refresh.
  907. */
  908. static void idr(H264Context *h)
  909. {
  910. ff_h264_remove_all_refs(h);
  911. h->prev_frame_num = 0;
  912. h->prev_frame_num_offset = 0;
  913. h->prev_poc_msb =
  914. h->prev_poc_lsb = 0;
  915. }
  916. /* forget old pics after a seek */
  917. void ff_h264_flush_change(H264Context *h)
  918. {
  919. int i;
  920. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  921. h->last_pocs[i] = INT_MIN;
  922. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  923. h->prev_interlaced_frame = 1;
  924. idr(h);
  925. if (h->cur_pic_ptr)
  926. h->cur_pic_ptr->reference = 0;
  927. h->first_field = 0;
  928. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  929. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  930. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  931. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  932. ff_h264_reset_sei(h);
  933. h->recovery_frame = -1;
  934. h->frame_recovered = 0;
  935. }
  936. /* forget old pics after a seek */
  937. static void flush_dpb(AVCodecContext *avctx)
  938. {
  939. H264Context *h = avctx->priv_data;
  940. int i;
  941. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  942. if (h->delayed_pic[i])
  943. h->delayed_pic[i]->reference = 0;
  944. h->delayed_pic[i] = NULL;
  945. }
  946. ff_h264_flush_change(h);
  947. if (h->DPB)
  948. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  949. ff_h264_unref_picture(h, &h->DPB[i]);
  950. h->cur_pic_ptr = NULL;
  951. ff_h264_unref_picture(h, &h->cur_pic);
  952. h->mb_x = h->mb_y = 0;
  953. h->parse_context.state = -1;
  954. h->parse_context.frame_start_found = 0;
  955. h->parse_context.overread = 0;
  956. h->parse_context.overread_index = 0;
  957. h->parse_context.index = 0;
  958. h->parse_context.last_index = 0;
  959. ff_h264_free_tables(h, 1);
  960. h->context_initialized = 0;
  961. }
  962. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  963. {
  964. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  965. int field_poc[2];
  966. h->frame_num_offset = h->prev_frame_num_offset;
  967. if (h->frame_num < h->prev_frame_num)
  968. h->frame_num_offset += max_frame_num;
  969. if (h->sps.poc_type == 0) {
  970. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  971. if (h->poc_lsb < h->prev_poc_lsb &&
  972. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  973. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  974. else if (h->poc_lsb > h->prev_poc_lsb &&
  975. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  976. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  977. else
  978. h->poc_msb = h->prev_poc_msb;
  979. field_poc[0] =
  980. field_poc[1] = h->poc_msb + h->poc_lsb;
  981. if (h->picture_structure == PICT_FRAME)
  982. field_poc[1] += h->delta_poc_bottom;
  983. } else if (h->sps.poc_type == 1) {
  984. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  985. int i;
  986. if (h->sps.poc_cycle_length != 0)
  987. abs_frame_num = h->frame_num_offset + h->frame_num;
  988. else
  989. abs_frame_num = 0;
  990. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  991. abs_frame_num--;
  992. expected_delta_per_poc_cycle = 0;
  993. for (i = 0; i < h->sps.poc_cycle_length; i++)
  994. // FIXME integrate during sps parse
  995. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  996. if (abs_frame_num > 0) {
  997. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  998. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  999. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1000. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1001. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1002. } else
  1003. expectedpoc = 0;
  1004. if (h->nal_ref_idc == 0)
  1005. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1006. field_poc[0] = expectedpoc + h->delta_poc[0];
  1007. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1008. if (h->picture_structure == PICT_FRAME)
  1009. field_poc[1] += h->delta_poc[1];
  1010. } else {
  1011. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1012. if (!h->nal_ref_idc)
  1013. poc--;
  1014. field_poc[0] = poc;
  1015. field_poc[1] = poc;
  1016. }
  1017. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1018. pic_field_poc[0] = field_poc[0];
  1019. if (h->picture_structure != PICT_TOP_FIELD)
  1020. pic_field_poc[1] = field_poc[1];
  1021. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1022. return 0;
  1023. }
  1024. /**
  1025. * Compute profile from profile_idc and constraint_set?_flags.
  1026. *
  1027. * @param sps SPS
  1028. *
  1029. * @return profile as defined by FF_PROFILE_H264_*
  1030. */
  1031. int ff_h264_get_profile(SPS *sps)
  1032. {
  1033. int profile = sps->profile_idc;
  1034. switch (sps->profile_idc) {
  1035. case FF_PROFILE_H264_BASELINE:
  1036. // constraint_set1_flag set to 1
  1037. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1038. break;
  1039. case FF_PROFILE_H264_HIGH_10:
  1040. case FF_PROFILE_H264_HIGH_422:
  1041. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1042. // constraint_set3_flag set to 1
  1043. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1044. break;
  1045. }
  1046. return profile;
  1047. }
  1048. int ff_h264_set_parameter_from_sps(H264Context *h)
  1049. {
  1050. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  1051. (h->sps.bitstream_restriction_flag &&
  1052. !h->sps.num_reorder_frames)) {
  1053. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  1054. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  1055. "Reenabling low delay requires a codec flush.\n");
  1056. else
  1057. h->low_delay = 1;
  1058. }
  1059. if (h->avctx->has_b_frames < 2)
  1060. h->avctx->has_b_frames = !h->low_delay;
  1061. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  1062. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  1063. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
  1064. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1065. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  1066. h->pixel_shift = h->sps.bit_depth_luma > 8;
  1067. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  1068. h->sps.chroma_format_idc);
  1069. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1070. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  1071. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  1072. h->sps.chroma_format_idc);
  1073. if (CONFIG_ERROR_RESILIENCE)
  1074. ff_dsputil_init(&h->dsp, h->avctx);
  1075. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  1076. } else {
  1077. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  1078. h->sps.bit_depth_luma);
  1079. return AVERROR_INVALIDDATA;
  1080. }
  1081. }
  1082. return 0;
  1083. }
  1084. int ff_set_ref_count(H264Context *h)
  1085. {
  1086. int ref_count[2], list_count;
  1087. int num_ref_idx_active_override_flag, max_refs;
  1088. // set defaults, might be overridden a few lines later
  1089. ref_count[0] = h->pps.ref_count[0];
  1090. ref_count[1] = h->pps.ref_count[1];
  1091. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  1092. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  1093. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  1094. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  1095. if (num_ref_idx_active_override_flag) {
  1096. ref_count[0] = get_ue_golomb(&h->gb) + 1;
  1097. if (ref_count[0] < 1)
  1098. return AVERROR_INVALIDDATA;
  1099. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  1100. ref_count[1] = get_ue_golomb(&h->gb) + 1;
  1101. if (ref_count[1] < 1)
  1102. return AVERROR_INVALIDDATA;
  1103. }
  1104. }
  1105. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  1106. list_count = 2;
  1107. else
  1108. list_count = 1;
  1109. } else {
  1110. list_count = 0;
  1111. ref_count[0] = ref_count[1] = 0;
  1112. }
  1113. max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
  1114. if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
  1115. av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
  1116. h->ref_count[0] = h->ref_count[1] = 0;
  1117. return AVERROR_INVALIDDATA;
  1118. }
  1119. if (list_count != h->list_count ||
  1120. ref_count[0] != h->ref_count[0] ||
  1121. ref_count[1] != h->ref_count[1]) {
  1122. h->ref_count[0] = ref_count[0];
  1123. h->ref_count[1] = ref_count[1];
  1124. h->list_count = list_count;
  1125. return 1;
  1126. }
  1127. return 0;
  1128. }
  1129. static int find_start_code(const uint8_t *buf, int buf_size,
  1130. int buf_index, int next_avc)
  1131. {
  1132. // start code prefix search
  1133. for (; buf_index + 3 < next_avc; buf_index++)
  1134. // This should always succeed in the first iteration.
  1135. if (buf[buf_index] == 0 &&
  1136. buf[buf_index + 1] == 0 &&
  1137. buf[buf_index + 2] == 1)
  1138. break;
  1139. if (buf_index + 3 >= buf_size)
  1140. return buf_size;
  1141. return buf_index + 3;
  1142. }
  1143. static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
  1144. int buf_size, int *buf_index)
  1145. {
  1146. int i, nalsize = 0;
  1147. if (*buf_index >= buf_size - h->nal_length_size)
  1148. return -1;
  1149. for (i = 0; i < h->nal_length_size; i++)
  1150. nalsize = (nalsize << 8) | buf[(*buf_index)++];
  1151. if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
  1152. av_log(h->avctx, AV_LOG_ERROR,
  1153. "AVC: nal size %d\n", nalsize);
  1154. return -1;
  1155. }
  1156. return nalsize;
  1157. }
  1158. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1159. const uint8_t *ptr, int dst_length,
  1160. int i, int next_avc)
  1161. {
  1162. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1163. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1164. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1165. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1166. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1167. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1168. dst_length--;
  1169. if (!dst_length)
  1170. return 0;
  1171. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1172. }
  1173. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1174. {
  1175. int next_avc = h->is_avc ? 0 : buf_size;
  1176. int nal_index = 0;
  1177. int buf_index = 0;
  1178. int nals_needed = 0;
  1179. while(1) {
  1180. int nalsize = 0;
  1181. int dst_length, bit_length, consumed;
  1182. const uint8_t *ptr;
  1183. if (buf_index >= next_avc) {
  1184. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1185. if (nalsize < 0)
  1186. break;
  1187. next_avc = buf_index + nalsize;
  1188. } else {
  1189. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1190. if (buf_index >= buf_size)
  1191. break;
  1192. }
  1193. ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
  1194. next_avc - buf_index);
  1195. if (ptr == NULL || dst_length < 0)
  1196. return AVERROR_INVALIDDATA;
  1197. buf_index += consumed;
  1198. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1199. buf_index, next_avc);
  1200. nal_index++;
  1201. /* packets can sometimes contain multiple PPS/SPS,
  1202. * e.g. two PAFF field pictures in one packet, or a demuxer
  1203. * which splits NALs strangely if so, when frame threading we
  1204. * can't start the next thread until we've read all of them */
  1205. switch (h->nal_unit_type) {
  1206. case NAL_SPS:
  1207. case NAL_PPS:
  1208. nals_needed = nal_index;
  1209. break;
  1210. case NAL_DPA:
  1211. case NAL_IDR_SLICE:
  1212. case NAL_SLICE:
  1213. init_get_bits(&h->gb, ptr, bit_length);
  1214. if (!get_ue_golomb(&h->gb))
  1215. nals_needed = nal_index;
  1216. }
  1217. }
  1218. return nals_needed;
  1219. }
  1220. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1221. int parse_extradata)
  1222. {
  1223. AVCodecContext *const avctx = h->avctx;
  1224. H264Context *hx; ///< thread context
  1225. int buf_index;
  1226. unsigned context_count;
  1227. int next_avc;
  1228. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1229. int nal_index;
  1230. int ret = 0;
  1231. h->max_contexts = h->slice_context_count;
  1232. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  1233. h->current_slice = 0;
  1234. if (!h->first_field)
  1235. h->cur_pic_ptr = NULL;
  1236. ff_h264_reset_sei(h);
  1237. }
  1238. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1239. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1240. {
  1241. buf_index = 0;
  1242. context_count = 0;
  1243. next_avc = h->is_avc ? 0 : buf_size;
  1244. nal_index = 0;
  1245. for (;;) {
  1246. int consumed;
  1247. int dst_length;
  1248. int bit_length;
  1249. const uint8_t *ptr;
  1250. int nalsize = 0;
  1251. int err;
  1252. if (buf_index >= next_avc) {
  1253. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1254. if (nalsize < 0)
  1255. break;
  1256. next_avc = buf_index + nalsize;
  1257. } else {
  1258. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1259. if (buf_index >= buf_size)
  1260. break;
  1261. }
  1262. hx = h->thread_context[context_count];
  1263. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  1264. &consumed, next_avc - buf_index);
  1265. if (ptr == NULL || dst_length < 0) {
  1266. ret = -1;
  1267. goto end;
  1268. }
  1269. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1270. buf_index + consumed, next_avc);
  1271. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1272. av_log(h->avctx, AV_LOG_DEBUG,
  1273. "NAL %d at %d/%d length %d\n",
  1274. hx->nal_unit_type, buf_index, buf_size, dst_length);
  1275. if (h->is_avc && (nalsize != consumed) && nalsize)
  1276. av_log(h->avctx, AV_LOG_DEBUG,
  1277. "AVC: Consumed only %d bytes instead of %d\n",
  1278. consumed, nalsize);
  1279. buf_index += consumed;
  1280. nal_index++;
  1281. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1282. h->nal_ref_idc == 0 &&
  1283. h->nal_unit_type != NAL_SEI)
  1284. continue;
  1285. again:
  1286. /* Ignore every NAL unit type except PPS and SPS during extradata
  1287. * parsing. Decoding slices is not possible in codec init
  1288. * with frame-mt */
  1289. if (parse_extradata && HAVE_THREADS &&
  1290. (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
  1291. (hx->nal_unit_type != NAL_PPS &&
  1292. hx->nal_unit_type != NAL_SPS)) {
  1293. if (hx->nal_unit_type < NAL_AUD ||
  1294. hx->nal_unit_type > NAL_AUXILIARY_SLICE)
  1295. av_log(avctx, AV_LOG_INFO,
  1296. "Ignoring NAL unit %d during extradata parsing\n",
  1297. hx->nal_unit_type);
  1298. hx->nal_unit_type = NAL_FF_IGNORE;
  1299. }
  1300. err = 0;
  1301. switch (hx->nal_unit_type) {
  1302. case NAL_IDR_SLICE:
  1303. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1304. av_log(h->avctx, AV_LOG_ERROR,
  1305. "Invalid mix of idr and non-idr slices\n");
  1306. ret = -1;
  1307. goto end;
  1308. }
  1309. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1310. case NAL_SLICE:
  1311. init_get_bits(&hx->gb, ptr, bit_length);
  1312. hx->intra_gb_ptr =
  1313. hx->inter_gb_ptr = &hx->gb;
  1314. hx->data_partitioning = 0;
  1315. if ((err = ff_h264_decode_slice_header(hx, h)))
  1316. break;
  1317. if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
  1318. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1319. ((1 << h->sps.log2_max_frame_num) - 1);
  1320. }
  1321. h->cur_pic_ptr->f.key_frame |=
  1322. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  1323. (h->sei_recovery_frame_cnt >= 0);
  1324. if (hx->nal_unit_type == NAL_IDR_SLICE ||
  1325. h->recovery_frame == h->frame_num) {
  1326. h->recovery_frame = -1;
  1327. h->cur_pic_ptr->recovered = 1;
  1328. }
  1329. // If we have an IDR, all frames after it in decoded order are
  1330. // "recovered".
  1331. if (hx->nal_unit_type == NAL_IDR_SLICE)
  1332. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1333. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1334. if (h->current_slice == 1) {
  1335. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  1336. decode_postinit(h, nal_index >= nals_needed);
  1337. if (h->avctx->hwaccel &&
  1338. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  1339. return ret;
  1340. }
  1341. if (hx->redundant_pic_count == 0 &&
  1342. (avctx->skip_frame < AVDISCARD_NONREF ||
  1343. hx->nal_ref_idc) &&
  1344. (avctx->skip_frame < AVDISCARD_BIDIR ||
  1345. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  1346. (avctx->skip_frame < AVDISCARD_NONKEY ||
  1347. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  1348. avctx->skip_frame < AVDISCARD_ALL) {
  1349. if (avctx->hwaccel) {
  1350. ret = avctx->hwaccel->decode_slice(avctx,
  1351. &buf[buf_index - consumed],
  1352. consumed);
  1353. if (ret < 0)
  1354. return ret;
  1355. } else
  1356. context_count++;
  1357. }
  1358. break;
  1359. case NAL_DPA:
  1360. if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
  1361. av_log(h->avctx, AV_LOG_ERROR,
  1362. "Decoding in chunks is not supported for "
  1363. "partitioned slices.\n");
  1364. return AVERROR(ENOSYS);
  1365. }
  1366. init_get_bits(&hx->gb, ptr, bit_length);
  1367. hx->intra_gb_ptr =
  1368. hx->inter_gb_ptr = NULL;
  1369. if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
  1370. /* make sure data_partitioning is cleared if it was set
  1371. * before, so we don't try decoding a slice without a valid
  1372. * slice header later */
  1373. h->data_partitioning = 0;
  1374. break;
  1375. }
  1376. hx->data_partitioning = 1;
  1377. break;
  1378. case NAL_DPB:
  1379. init_get_bits(&hx->intra_gb, ptr, bit_length);
  1380. hx->intra_gb_ptr = &hx->intra_gb;
  1381. break;
  1382. case NAL_DPC:
  1383. init_get_bits(&hx->inter_gb, ptr, bit_length);
  1384. hx->inter_gb_ptr = &hx->inter_gb;
  1385. if (hx->redundant_pic_count == 0 &&
  1386. hx->intra_gb_ptr &&
  1387. hx->data_partitioning &&
  1388. h->cur_pic_ptr && h->context_initialized &&
  1389. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  1390. (avctx->skip_frame < AVDISCARD_BIDIR ||
  1391. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  1392. (avctx->skip_frame < AVDISCARD_NONKEY ||
  1393. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  1394. avctx->skip_frame < AVDISCARD_ALL)
  1395. context_count++;
  1396. break;
  1397. case NAL_SEI:
  1398. init_get_bits(&h->gb, ptr, bit_length);
  1399. ret = ff_h264_decode_sei(h);
  1400. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1401. goto end;
  1402. break;
  1403. case NAL_SPS:
  1404. init_get_bits(&h->gb, ptr, bit_length);
  1405. ret = ff_h264_decode_seq_parameter_set(h);
  1406. if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
  1407. av_log(h->avctx, AV_LOG_DEBUG,
  1408. "SPS decoding failure, trying again with the complete NAL\n");
  1409. init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
  1410. 8 * (nalsize - 1));
  1411. ff_h264_decode_seq_parameter_set(h);
  1412. }
  1413. ret = ff_h264_set_parameter_from_sps(h);
  1414. if (ret < 0)
  1415. goto end;
  1416. break;
  1417. case NAL_PPS:
  1418. init_get_bits(&h->gb, ptr, bit_length);
  1419. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1420. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1421. goto end;
  1422. break;
  1423. case NAL_AUD:
  1424. case NAL_END_SEQUENCE:
  1425. case NAL_END_STREAM:
  1426. case NAL_FILLER_DATA:
  1427. case NAL_SPS_EXT:
  1428. case NAL_AUXILIARY_SLICE:
  1429. break;
  1430. case NAL_FF_IGNORE:
  1431. break;
  1432. default:
  1433. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1434. hx->nal_unit_type, bit_length);
  1435. }
  1436. if (context_count == h->max_contexts) {
  1437. ret = ff_h264_execute_decode_slices(h, context_count);
  1438. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1439. goto end;
  1440. context_count = 0;
  1441. }
  1442. if (err < 0) {
  1443. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1444. h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
  1445. } else if (err == 1) {
  1446. /* Slice could not be decoded in parallel mode, copy down
  1447. * NAL unit stuff to context 0 and restart. Note that
  1448. * rbsp_buffer is not transferred, but since we no longer
  1449. * run in parallel mode this should not be an issue. */
  1450. h->nal_unit_type = hx->nal_unit_type;
  1451. h->nal_ref_idc = hx->nal_ref_idc;
  1452. hx = h;
  1453. goto again;
  1454. }
  1455. }
  1456. }
  1457. if (context_count) {
  1458. ret = ff_h264_execute_decode_slices(h, context_count);
  1459. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1460. goto end;
  1461. }
  1462. end:
  1463. /* clean up */
  1464. if (h->cur_pic_ptr && !h->droppable) {
  1465. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1466. h->picture_structure == PICT_BOTTOM_FIELD);
  1467. }
  1468. return (ret < 0) ? ret : buf_index;
  1469. }
  1470. /**
  1471. * Return the number of bytes consumed for building the current frame.
  1472. */
  1473. static int get_consumed_bytes(int pos, int buf_size)
  1474. {
  1475. if (pos == 0)
  1476. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  1477. if (pos + 10 > buf_size)
  1478. pos = buf_size; // oops ;)
  1479. return pos;
  1480. }
  1481. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  1482. {
  1483. int i;
  1484. int ret = av_frame_ref(dst, src);
  1485. if (ret < 0)
  1486. return ret;
  1487. if (!h->sps.crop)
  1488. return 0;
  1489. for (i = 0; i < 3; i++) {
  1490. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  1491. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  1492. int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
  1493. (h->sps.crop_top >> vshift) * dst->linesize[i];
  1494. dst->data[i] += off;
  1495. }
  1496. return 0;
  1497. }
  1498. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1499. int *got_frame, AVPacket *avpkt)
  1500. {
  1501. const uint8_t *buf = avpkt->data;
  1502. int buf_size = avpkt->size;
  1503. H264Context *h = avctx->priv_data;
  1504. AVFrame *pict = data;
  1505. int buf_index = 0;
  1506. int ret;
  1507. h->flags = avctx->flags;
  1508. /* reset data partitioning here, to ensure GetBitContexts from previous
  1509. * packets do not get used. */
  1510. h->data_partitioning = 0;
  1511. /* end of stream, output what is still in the buffers */
  1512. out:
  1513. if (buf_size == 0) {
  1514. H264Picture *out;
  1515. int i, out_idx;
  1516. h->cur_pic_ptr = NULL;
  1517. // FIXME factorize this with the output code below
  1518. out = h->delayed_pic[0];
  1519. out_idx = 0;
  1520. for (i = 1;
  1521. h->delayed_pic[i] &&
  1522. !h->delayed_pic[i]->f.key_frame &&
  1523. !h->delayed_pic[i]->mmco_reset;
  1524. i++)
  1525. if (h->delayed_pic[i]->poc < out->poc) {
  1526. out = h->delayed_pic[i];
  1527. out_idx = i;
  1528. }
  1529. for (i = out_idx; h->delayed_pic[i]; i++)
  1530. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1531. if (out) {
  1532. ret = output_frame(h, pict, &out->f);
  1533. if (ret < 0)
  1534. return ret;
  1535. *got_frame = 1;
  1536. }
  1537. return buf_index;
  1538. }
  1539. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1540. if (buf_index < 0)
  1541. return AVERROR_INVALIDDATA;
  1542. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1543. buf_size = 0;
  1544. goto out;
  1545. }
  1546. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1547. if (avctx->skip_frame >= AVDISCARD_NONREF)
  1548. return 0;
  1549. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1550. return AVERROR_INVALIDDATA;
  1551. }
  1552. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  1553. (h->mb_y >= h->mb_height && h->mb_height)) {
  1554. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  1555. decode_postinit(h, 1);
  1556. ff_h264_field_end(h, 0);
  1557. *got_frame = 0;
  1558. if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
  1559. h->next_output_pic->recovered)) {
  1560. if (!h->next_output_pic->recovered)
  1561. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  1562. ret = output_frame(h, pict, &h->next_output_pic->f);
  1563. if (ret < 0)
  1564. return ret;
  1565. *got_frame = 1;
  1566. }
  1567. }
  1568. assert(pict->buf[0] || !*got_frame);
  1569. return get_consumed_bytes(buf_index, buf_size);
  1570. }
  1571. av_cold void ff_h264_free_context(H264Context *h)
  1572. {
  1573. int i;
  1574. ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
  1575. for (i = 0; i < MAX_SPS_COUNT; i++)
  1576. av_freep(h->sps_buffers + i);
  1577. for (i = 0; i < MAX_PPS_COUNT; i++)
  1578. av_freep(h->pps_buffers + i);
  1579. }
  1580. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1581. {
  1582. H264Context *h = avctx->priv_data;
  1583. ff_h264_free_context(h);
  1584. ff_h264_unref_picture(h, &h->cur_pic);
  1585. return 0;
  1586. }
  1587. static const AVProfile profiles[] = {
  1588. { FF_PROFILE_H264_BASELINE, "Baseline" },
  1589. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  1590. { FF_PROFILE_H264_MAIN, "Main" },
  1591. { FF_PROFILE_H264_EXTENDED, "Extended" },
  1592. { FF_PROFILE_H264_HIGH, "High" },
  1593. { FF_PROFILE_H264_HIGH_10, "High 10" },
  1594. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  1595. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  1596. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  1597. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  1598. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  1599. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  1600. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  1601. { FF_PROFILE_UNKNOWN },
  1602. };
  1603. AVCodec ff_h264_decoder = {
  1604. .name = "h264",
  1605. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1606. .type = AVMEDIA_TYPE_VIDEO,
  1607. .id = AV_CODEC_ID_H264,
  1608. .priv_data_size = sizeof(H264Context),
  1609. .init = ff_h264_decode_init,
  1610. .close = h264_decode_end,
  1611. .decode = h264_decode_frame,
  1612. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  1613. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  1614. CODEC_CAP_FRAME_THREADS,
  1615. .flush = flush_dpb,
  1616. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1617. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1618. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1619. };