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.

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