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.

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