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.

2031 lines
69KB

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