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.

1448 lines
50KB

  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 / MPEG-4 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 "bytestream.h"
  35. #include "cabac.h"
  36. #include "cabac_functions.h"
  37. #include "error_resilience.h"
  38. #include "avcodec.h"
  39. #include "h264.h"
  40. #include "h2645_parse.h"
  41. #include "h264data.h"
  42. #include "h264chroma.h"
  43. #include "h264_mvpred.h"
  44. #include "golomb.h"
  45. #include "mathops.h"
  46. #include "me_cmp.h"
  47. #include "mpegutils.h"
  48. #include "profiles.h"
  49. #include "rectangle.h"
  50. #include "thread.h"
  51. #include "vdpau_compat.h"
  52. static int h264_decode_end(AVCodecContext *avctx);
  53. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  54. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  55. {
  56. H264Context *h = avctx->priv_data;
  57. return h && h->ps.sps ? h->ps.sps->num_reorder_frames : 0;
  58. }
  59. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  60. int (*mv)[2][4][2],
  61. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  62. {
  63. H264Context *h = opaque;
  64. H264SliceContext *sl = &h->slice_ctx[0];
  65. sl->mb_x = mb_x;
  66. sl->mb_y = mb_y;
  67. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  68. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  69. av_assert1(ref >= 0);
  70. /* FIXME: It is possible albeit uncommon that slice references
  71. * differ between slices. We take the easy approach and ignore
  72. * it for now. If this turns out to have any relevance in
  73. * practice then correct remapping should be added. */
  74. if (ref >= sl->ref_count[0])
  75. ref = 0;
  76. if (!sl->ref_list[0][ref].data[0]) {
  77. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  78. ref = 0;
  79. }
  80. if ((sl->ref_list[0][ref].reference&3) != 3) {
  81. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  82. return;
  83. }
  84. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  85. 2, 2, 2, ref, 1);
  86. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  87. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  88. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  89. sl->mb_mbaff =
  90. sl->mb_field_decoding_flag = 0;
  91. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  92. }
  93. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  94. int y, int height)
  95. {
  96. AVCodecContext *avctx = h->avctx;
  97. const AVFrame *src = h->cur_pic.f;
  98. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  99. int vshift = desc->log2_chroma_h;
  100. const int field_pic = h->picture_structure != PICT_FRAME;
  101. if (field_pic) {
  102. height <<= 1;
  103. y <<= 1;
  104. }
  105. height = FFMIN(height, avctx->height - y);
  106. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  107. return;
  108. if (avctx->draw_horiz_band) {
  109. int offset[AV_NUM_DATA_POINTERS];
  110. int i;
  111. offset[0] = y * src->linesize[0];
  112. offset[1] =
  113. offset[2] = (y >> vshift) * src->linesize[1];
  114. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  115. offset[i] = 0;
  116. emms_c();
  117. avctx->draw_horiz_band(avctx, src, offset,
  118. y, h->picture_structure, height);
  119. }
  120. }
  121. void ff_h264_free_tables(H264Context *h)
  122. {
  123. int i;
  124. av_freep(&h->intra4x4_pred_mode);
  125. av_freep(&h->chroma_pred_mode_table);
  126. av_freep(&h->cbp_table);
  127. av_freep(&h->mvd_table[0]);
  128. av_freep(&h->mvd_table[1]);
  129. av_freep(&h->direct_table);
  130. av_freep(&h->non_zero_count);
  131. av_freep(&h->slice_table_base);
  132. h->slice_table = NULL;
  133. av_freep(&h->list_counts);
  134. av_freep(&h->mb2b_xy);
  135. av_freep(&h->mb2br_xy);
  136. av_buffer_pool_uninit(&h->qscale_table_pool);
  137. av_buffer_pool_uninit(&h->mb_type_pool);
  138. av_buffer_pool_uninit(&h->motion_val_pool);
  139. av_buffer_pool_uninit(&h->ref_index_pool);
  140. for (i = 0; i < h->nb_slice_ctx; i++) {
  141. H264SliceContext *sl = &h->slice_ctx[i];
  142. av_freep(&sl->dc_val_base);
  143. av_freep(&sl->er.mb_index2xy);
  144. av_freep(&sl->er.error_status_table);
  145. av_freep(&sl->er.er_temp_buffer);
  146. av_freep(&sl->bipred_scratchpad);
  147. av_freep(&sl->edge_emu_buffer);
  148. av_freep(&sl->top_borders[0]);
  149. av_freep(&sl->top_borders[1]);
  150. sl->bipred_scratchpad_allocated = 0;
  151. sl->edge_emu_buffer_allocated = 0;
  152. sl->top_borders_allocated[0] = 0;
  153. sl->top_borders_allocated[1] = 0;
  154. }
  155. }
  156. int ff_h264_alloc_tables(H264Context *h)
  157. {
  158. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  159. const int row_mb_num = 2*h->mb_stride*FFMAX(h->nb_slice_ctx, 1);
  160. int x, y;
  161. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  162. row_mb_num, 8 * sizeof(uint8_t), fail)
  163. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  164. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  165. big_mb_num * 48 * sizeof(uint8_t), fail)
  166. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  167. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  168. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  169. big_mb_num * sizeof(uint16_t), fail)
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  171. big_mb_num * sizeof(uint8_t), fail)
  172. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
  173. row_mb_num, 16 * sizeof(uint8_t), fail);
  174. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
  175. row_mb_num, 16 * sizeof(uint8_t), fail);
  176. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  177. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  178. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  179. 4 * big_mb_num * sizeof(uint8_t), fail);
  180. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  181. big_mb_num * sizeof(uint8_t), fail)
  182. memset(h->slice_table_base, -1,
  183. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  184. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  185. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  186. big_mb_num * sizeof(uint32_t), fail);
  187. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  188. big_mb_num * sizeof(uint32_t), fail);
  189. for (y = 0; y < h->mb_height; y++)
  190. for (x = 0; x < h->mb_width; x++) {
  191. const int mb_xy = x + y * h->mb_stride;
  192. const int b_xy = 4 * x + 4 * y * h->b_stride;
  193. h->mb2b_xy[mb_xy] = b_xy;
  194. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  195. }
  196. return 0;
  197. fail:
  198. ff_h264_free_tables(h);
  199. return AVERROR(ENOMEM);
  200. }
  201. /**
  202. * Init context
  203. * Allocate buffers which are not shared amongst multiple threads.
  204. */
  205. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  206. {
  207. ERContext *er = &sl->er;
  208. int mb_array_size = h->mb_height * h->mb_stride;
  209. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  210. int c_size = h->mb_stride * (h->mb_height + 1);
  211. int yc_size = y_size + 2 * c_size;
  212. int x, y, i;
  213. sl->ref_cache[0][scan8[5] + 1] =
  214. sl->ref_cache[0][scan8[7] + 1] =
  215. sl->ref_cache[0][scan8[13] + 1] =
  216. sl->ref_cache[1][scan8[5] + 1] =
  217. sl->ref_cache[1][scan8[7] + 1] =
  218. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  219. if (sl != h->slice_ctx) {
  220. memset(er, 0, sizeof(*er));
  221. } else
  222. if (CONFIG_ERROR_RESILIENCE) {
  223. /* init ER */
  224. er->avctx = h->avctx;
  225. er->decode_mb = h264_er_decode_mb;
  226. er->opaque = h;
  227. er->quarter_sample = 1;
  228. er->mb_num = h->mb_num;
  229. er->mb_width = h->mb_width;
  230. er->mb_height = h->mb_height;
  231. er->mb_stride = h->mb_stride;
  232. er->b8_stride = h->mb_width * 2 + 1;
  233. // error resilience code looks cleaner with this
  234. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  235. (h->mb_num + 1) * sizeof(int), fail);
  236. for (y = 0; y < h->mb_height; y++)
  237. for (x = 0; x < h->mb_width; x++)
  238. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  239. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  240. h->mb_stride + h->mb_width;
  241. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  242. mb_array_size * sizeof(uint8_t), fail);
  243. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  244. h->mb_height * h->mb_stride, fail);
  245. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  246. yc_size * sizeof(int16_t), fail);
  247. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  248. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  249. er->dc_val[2] = er->dc_val[1] + c_size;
  250. for (i = 0; i < yc_size; i++)
  251. sl->dc_val_base[i] = 1024;
  252. }
  253. return 0;
  254. fail:
  255. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  256. }
  257. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  258. {
  259. int i;
  260. h->avctx = avctx;
  261. h->backup_width = -1;
  262. h->backup_height = -1;
  263. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  264. h->current_sps_id = -1;
  265. h->cur_chroma_format_idc = -1;
  266. h->picture_structure = PICT_FRAME;
  267. h->workaround_bugs = avctx->workaround_bugs;
  268. h->flags = avctx->flags;
  269. h->poc.prev_poc_msb = 1 << 16;
  270. h->recovery_frame = -1;
  271. h->frame_recovered = 0;
  272. h->poc.prev_frame_num = -1;
  273. h->sei.frame_packing.frame_packing_arrangement_cancel_flag = -1;
  274. h->sei.unregistered.x264_build = -1;
  275. h->next_outputed_poc = INT_MIN;
  276. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  277. h->last_pocs[i] = INT_MIN;
  278. ff_h264_sei_uninit(&h->sei);
  279. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  280. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  281. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  282. if (!h->slice_ctx) {
  283. h->nb_slice_ctx = 0;
  284. return AVERROR(ENOMEM);
  285. }
  286. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  287. h->DPB[i].f = av_frame_alloc();
  288. if (!h->DPB[i].f)
  289. return AVERROR(ENOMEM);
  290. }
  291. h->cur_pic.f = av_frame_alloc();
  292. if (!h->cur_pic.f)
  293. return AVERROR(ENOMEM);
  294. h->last_pic_for_ec.f = av_frame_alloc();
  295. if (!h->last_pic_for_ec.f)
  296. return AVERROR(ENOMEM);
  297. for (i = 0; i < h->nb_slice_ctx; i++)
  298. h->slice_ctx[i].h264 = h;
  299. return 0;
  300. }
  301. static av_cold int h264_decode_end(AVCodecContext *avctx)
  302. {
  303. H264Context *h = avctx->priv_data;
  304. int i;
  305. ff_h264_remove_all_refs(h);
  306. ff_h264_free_tables(h);
  307. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  308. ff_h264_unref_picture(h, &h->DPB[i]);
  309. av_frame_free(&h->DPB[i].f);
  310. }
  311. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  312. h->cur_pic_ptr = NULL;
  313. av_freep(&h->slice_ctx);
  314. h->nb_slice_ctx = 0;
  315. ff_h264_sei_uninit(&h->sei);
  316. ff_h264_ps_uninit(&h->ps);
  317. ff_h2645_packet_uninit(&h->pkt);
  318. ff_h264_unref_picture(h, &h->cur_pic);
  319. av_frame_free(&h->cur_pic.f);
  320. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  321. av_frame_free(&h->last_pic_for_ec.f);
  322. return 0;
  323. }
  324. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  325. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  326. {
  327. H264Context *h = avctx->priv_data;
  328. int ret;
  329. ret = h264_init_context(avctx, h);
  330. if (ret < 0)
  331. return ret;
  332. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  333. if (ret != 0) {
  334. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  335. return AVERROR_UNKNOWN;
  336. }
  337. if (avctx->codec_id == AV_CODEC_ID_H264) {
  338. if (avctx->ticks_per_frame == 1) {
  339. if(h->avctx->time_base.den < INT_MAX/2) {
  340. h->avctx->time_base.den *= 2;
  341. } else
  342. h->avctx->time_base.num /= 2;
  343. }
  344. avctx->ticks_per_frame = 2;
  345. }
  346. if (avctx->extradata_size > 0 && avctx->extradata) {
  347. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  348. &h->ps, &h->is_avc, &h->nal_length_size,
  349. avctx->err_recognition, avctx);
  350. if (ret < 0) {
  351. h264_decode_end(avctx);
  352. return ret;
  353. }
  354. }
  355. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  356. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  357. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  358. }
  359. avctx->internal->allocate_progress = 1;
  360. ff_h264_flush_change(h);
  361. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  362. h->enable_er = 0;
  363. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  364. av_log(avctx, AV_LOG_WARNING,
  365. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  366. "Use it at your own risk\n");
  367. }
  368. return 0;
  369. }
  370. #if HAVE_THREADS
  371. static int decode_init_thread_copy(AVCodecContext *avctx)
  372. {
  373. H264Context *h = avctx->priv_data;
  374. int ret;
  375. if (!avctx->internal->is_copy)
  376. return 0;
  377. memset(h, 0, sizeof(*h));
  378. ret = h264_init_context(avctx, h);
  379. if (ret < 0)
  380. return ret;
  381. h->context_initialized = 0;
  382. return 0;
  383. }
  384. #endif
  385. /**
  386. * Run setup operations that must be run after slice header decoding.
  387. * This includes finding the next displayed frame.
  388. *
  389. * @param h h264 master context
  390. * @param setup_finished enough NALs have been read that we can call
  391. * ff_thread_finish_setup()
  392. */
  393. static void decode_postinit(H264Context *h, int setup_finished)
  394. {
  395. const SPS *sps = h->ps.sps;
  396. H264Picture *out = h->cur_pic_ptr;
  397. H264Picture *cur = h->cur_pic_ptr;
  398. int i, pics, out_of_order, out_idx;
  399. if (h->next_output_pic)
  400. return;
  401. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  402. /* FIXME: if we have two PAFF fields in one packet, we can't start
  403. * the next thread here. If we have one field per packet, we can.
  404. * The check in decode_nal_units() is not good enough to find this
  405. * yet, so we assume the worst for now. */
  406. // if (setup_finished)
  407. // ff_thread_finish_setup(h->avctx);
  408. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  409. return;
  410. if (h->avctx->hwaccel || h->missing_fields <=1)
  411. return;
  412. }
  413. cur->f->interlaced_frame = 0;
  414. cur->f->repeat_pict = 0;
  415. /* Signal interlacing information externally. */
  416. /* Prioritize picture timing SEI information over used
  417. * decoding process if it exists. */
  418. if (sps->pic_struct_present_flag) {
  419. H264SEIPictureTiming *pt = &h->sei.picture_timing;
  420. switch (pt->pic_struct) {
  421. case SEI_PIC_STRUCT_FRAME:
  422. break;
  423. case SEI_PIC_STRUCT_TOP_FIELD:
  424. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  425. cur->f->interlaced_frame = 1;
  426. break;
  427. case SEI_PIC_STRUCT_TOP_BOTTOM:
  428. case SEI_PIC_STRUCT_BOTTOM_TOP:
  429. if (FIELD_OR_MBAFF_PICTURE(h))
  430. cur->f->interlaced_frame = 1;
  431. else
  432. // try to flag soft telecine progressive
  433. cur->f->interlaced_frame = h->prev_interlaced_frame;
  434. break;
  435. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  436. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  437. /* Signal the possibility of telecined film externally
  438. * (pic_struct 5,6). From these hints, let the applications
  439. * decide if they apply deinterlacing. */
  440. cur->f->repeat_pict = 1;
  441. break;
  442. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  443. cur->f->repeat_pict = 2;
  444. break;
  445. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  446. cur->f->repeat_pict = 4;
  447. break;
  448. }
  449. if ((pt->ct_type & 3) &&
  450. pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  451. cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
  452. } else {
  453. /* Derive interlacing flag from used decoding process. */
  454. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  455. }
  456. h->prev_interlaced_frame = cur->f->interlaced_frame;
  457. if (cur->field_poc[0] != cur->field_poc[1]) {
  458. /* Derive top_field_first from field pocs. */
  459. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  460. } else {
  461. if (sps->pic_struct_present_flag) {
  462. /* Use picture timing SEI information. Even if it is a
  463. * information of a past frame, better than nothing. */
  464. if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  465. h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  466. cur->f->top_field_first = 1;
  467. else
  468. cur->f->top_field_first = 0;
  469. } else if (cur->f->interlaced_frame) {
  470. /* Default to top field first when pic_struct_present_flag
  471. * is not set but interlaced frame detected */
  472. cur->f->top_field_first = 1;
  473. } else {
  474. /* Most likely progressive */
  475. cur->f->top_field_first = 0;
  476. }
  477. }
  478. if (h->sei.frame_packing.present &&
  479. h->sei.frame_packing.frame_packing_arrangement_type <= 6 &&
  480. h->sei.frame_packing.content_interpretation_type > 0 &&
  481. h->sei.frame_packing.content_interpretation_type < 3) {
  482. H264SEIFramePacking *fp = &h->sei.frame_packing;
  483. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  484. if (stereo) {
  485. switch (fp->frame_packing_arrangement_type) {
  486. case 0:
  487. stereo->type = AV_STEREO3D_CHECKERBOARD;
  488. break;
  489. case 1:
  490. stereo->type = AV_STEREO3D_COLUMNS;
  491. break;
  492. case 2:
  493. stereo->type = AV_STEREO3D_LINES;
  494. break;
  495. case 3:
  496. if (fp->quincunx_sampling_flag)
  497. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  498. else
  499. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  500. break;
  501. case 4:
  502. stereo->type = AV_STEREO3D_TOPBOTTOM;
  503. break;
  504. case 5:
  505. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  506. break;
  507. case 6:
  508. stereo->type = AV_STEREO3D_2D;
  509. break;
  510. }
  511. if (fp->content_interpretation_type == 2)
  512. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  513. }
  514. }
  515. if (h->sei.display_orientation.present &&
  516. (h->sei.display_orientation.anticlockwise_rotation ||
  517. h->sei.display_orientation.hflip ||
  518. h->sei.display_orientation.vflip)) {
  519. H264SEIDisplayOrientation *o = &h->sei.display_orientation;
  520. double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
  521. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  522. AV_FRAME_DATA_DISPLAYMATRIX,
  523. sizeof(int32_t) * 9);
  524. if (rotation) {
  525. av_display_rotation_set((int32_t *)rotation->data, angle);
  526. av_display_matrix_flip((int32_t *)rotation->data,
  527. o->hflip, o->vflip);
  528. }
  529. }
  530. if (h->sei.afd.present) {
  531. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  532. sizeof(uint8_t));
  533. if (sd) {
  534. *sd->data = h->sei.afd.active_format_description;
  535. h->sei.afd.present = 0;
  536. }
  537. }
  538. if (h->sei.a53_caption.a53_caption) {
  539. H264SEIA53Caption *a53 = &h->sei.a53_caption;
  540. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  541. AV_FRAME_DATA_A53_CC,
  542. a53->a53_caption_size);
  543. if (sd)
  544. memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
  545. av_freep(&a53->a53_caption);
  546. a53->a53_caption_size = 0;
  547. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  548. }
  549. cur->mmco_reset = h->mmco_reset;
  550. h->mmco_reset = 0;
  551. // FIXME do something with unavailable reference frames
  552. /* Sort B-frames into display order */
  553. if (sps->bitstream_restriction_flag ||
  554. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  555. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  556. }
  557. for (i = 0; 1; i++) {
  558. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  559. if(i)
  560. h->last_pocs[i-1] = cur->poc;
  561. break;
  562. } else if(i) {
  563. h->last_pocs[i-1]= h->last_pocs[i];
  564. }
  565. }
  566. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  567. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  568. || (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))
  569. out_of_order = FFMAX(out_of_order, 1);
  570. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  571. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  572. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  573. h->last_pocs[i] = INT_MIN;
  574. h->last_pocs[0] = cur->poc;
  575. cur->mmco_reset = 1;
  576. } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
  577. av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
  578. h->avctx->has_b_frames = out_of_order;
  579. }
  580. pics = 0;
  581. while (h->delayed_pic[pics])
  582. pics++;
  583. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  584. h->delayed_pic[pics++] = cur;
  585. if (cur->reference == 0)
  586. cur->reference = DELAYED_PIC_REF;
  587. out = h->delayed_pic[0];
  588. out_idx = 0;
  589. for (i = 1; h->delayed_pic[i] &&
  590. !h->delayed_pic[i]->f->key_frame &&
  591. !h->delayed_pic[i]->mmco_reset;
  592. i++)
  593. if (h->delayed_pic[i]->poc < out->poc) {
  594. out = h->delayed_pic[i];
  595. out_idx = i;
  596. }
  597. if (h->avctx->has_b_frames == 0 &&
  598. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  599. h->next_outputed_poc = INT_MIN;
  600. out_of_order = out->poc < h->next_outputed_poc;
  601. if (out_of_order || pics > h->avctx->has_b_frames) {
  602. out->reference &= ~DELAYED_PIC_REF;
  603. for (i = out_idx; h->delayed_pic[i]; i++)
  604. h->delayed_pic[i] = h->delayed_pic[i + 1];
  605. }
  606. if (!out_of_order && pics > h->avctx->has_b_frames) {
  607. h->next_output_pic = out;
  608. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  609. h->next_outputed_poc = INT_MIN;
  610. } else
  611. h->next_outputed_poc = out->poc;
  612. } else {
  613. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  614. }
  615. if (h->next_output_pic) {
  616. if (h->next_output_pic->recovered) {
  617. // We have reached an recovery point and all frames after it in
  618. // display order are "recovered".
  619. h->frame_recovered |= FRAME_RECOVERED_SEI;
  620. }
  621. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  622. }
  623. if (setup_finished && !h->avctx->hwaccel) {
  624. ff_thread_finish_setup(h->avctx);
  625. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  626. h->setup_finished = 1;
  627. }
  628. }
  629. /**
  630. * instantaneous decoder refresh.
  631. */
  632. static void idr(H264Context *h)
  633. {
  634. int i;
  635. ff_h264_remove_all_refs(h);
  636. h->poc.prev_frame_num =
  637. h->poc.prev_frame_num_offset = 0;
  638. h->poc.prev_poc_msb = 1<<16;
  639. h->poc.prev_poc_lsb = 0;
  640. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  641. h->last_pocs[i] = INT_MIN;
  642. }
  643. /* forget old pics after a seek */
  644. void ff_h264_flush_change(H264Context *h)
  645. {
  646. int i, j;
  647. h->next_outputed_poc = INT_MIN;
  648. h->prev_interlaced_frame = 1;
  649. idr(h);
  650. h->poc.prev_frame_num = -1;
  651. if (h->cur_pic_ptr) {
  652. h->cur_pic_ptr->reference = 0;
  653. for (j=i=0; h->delayed_pic[i]; i++)
  654. if (h->delayed_pic[i] != h->cur_pic_ptr)
  655. h->delayed_pic[j++] = h->delayed_pic[i];
  656. h->delayed_pic[j] = NULL;
  657. }
  658. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  659. h->first_field = 0;
  660. ff_h264_sei_uninit(&h->sei);
  661. h->recovery_frame = -1;
  662. h->frame_recovered = 0;
  663. h->current_slice = 0;
  664. h->mmco_reset = 1;
  665. for (i = 0; i < h->nb_slice_ctx; i++)
  666. h->slice_ctx[i].list_count = 0;
  667. }
  668. /* forget old pics after a seek */
  669. static void flush_dpb(AVCodecContext *avctx)
  670. {
  671. H264Context *h = avctx->priv_data;
  672. int i;
  673. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  674. ff_h264_flush_change(h);
  675. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  676. ff_h264_unref_picture(h, &h->DPB[i]);
  677. h->cur_pic_ptr = NULL;
  678. ff_h264_unref_picture(h, &h->cur_pic);
  679. h->mb_y = 0;
  680. ff_h264_free_tables(h);
  681. h->context_initialized = 0;
  682. }
  683. #if FF_API_CAP_VDPAU
  684. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  685. #endif
  686. static int get_last_needed_nal(H264Context *h)
  687. {
  688. int nals_needed = 0;
  689. int first_slice = 0;
  690. int i;
  691. int ret;
  692. for (i = 0; i < h->pkt.nb_nals; i++) {
  693. H2645NAL *nal = &h->pkt.nals[i];
  694. GetBitContext gb;
  695. /* packets can sometimes contain multiple PPS/SPS,
  696. * e.g. two PAFF field pictures in one packet, or a demuxer
  697. * which splits NALs strangely if so, when frame threading we
  698. * can't start the next thread until we've read all of them */
  699. switch (nal->type) {
  700. case NAL_SPS:
  701. case NAL_PPS:
  702. nals_needed = i;
  703. break;
  704. case NAL_DPA:
  705. case NAL_IDR_SLICE:
  706. case NAL_SLICE:
  707. ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
  708. if (ret < 0)
  709. return ret;
  710. if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
  711. !first_slice ||
  712. first_slice != nal->type)
  713. nals_needed = i;
  714. if (!first_slice)
  715. first_slice = nal->type;
  716. }
  717. }
  718. return nals_needed;
  719. }
  720. static void debug_green_metadata(const H264SEIGreenMetaData *gm, void *logctx)
  721. {
  722. av_log(logctx, AV_LOG_DEBUG, "Green Metadata Info SEI message\n");
  723. av_log(logctx, AV_LOG_DEBUG, " green_metadata_type: %d\n", gm->green_metadata_type);
  724. if (gm->green_metadata_type == 0) {
  725. av_log(logctx, AV_LOG_DEBUG, " green_metadata_period_type: %d\n", gm->period_type);
  726. if (gm->period_type == 2)
  727. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_seconds: %d\n", gm->num_seconds);
  728. else if (gm->period_type == 3)
  729. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_pictures: %d\n", gm->num_pictures);
  730. av_log(logctx, AV_LOG_DEBUG, " SEI GREEN Complexity Metrics: %f %f %f %f\n",
  731. (float)gm->percent_non_zero_macroblocks/255,
  732. (float)gm->percent_intra_coded_macroblocks/255,
  733. (float)gm->percent_six_tap_filtering/255,
  734. (float)gm->percent_alpha_point_deblocking_instance/255);
  735. } else if (gm->green_metadata_type == 1) {
  736. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_type: %d\n", gm->xsd_metric_type);
  737. if (gm->xsd_metric_type == 0)
  738. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_value: %f\n",
  739. (float)gm->xsd_metric_value/100);
  740. }
  741. }
  742. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  743. {
  744. AVCodecContext *const avctx = h->avctx;
  745. unsigned context_count = 0;
  746. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  747. int idr_cleared=0;
  748. int i, ret = 0;
  749. h->nal_unit_type= 0;
  750. h->max_contexts = h->nb_slice_ctx;
  751. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  752. h->current_slice = 0;
  753. if (!h->first_field)
  754. h->cur_pic_ptr = NULL;
  755. ff_h264_sei_uninit(&h->sei);
  756. }
  757. if (h->nal_length_size == 4) {
  758. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  759. h->is_avc = 0;
  760. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  761. h->is_avc = 1;
  762. }
  763. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  764. h->nal_length_size, avctx->codec_id);
  765. if (ret < 0) {
  766. av_log(avctx, AV_LOG_ERROR,
  767. "Error splitting the input into NAL units.\n");
  768. return ret;
  769. }
  770. if (avctx->active_thread_type & FF_THREAD_FRAME)
  771. nals_needed = get_last_needed_nal(h);
  772. if (nals_needed < 0)
  773. return nals_needed;
  774. for (i = 0; i < h->pkt.nb_nals; i++) {
  775. H2645NAL *nal = &h->pkt.nals[i];
  776. H264SliceContext *sl = &h->slice_ctx[context_count];
  777. int err;
  778. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  779. nal->ref_idc == 0 && nal->type != NAL_SEI)
  780. continue;
  781. again:
  782. // FIXME these should stop being context-global variables
  783. h->nal_ref_idc = nal->ref_idc;
  784. h->nal_unit_type = nal->type;
  785. err = 0;
  786. switch (nal->type) {
  787. case NAL_IDR_SLICE:
  788. if ((nal->data[1] & 0xFC) == 0x98) {
  789. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  790. h->next_outputed_poc = INT_MIN;
  791. ret = -1;
  792. goto end;
  793. }
  794. if (nal->type != NAL_IDR_SLICE) {
  795. av_log(h->avctx, AV_LOG_ERROR,
  796. "Invalid mix of idr and non-idr slices\n");
  797. ret = -1;
  798. goto end;
  799. }
  800. if(!idr_cleared) {
  801. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  802. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  803. ret = AVERROR_INVALIDDATA;
  804. goto end;
  805. }
  806. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  807. }
  808. idr_cleared = 1;
  809. h->has_recovery_point = 1;
  810. case NAL_SLICE:
  811. sl->gb = nal->gb;
  812. if ( nals_needed >= i
  813. || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
  814. h->au_pps_id = -1;
  815. if ((err = ff_h264_decode_slice_header(h, sl)))
  816. break;
  817. if (h->sei.recovery_point.recovery_frame_cnt >= 0) {
  818. const int sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  819. if (h->poc.frame_num != sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  820. h->valid_recovery_point = 1;
  821. if ( h->recovery_frame < 0
  822. || av_mod_uintp2(h->recovery_frame - h->poc.frame_num, h->ps.sps->log2_max_frame_num) > sei_recovery_frame_cnt) {
  823. h->recovery_frame = av_mod_uintp2(h->poc.frame_num + sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
  824. if (!h->valid_recovery_point)
  825. h->recovery_frame = h->poc.frame_num;
  826. }
  827. }
  828. h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
  829. if (nal->type == NAL_IDR_SLICE ||
  830. (h->recovery_frame == h->poc.frame_num && nal->ref_idc)) {
  831. h->recovery_frame = -1;
  832. h->cur_pic_ptr->recovered = 1;
  833. }
  834. // If we have an IDR, all frames after it in decoded order are
  835. // "recovered".
  836. if (nal->type == NAL_IDR_SLICE)
  837. h->frame_recovered |= FRAME_RECOVERED_IDR;
  838. #if 1
  839. h->cur_pic_ptr->recovered |= h->frame_recovered;
  840. #else
  841. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  842. #endif
  843. if (h->current_slice == 1) {
  844. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  845. decode_postinit(h, i >= nals_needed);
  846. if (h->avctx->hwaccel &&
  847. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  848. goto end;
  849. #if FF_API_CAP_VDPAU
  850. if (CONFIG_H264_VDPAU_DECODER &&
  851. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
  852. ff_vdpau_h264_picture_start(h);
  853. #endif
  854. }
  855. if (sl->redundant_pic_count == 0) {
  856. if (avctx->hwaccel) {
  857. ret = avctx->hwaccel->decode_slice(avctx,
  858. nal->raw_data,
  859. nal->raw_size);
  860. if (ret < 0)
  861. goto end;
  862. #if FF_API_CAP_VDPAU
  863. } else if (CONFIG_H264_VDPAU_DECODER &&
  864. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
  865. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  866. start_code,
  867. sizeof(start_code));
  868. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  869. nal->raw_data,
  870. nal->raw_size);
  871. #endif
  872. } else
  873. context_count++;
  874. }
  875. break;
  876. case NAL_DPA:
  877. case NAL_DPB:
  878. case NAL_DPC:
  879. avpriv_request_sample(avctx, "data partitioning");
  880. break;
  881. case NAL_SEI:
  882. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  883. h->has_recovery_point = h->has_recovery_point || h->sei.recovery_point.recovery_frame_cnt != -1;
  884. if (avctx->debug & FF_DEBUG_GREEN_MD)
  885. debug_green_metadata(&h->sei.green_metadata, h->avctx);
  886. #if FF_API_AFD
  887. FF_DISABLE_DEPRECATION_WARNINGS
  888. h->avctx->dtg_active_format = h->sei.afd.active_format_description;
  889. FF_ENABLE_DEPRECATION_WARNINGS
  890. #endif /* FF_API_AFD */
  891. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  892. goto end;
  893. break;
  894. case NAL_SPS: {
  895. GetBitContext tmp_gb = nal->gb;
  896. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  897. break;
  898. av_log(h->avctx, AV_LOG_DEBUG,
  899. "SPS decoding failure, trying again with the complete NAL\n");
  900. init_get_bits8(&tmp_gb, nal->raw_data + 1, nal->raw_size - 1);
  901. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  902. break;
  903. ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps, 1);
  904. break;
  905. }
  906. case NAL_PPS:
  907. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  908. nal->size_bits);
  909. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  910. goto end;
  911. break;
  912. case NAL_AUD:
  913. case NAL_END_SEQUENCE:
  914. case NAL_END_STREAM:
  915. case NAL_FILLER_DATA:
  916. case NAL_SPS_EXT:
  917. case NAL_AUXILIARY_SLICE:
  918. break;
  919. case NAL_FF_IGNORE:
  920. break;
  921. default:
  922. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  923. nal->type, nal->size_bits);
  924. }
  925. if (context_count == h->max_contexts) {
  926. ret = ff_h264_execute_decode_slices(h, context_count);
  927. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  928. goto end;
  929. context_count = 0;
  930. }
  931. if (err < 0 || err == SLICE_SKIPED) {
  932. if (err < 0)
  933. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  934. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  935. } else if (err == SLICE_SINGLETHREAD) {
  936. if (context_count > 0) {
  937. ret = ff_h264_execute_decode_slices(h, context_count);
  938. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  939. goto end;
  940. context_count = 0;
  941. }
  942. /* Slice could not be decoded in parallel mode, restart. */
  943. sl = &h->slice_ctx[0];
  944. goto again;
  945. }
  946. }
  947. if (context_count) {
  948. ret = ff_h264_execute_decode_slices(h, context_count);
  949. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  950. goto end;
  951. }
  952. ret = 0;
  953. end:
  954. #if CONFIG_ERROR_RESILIENCE
  955. /*
  956. * FIXME: Error handling code does not seem to support interlaced
  957. * when slices span multiple rows
  958. * The ff_er_add_slice calls don't work right for bottom
  959. * fields; they cause massive erroneous error concealing
  960. * Error marking covers both fields (top and bottom).
  961. * This causes a mismatched s->error_count
  962. * and a bad error table. Further, the error count goes to
  963. * INT_MAX when called for bottom field, because mb_y is
  964. * past end by one (callers fault) and resync_mb_y != 0
  965. * causes problems for the first MB line, too.
  966. */
  967. if (!FIELD_PICTURE(h) && h->current_slice &&
  968. h->ps.sps == (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data &&
  969. h->enable_er) {
  970. H264SliceContext *sl = h->slice_ctx;
  971. int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
  972. ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
  973. if (use_last_pic) {
  974. ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
  975. sl->ref_list[0][0].parent = &h->last_pic_for_ec;
  976. memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
  977. memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
  978. sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
  979. } else if (sl->ref_count[0]) {
  980. ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
  981. } else
  982. ff_h264_set_erpic(&sl->er.last_pic, NULL);
  983. if (sl->ref_count[1])
  984. ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
  985. sl->er.ref_count = sl->ref_count[0];
  986. ff_er_frame_end(&sl->er);
  987. if (use_last_pic)
  988. memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
  989. }
  990. #endif /* CONFIG_ERROR_RESILIENCE */
  991. /* clean up */
  992. if (h->cur_pic_ptr && !h->droppable) {
  993. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  994. h->picture_structure == PICT_BOTTOM_FIELD);
  995. }
  996. return (ret < 0) ? ret : buf_size;
  997. }
  998. /**
  999. * Return the number of bytes consumed for building the current frame.
  1000. */
  1001. static int get_consumed_bytes(int pos, int buf_size)
  1002. {
  1003. if (pos == 0)
  1004. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1005. if (pos + 10 > buf_size)
  1006. pos = buf_size; // oops ;)
  1007. return pos;
  1008. }
  1009. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1010. {
  1011. AVFrame *src = srcp->f;
  1012. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1013. int i;
  1014. int ret = av_frame_ref(dst, src);
  1015. if (ret < 0)
  1016. return ret;
  1017. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(&h->sei.frame_packing), 0);
  1018. h->backup_width = h->avctx->width;
  1019. h->backup_height = h->avctx->height;
  1020. h->backup_pix_fmt = h->avctx->pix_fmt;
  1021. h->avctx->width = dst->width;
  1022. h->avctx->height = dst->height;
  1023. h->avctx->pix_fmt = dst->format;
  1024. if (srcp->sei_recovery_frame_cnt == 0)
  1025. dst->key_frame = 1;
  1026. if (!srcp->crop)
  1027. return 0;
  1028. for (i = 0; i < desc->nb_components; i++) {
  1029. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1030. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1031. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1032. (srcp->crop_top >> vshift) * dst->linesize[i];
  1033. dst->data[i] += off;
  1034. }
  1035. return 0;
  1036. }
  1037. static int is_extra(const uint8_t *buf, int buf_size)
  1038. {
  1039. int cnt= buf[5]&0x1f;
  1040. const uint8_t *p= buf+6;
  1041. while(cnt--){
  1042. int nalsize= AV_RB16(p) + 2;
  1043. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
  1044. return 0;
  1045. p += nalsize;
  1046. }
  1047. cnt = *(p++);
  1048. if(!cnt)
  1049. return 0;
  1050. while(cnt--){
  1051. int nalsize= AV_RB16(p) + 2;
  1052. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
  1053. return 0;
  1054. p += nalsize;
  1055. }
  1056. return 1;
  1057. }
  1058. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1059. int *got_frame, AVPacket *avpkt)
  1060. {
  1061. const uint8_t *buf = avpkt->data;
  1062. int buf_size = avpkt->size;
  1063. H264Context *h = avctx->priv_data;
  1064. AVFrame *pict = data;
  1065. int buf_index = 0;
  1066. H264Picture *out;
  1067. int i, out_idx;
  1068. int ret;
  1069. h->flags = avctx->flags;
  1070. h->setup_finished = 0;
  1071. if (h->backup_width != -1) {
  1072. avctx->width = h->backup_width;
  1073. h->backup_width = -1;
  1074. }
  1075. if (h->backup_height != -1) {
  1076. avctx->height = h->backup_height;
  1077. h->backup_height = -1;
  1078. }
  1079. if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
  1080. avctx->pix_fmt = h->backup_pix_fmt;
  1081. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  1082. }
  1083. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1084. /* end of stream, output what is still in the buffers */
  1085. if (buf_size == 0) {
  1086. out:
  1087. h->cur_pic_ptr = NULL;
  1088. h->first_field = 0;
  1089. // FIXME factorize this with the output code below
  1090. out = h->delayed_pic[0];
  1091. out_idx = 0;
  1092. for (i = 1;
  1093. h->delayed_pic[i] &&
  1094. !h->delayed_pic[i]->f->key_frame &&
  1095. !h->delayed_pic[i]->mmco_reset;
  1096. i++)
  1097. if (h->delayed_pic[i]->poc < out->poc) {
  1098. out = h->delayed_pic[i];
  1099. out_idx = i;
  1100. }
  1101. for (i = out_idx; h->delayed_pic[i]; i++)
  1102. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1103. if (out) {
  1104. out->reference &= ~DELAYED_PIC_REF;
  1105. ret = output_frame(h, pict, out);
  1106. if (ret < 0)
  1107. return ret;
  1108. *got_frame = 1;
  1109. }
  1110. return buf_index;
  1111. }
  1112. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1113. int side_size;
  1114. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1115. if (is_extra(side, side_size))
  1116. ff_h264_decode_extradata(side, side_size,
  1117. &h->ps, &h->is_avc, &h->nal_length_size,
  1118. avctx->err_recognition, avctx);
  1119. }
  1120. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1121. if (is_extra(buf, buf_size))
  1122. return ff_h264_decode_extradata(buf, buf_size,
  1123. &h->ps, &h->is_avc, &h->nal_length_size,
  1124. avctx->err_recognition, avctx);
  1125. }
  1126. buf_index = decode_nal_units(h, buf, buf_size);
  1127. if (buf_index < 0)
  1128. return AVERROR_INVALIDDATA;
  1129. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1130. av_assert0(buf_index <= buf_size);
  1131. goto out;
  1132. }
  1133. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1134. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1135. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1136. return buf_size;
  1137. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1138. return AVERROR_INVALIDDATA;
  1139. }
  1140. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1141. (h->mb_y >= h->mb_height && h->mb_height)) {
  1142. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1143. decode_postinit(h, 1);
  1144. if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
  1145. return ret;
  1146. /* Wait for second field. */
  1147. *got_frame = 0;
  1148. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1149. (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
  1150. h->next_output_pic->recovered)) {
  1151. if (!h->next_output_pic->recovered)
  1152. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1153. if (!h->avctx->hwaccel &&
  1154. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1155. h->next_output_pic->field_poc[1] == INT_MAX)
  1156. ) {
  1157. int p;
  1158. AVFrame *f = h->next_output_pic->f;
  1159. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1160. uint8_t *dst_data[4];
  1161. int linesizes[4];
  1162. const uint8_t *src_data[4];
  1163. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1164. for (p = 0; p<4; p++) {
  1165. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1166. src_data[p] = f->data[p] + field *f->linesize[p];
  1167. linesizes[p] = 2*f->linesize[p];
  1168. }
  1169. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1170. f->format, f->width, f->height>>1);
  1171. }
  1172. ret = output_frame(h, pict, h->next_output_pic);
  1173. if (ret < 0)
  1174. return ret;
  1175. *got_frame = 1;
  1176. if (CONFIG_MPEGVIDEO) {
  1177. ff_print_debug_info2(h->avctx, pict, NULL,
  1178. h->next_output_pic->mb_type,
  1179. h->next_output_pic->qscale_table,
  1180. h->next_output_pic->motion_val,
  1181. NULL,
  1182. h->mb_width, h->mb_height, h->mb_stride, 1);
  1183. }
  1184. }
  1185. }
  1186. av_assert0(pict->buf[0] || !*got_frame);
  1187. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1188. return get_consumed_bytes(buf_index, buf_size);
  1189. }
  1190. #define OFFSET(x) offsetof(H264Context, x)
  1191. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1192. static const AVOption h264_options[] = {
  1193. {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
  1194. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1195. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  1196. { NULL },
  1197. };
  1198. static const AVClass h264_class = {
  1199. .class_name = "H264 Decoder",
  1200. .item_name = av_default_item_name,
  1201. .option = h264_options,
  1202. .version = LIBAVUTIL_VERSION_INT,
  1203. };
  1204. AVCodec ff_h264_decoder = {
  1205. .name = "h264",
  1206. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1207. .type = AVMEDIA_TYPE_VIDEO,
  1208. .id = AV_CODEC_ID_H264,
  1209. .priv_data_size = sizeof(H264Context),
  1210. .init = ff_h264_decode_init,
  1211. .close = h264_decode_end,
  1212. .decode = h264_decode_frame,
  1213. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1214. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1215. AV_CODEC_CAP_FRAME_THREADS,
  1216. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1217. .flush = flush_dpb,
  1218. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1219. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1220. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1221. .priv_class = &h264_class,
  1222. };
  1223. #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
  1224. static const AVClass h264_vdpau_class = {
  1225. .class_name = "H264 VDPAU Decoder",
  1226. .item_name = av_default_item_name,
  1227. .option = h264_options,
  1228. .version = LIBAVUTIL_VERSION_INT,
  1229. };
  1230. AVCodec ff_h264_vdpau_decoder = {
  1231. .name = "h264_vdpau",
  1232. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1233. .type = AVMEDIA_TYPE_VIDEO,
  1234. .id = AV_CODEC_ID_H264,
  1235. .priv_data_size = sizeof(H264Context),
  1236. .init = ff_h264_decode_init,
  1237. .close = h264_decode_end,
  1238. .decode = h264_decode_frame,
  1239. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
  1240. .flush = flush_dpb,
  1241. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1242. AV_PIX_FMT_NONE},
  1243. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1244. .priv_class = &h264_vdpau_class,
  1245. };
  1246. #endif