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.

2018 lines
68KB

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