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.

983 lines
32KB

  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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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. #include "libavutil/display.h"
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/stereo3d.h"
  30. #include "libavutil/timer.h"
  31. #include "internal.h"
  32. #include "bytestream.h"
  33. #include "cabac.h"
  34. #include "cabac_functions.h"
  35. #include "error_resilience.h"
  36. #include "avcodec.h"
  37. #include "h264dec.h"
  38. #include "h2645_parse.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 "profiles.h"
  47. #include "rectangle.h"
  48. #include "thread.h"
  49. #include <assert.h>
  50. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  51. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  52. int (*mv)[2][4][2],
  53. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  54. {
  55. H264Context *h = opaque;
  56. H264SliceContext *sl = &h->slice_ctx[0];
  57. sl->mb_x = mb_x;
  58. sl->mb_y = mb_y;
  59. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  60. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  61. assert(ref >= 0);
  62. /* FIXME: It is possible albeit uncommon that slice references
  63. * differ between slices. We take the easy approach and ignore
  64. * it for now. If this turns out to have any relevance in
  65. * practice then correct remapping should be added. */
  66. if (ref >= sl->ref_count[0])
  67. ref = 0;
  68. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  69. 2, 2, 2, ref, 1);
  70. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  71. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  72. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  73. assert(!FRAME_MBAFF(h));
  74. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  75. }
  76. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  77. int y, int height)
  78. {
  79. AVCodecContext *avctx = h->avctx;
  80. const AVFrame *src = h->cur_pic.f;
  81. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  82. int vshift = desc->log2_chroma_h;
  83. const int field_pic = h->picture_structure != PICT_FRAME;
  84. if (field_pic) {
  85. height <<= 1;
  86. y <<= 1;
  87. }
  88. height = FFMIN(height, avctx->height - y);
  89. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  90. return;
  91. if (avctx->draw_horiz_band) {
  92. int offset[AV_NUM_DATA_POINTERS];
  93. int i;
  94. offset[0] = y * src->linesize[0];
  95. offset[1] =
  96. offset[2] = (y >> vshift) * src->linesize[1];
  97. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  98. offset[i] = 0;
  99. emms_c();
  100. avctx->draw_horiz_band(avctx, src, offset,
  101. y, h->picture_structure, height);
  102. }
  103. }
  104. void ff_h264_free_tables(H264Context *h)
  105. {
  106. int i;
  107. av_freep(&h->intra4x4_pred_mode);
  108. av_freep(&h->chroma_pred_mode_table);
  109. av_freep(&h->cbp_table);
  110. av_freep(&h->mvd_table[0]);
  111. av_freep(&h->mvd_table[1]);
  112. av_freep(&h->direct_table);
  113. av_freep(&h->non_zero_count);
  114. av_freep(&h->slice_table_base);
  115. h->slice_table = NULL;
  116. av_freep(&h->list_counts);
  117. av_freep(&h->mb2b_xy);
  118. av_freep(&h->mb2br_xy);
  119. av_buffer_pool_uninit(&h->qscale_table_pool);
  120. av_buffer_pool_uninit(&h->mb_type_pool);
  121. av_buffer_pool_uninit(&h->motion_val_pool);
  122. av_buffer_pool_uninit(&h->ref_index_pool);
  123. for (i = 0; i < h->nb_slice_ctx; i++) {
  124. H264SliceContext *sl = &h->slice_ctx[i];
  125. av_freep(&sl->dc_val_base);
  126. av_freep(&sl->er.mb_index2xy);
  127. av_freep(&sl->er.error_status_table);
  128. av_freep(&sl->er.er_temp_buffer);
  129. av_freep(&sl->bipred_scratchpad);
  130. av_freep(&sl->edge_emu_buffer);
  131. av_freep(&sl->top_borders[0]);
  132. av_freep(&sl->top_borders[1]);
  133. sl->bipred_scratchpad_allocated = 0;
  134. sl->edge_emu_buffer_allocated = 0;
  135. sl->top_borders_allocated[0] = 0;
  136. sl->top_borders_allocated[1] = 0;
  137. }
  138. }
  139. int ff_h264_alloc_tables(H264Context *h)
  140. {
  141. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  142. const int row_mb_num = h->mb_stride * 2 * h->nb_slice_ctx;
  143. int x, y;
  144. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  145. row_mb_num * 8 * sizeof(uint8_t), fail)
  146. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  147. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  148. big_mb_num * 48 * sizeof(uint8_t), fail)
  149. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  150. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  151. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  152. big_mb_num * sizeof(uint16_t), fail)
  153. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  154. big_mb_num * sizeof(uint8_t), fail)
  155. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  156. 16 * row_mb_num * sizeof(uint8_t), fail);
  157. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  158. 16 * row_mb_num * sizeof(uint8_t), fail);
  159. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  160. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  161. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  162. 4 * big_mb_num * sizeof(uint8_t), fail);
  163. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  164. big_mb_num * sizeof(uint8_t), fail)
  165. memset(h->slice_table_base, -1,
  166. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  167. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  168. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  169. big_mb_num * sizeof(uint32_t), fail);
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  171. big_mb_num * sizeof(uint32_t), fail);
  172. for (y = 0; y < h->mb_height; y++)
  173. for (x = 0; x < h->mb_width; x++) {
  174. const int mb_xy = x + y * h->mb_stride;
  175. const int b_xy = 4 * x + 4 * y * h->b_stride;
  176. h->mb2b_xy[mb_xy] = b_xy;
  177. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  178. }
  179. return 0;
  180. fail:
  181. ff_h264_free_tables(h);
  182. return AVERROR(ENOMEM);
  183. }
  184. /**
  185. * Init context
  186. * Allocate buffers which are not shared amongst multiple threads.
  187. */
  188. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  189. {
  190. ERContext *er = &sl->er;
  191. int mb_array_size = h->mb_height * h->mb_stride;
  192. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  193. int c_size = h->mb_stride * (h->mb_height + 1);
  194. int yc_size = y_size + 2 * c_size;
  195. int x, y, i;
  196. sl->ref_cache[0][scan8[5] + 1] =
  197. sl->ref_cache[0][scan8[7] + 1] =
  198. sl->ref_cache[0][scan8[13] + 1] =
  199. sl->ref_cache[1][scan8[5] + 1] =
  200. sl->ref_cache[1][scan8[7] + 1] =
  201. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  202. if (CONFIG_ERROR_RESILIENCE) {
  203. /* init ER */
  204. er->avctx = h->avctx;
  205. er->decode_mb = h264_er_decode_mb;
  206. er->opaque = h;
  207. er->quarter_sample = 1;
  208. er->mb_num = h->mb_num;
  209. er->mb_width = h->mb_width;
  210. er->mb_height = h->mb_height;
  211. er->mb_stride = h->mb_stride;
  212. er->b8_stride = h->mb_width * 2 + 1;
  213. // error resilience code looks cleaner with this
  214. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  215. (h->mb_num + 1) * sizeof(int), fail);
  216. for (y = 0; y < h->mb_height; y++)
  217. for (x = 0; x < h->mb_width; x++)
  218. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  219. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  220. h->mb_stride + h->mb_width;
  221. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  222. mb_array_size * sizeof(uint8_t), fail);
  223. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  224. h->mb_height * h->mb_stride, fail);
  225. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  226. yc_size * sizeof(int16_t), fail);
  227. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  228. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  229. er->dc_val[2] = er->dc_val[1] + c_size;
  230. for (i = 0; i < yc_size; i++)
  231. sl->dc_val_base[i] = 1024;
  232. }
  233. return 0;
  234. fail:
  235. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  236. }
  237. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  238. {
  239. int i;
  240. h->avctx = avctx;
  241. h->picture_structure = PICT_FRAME;
  242. h->workaround_bugs = avctx->workaround_bugs;
  243. h->flags = avctx->flags;
  244. h->poc.prev_poc_msb = 1 << 16;
  245. h->recovery_frame = -1;
  246. h->frame_recovered = 0;
  247. h->next_outputed_poc = INT_MIN;
  248. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  249. h->last_pocs[i] = INT_MIN;
  250. ff_h264_sei_uninit(&h->sei);
  251. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  252. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  253. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  254. if (!h->slice_ctx) {
  255. h->nb_slice_ctx = 0;
  256. return AVERROR(ENOMEM);
  257. }
  258. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  259. h->DPB[i].f = av_frame_alloc();
  260. if (!h->DPB[i].f)
  261. return AVERROR(ENOMEM);
  262. }
  263. h->cur_pic.f = av_frame_alloc();
  264. if (!h->cur_pic.f)
  265. return AVERROR(ENOMEM);
  266. for (i = 0; i < h->nb_slice_ctx; i++)
  267. h->slice_ctx[i].h264 = h;
  268. return 0;
  269. }
  270. static av_cold int h264_decode_end(AVCodecContext *avctx)
  271. {
  272. H264Context *h = avctx->priv_data;
  273. int i;
  274. ff_h264_free_tables(h);
  275. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  276. ff_h264_unref_picture(h, &h->DPB[i]);
  277. av_frame_free(&h->DPB[i].f);
  278. }
  279. h->cur_pic_ptr = NULL;
  280. av_freep(&h->slice_ctx);
  281. h->nb_slice_ctx = 0;
  282. for (i = 0; i < MAX_SPS_COUNT; i++)
  283. av_buffer_unref(&h->ps.sps_list[i]);
  284. for (i = 0; i < MAX_PPS_COUNT; i++)
  285. av_buffer_unref(&h->ps.pps_list[i]);
  286. ff_h2645_packet_uninit(&h->pkt);
  287. ff_h264_unref_picture(h, &h->cur_pic);
  288. av_frame_free(&h->cur_pic.f);
  289. return 0;
  290. }
  291. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  292. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  293. {
  294. H264Context *h = avctx->priv_data;
  295. int ret;
  296. ret = h264_init_context(avctx, h);
  297. if (ret < 0)
  298. return ret;
  299. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  300. if (ret != 0) {
  301. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  302. return AVERROR_UNKNOWN;
  303. }
  304. if (avctx->codec_id == AV_CODEC_ID_H264) {
  305. if (avctx->ticks_per_frame == 1)
  306. h->avctx->framerate.num *= 2;
  307. avctx->ticks_per_frame = 2;
  308. }
  309. if (avctx->extradata_size > 0 && avctx->extradata) {
  310. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  311. &h->ps, &h->is_avc, &h->nal_length_size,
  312. avctx->err_recognition, avctx);
  313. if (ret < 0) {
  314. h264_decode_end(avctx);
  315. return ret;
  316. }
  317. }
  318. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  319. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  320. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  321. }
  322. avctx->internal->allocate_progress = 1;
  323. if (h->enable_er) {
  324. av_log(avctx, AV_LOG_WARNING,
  325. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  326. "Use it at your own risk\n");
  327. }
  328. return 0;
  329. }
  330. static int decode_init_thread_copy(AVCodecContext *avctx)
  331. {
  332. H264Context *h = avctx->priv_data;
  333. int ret;
  334. if (!avctx->internal->is_copy)
  335. return 0;
  336. memset(h, 0, sizeof(*h));
  337. ret = h264_init_context(avctx, h);
  338. if (ret < 0)
  339. return ret;
  340. h->context_initialized = 0;
  341. return 0;
  342. }
  343. /**
  344. * Run setup operations that must be run after slice header decoding.
  345. * This includes finding the next displayed frame.
  346. *
  347. * @param h h264 master context
  348. * @param setup_finished enough NALs have been read that we can call
  349. * ff_thread_finish_setup()
  350. */
  351. static void decode_postinit(H264Context *h, int setup_finished)
  352. {
  353. const SPS *sps = h->ps.sps;
  354. H264Picture *out = h->cur_pic_ptr;
  355. H264Picture *cur = h->cur_pic_ptr;
  356. int i, pics, out_of_order, out_idx;
  357. int invalid = 0, cnt = 0;
  358. if (h->next_output_pic)
  359. return;
  360. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  361. /* FIXME: if we have two PAFF fields in one packet, we can't start
  362. * the next thread here. If we have one field per packet, we can.
  363. * The check in decode_nal_units() is not good enough to find this
  364. * yet, so we assume the worst for now. */
  365. // if (setup_finished)
  366. // ff_thread_finish_setup(h->avctx);
  367. return;
  368. }
  369. // FIXME do something with unavailable reference frames
  370. /* Sort B-frames into display order */
  371. if (sps->bitstream_restriction_flag ||
  372. h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  373. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  374. }
  375. pics = 0;
  376. while (h->delayed_pic[pics])
  377. pics++;
  378. assert(pics <= MAX_DELAYED_PIC_COUNT);
  379. h->delayed_pic[pics++] = cur;
  380. if (cur->reference == 0)
  381. cur->reference = DELAYED_PIC_REF;
  382. /* Frame reordering. This code takes pictures from coding order and sorts
  383. * them by their incremental POC value into display order. It supports POC
  384. * gaps, MMCO reset codes and random resets.
  385. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  386. * and/or can be closed down with a MMCO reset code. In sequences where
  387. * there is no delay, we can't detect that (since the frame was already
  388. * output to the user), so we also set h->mmco_reset to detect the MMCO
  389. * reset code.
  390. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  391. * we increase the delay between input and output. All frames affected by
  392. * the lag (e.g. those that should have been output before another frame
  393. * that we already returned to the user) will be dropped. This is a bug
  394. * that we will fix later. */
  395. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  396. cnt += out->poc < h->last_pocs[i];
  397. invalid += out->poc == INT_MIN;
  398. }
  399. if (!h->mmco_reset && !cur->f->key_frame &&
  400. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  401. h->mmco_reset = 2;
  402. if (pics > 1)
  403. h->delayed_pic[pics - 2]->mmco_reset = 2;
  404. }
  405. if (h->mmco_reset || cur->f->key_frame) {
  406. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  407. h->last_pocs[i] = INT_MIN;
  408. cnt = 0;
  409. invalid = MAX_DELAYED_PIC_COUNT;
  410. }
  411. out = h->delayed_pic[0];
  412. out_idx = 0;
  413. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  414. h->delayed_pic[i] &&
  415. !h->delayed_pic[i - 1]->mmco_reset &&
  416. !h->delayed_pic[i]->f->key_frame;
  417. i++)
  418. if (h->delayed_pic[i]->poc < out->poc) {
  419. out = h->delayed_pic[i];
  420. out_idx = i;
  421. }
  422. if (h->avctx->has_b_frames == 0 &&
  423. (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
  424. h->next_outputed_poc = INT_MIN;
  425. out_of_order = !out->f->key_frame && !h->mmco_reset &&
  426. (out->poc < h->next_outputed_poc);
  427. if (sps->bitstream_restriction_flag &&
  428. h->avctx->has_b_frames >= sps->num_reorder_frames) {
  429. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  430. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  431. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  432. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  433. }
  434. } else if (!h->avctx->has_b_frames &&
  435. ((h->next_outputed_poc != INT_MIN &&
  436. out->poc > h->next_outputed_poc + 2) ||
  437. cur->f->pict_type == AV_PICTURE_TYPE_B)) {
  438. h->avctx->has_b_frames++;
  439. }
  440. if (pics > h->avctx->has_b_frames) {
  441. out->reference &= ~DELAYED_PIC_REF;
  442. for (i = out_idx; h->delayed_pic[i]; i++)
  443. h->delayed_pic[i] = h->delayed_pic[i + 1];
  444. }
  445. memmove(h->last_pocs, &h->last_pocs[1],
  446. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  447. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  448. if (!out_of_order && pics > h->avctx->has_b_frames) {
  449. h->next_output_pic = out;
  450. if (out->mmco_reset) {
  451. if (out_idx > 0) {
  452. h->next_outputed_poc = out->poc;
  453. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  454. } else {
  455. h->next_outputed_poc = INT_MIN;
  456. }
  457. } else {
  458. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
  459. h->next_outputed_poc = INT_MIN;
  460. } else {
  461. h->next_outputed_poc = out->poc;
  462. }
  463. }
  464. h->mmco_reset = 0;
  465. } else {
  466. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  467. }
  468. if (h->next_output_pic) {
  469. if (h->next_output_pic->recovered) {
  470. // We have reached an recovery point and all frames after it in
  471. // display order are "recovered".
  472. h->frame_recovered |= FRAME_RECOVERED_SEI;
  473. }
  474. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  475. }
  476. if (setup_finished && !h->avctx->hwaccel) {
  477. ff_thread_finish_setup(h->avctx);
  478. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  479. h->setup_finished = 1;
  480. }
  481. }
  482. /**
  483. * instantaneous decoder refresh.
  484. */
  485. static void idr(H264Context *h)
  486. {
  487. ff_h264_remove_all_refs(h);
  488. h->poc.prev_frame_num =
  489. h->poc.prev_frame_num_offset =
  490. h->poc.prev_poc_msb =
  491. h->poc.prev_poc_lsb = 0;
  492. }
  493. /* forget old pics after a seek */
  494. void ff_h264_flush_change(H264Context *h)
  495. {
  496. int i;
  497. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  498. h->last_pocs[i] = INT_MIN;
  499. h->next_outputed_poc = INT_MIN;
  500. h->prev_interlaced_frame = 1;
  501. idr(h);
  502. if (h->cur_pic_ptr)
  503. h->cur_pic_ptr->reference = 0;
  504. h->first_field = 0;
  505. ff_h264_sei_uninit(&h->sei);
  506. h->recovery_frame = -1;
  507. h->frame_recovered = 0;
  508. }
  509. /* forget old pics after a seek */
  510. static void flush_dpb(AVCodecContext *avctx)
  511. {
  512. H264Context *h = avctx->priv_data;
  513. int i;
  514. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  515. ff_h264_flush_change(h);
  516. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  517. ff_h264_unref_picture(h, &h->DPB[i]);
  518. h->cur_pic_ptr = NULL;
  519. ff_h264_unref_picture(h, &h->cur_pic);
  520. h->mb_y = 0;
  521. ff_h264_free_tables(h);
  522. h->context_initialized = 0;
  523. }
  524. static int get_last_needed_nal(H264Context *h)
  525. {
  526. int nals_needed = 0;
  527. int i;
  528. for (i = 0; i < h->pkt.nb_nals; i++) {
  529. H2645NAL *nal = &h->pkt.nals[i];
  530. GetBitContext gb;
  531. /* packets can sometimes contain multiple PPS/SPS,
  532. * e.g. two PAFF field pictures in one packet, or a demuxer
  533. * which splits NALs strangely if so, when frame threading we
  534. * can't start the next thread until we've read all of them */
  535. switch (nal->type) {
  536. case NAL_SPS:
  537. case NAL_PPS:
  538. nals_needed = i;
  539. break;
  540. case NAL_DPA:
  541. case NAL_IDR_SLICE:
  542. case NAL_SLICE:
  543. init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
  544. if (!get_ue_golomb(&gb))
  545. nals_needed = i;
  546. }
  547. }
  548. return nals_needed;
  549. }
  550. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  551. {
  552. AVCodecContext *const avctx = h->avctx;
  553. unsigned context_count = 0;
  554. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  555. int i, ret = 0;
  556. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  557. h->current_slice = 0;
  558. if (!h->first_field)
  559. h->cur_pic_ptr = NULL;
  560. ff_h264_sei_uninit(&h->sei);
  561. }
  562. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  563. h->nal_length_size, avctx->codec_id);
  564. if (ret < 0) {
  565. av_log(avctx, AV_LOG_ERROR,
  566. "Error splitting the input into NAL units.\n");
  567. return ret;
  568. }
  569. if (avctx->active_thread_type & FF_THREAD_FRAME)
  570. nals_needed = get_last_needed_nal(h);
  571. for (i = 0; i < h->pkt.nb_nals; i++) {
  572. H2645NAL *nal = &h->pkt.nals[i];
  573. H264SliceContext *sl = &h->slice_ctx[context_count];
  574. int err;
  575. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  576. nal->ref_idc == 0 && nal->type != NAL_SEI)
  577. continue;
  578. // FIXME these should stop being context-global variables
  579. h->nal_ref_idc = nal->ref_idc;
  580. h->nal_unit_type = nal->type;
  581. err = 0;
  582. switch (nal->type) {
  583. case NAL_IDR_SLICE:
  584. if (nal->type != NAL_IDR_SLICE) {
  585. av_log(h->avctx, AV_LOG_ERROR,
  586. "Invalid mix of idr and non-idr slices\n");
  587. ret = -1;
  588. goto end;
  589. }
  590. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  591. case NAL_SLICE:
  592. sl->gb = nal->gb;
  593. if ((err = ff_h264_decode_slice_header(h, sl, nal)))
  594. break;
  595. if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
  596. h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
  597. ((1 << h->ps.sps->log2_max_frame_num) - 1);
  598. }
  599. h->cur_pic_ptr->f->key_frame |=
  600. (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
  601. if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
  602. h->recovery_frame = -1;
  603. h->cur_pic_ptr->recovered = 1;
  604. }
  605. // If we have an IDR, all frames after it in decoded order are
  606. // "recovered".
  607. if (nal->type == NAL_IDR_SLICE)
  608. h->frame_recovered |= FRAME_RECOVERED_IDR;
  609. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  610. if (h->current_slice == 1) {
  611. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  612. decode_postinit(h, i >= nals_needed);
  613. if (h->avctx->hwaccel &&
  614. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  615. return ret;
  616. }
  617. if (sl->redundant_pic_count == 0 &&
  618. (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
  619. (avctx->skip_frame < AVDISCARD_BIDIR ||
  620. sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
  621. (avctx->skip_frame < AVDISCARD_NONKEY ||
  622. h->cur_pic_ptr->f->key_frame) &&
  623. avctx->skip_frame < AVDISCARD_ALL) {
  624. if (avctx->hwaccel) {
  625. ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
  626. if (ret < 0)
  627. return ret;
  628. } else
  629. context_count++;
  630. }
  631. break;
  632. case NAL_DPA:
  633. case NAL_DPB:
  634. case NAL_DPC:
  635. avpriv_request_sample(avctx, "data partitioning");
  636. ret = AVERROR(ENOSYS);
  637. goto end;
  638. break;
  639. case NAL_SEI:
  640. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  641. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  642. goto end;
  643. break;
  644. case NAL_SPS:
  645. ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
  646. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  647. goto end;
  648. break;
  649. case NAL_PPS:
  650. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  651. nal->size_bits);
  652. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  653. goto end;
  654. break;
  655. case NAL_AUD:
  656. case NAL_END_SEQUENCE:
  657. case NAL_END_STREAM:
  658. case NAL_FILLER_DATA:
  659. case NAL_SPS_EXT:
  660. case NAL_AUXILIARY_SLICE:
  661. break;
  662. default:
  663. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  664. nal->type, nal->size_bits);
  665. }
  666. if (context_count == h->nb_slice_ctx) {
  667. ret = ff_h264_execute_decode_slices(h, context_count);
  668. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  669. goto end;
  670. context_count = 0;
  671. }
  672. if (err < 0) {
  673. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  674. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  675. }
  676. }
  677. if (context_count) {
  678. ret = ff_h264_execute_decode_slices(h, context_count);
  679. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  680. goto end;
  681. }
  682. ret = 0;
  683. end:
  684. /* clean up */
  685. if (h->cur_pic_ptr && !h->droppable) {
  686. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  687. h->picture_structure == PICT_BOTTOM_FIELD);
  688. }
  689. return (ret < 0) ? ret : buf_size;
  690. }
  691. /**
  692. * Return the number of bytes consumed for building the current frame.
  693. */
  694. static int get_consumed_bytes(int pos, int buf_size)
  695. {
  696. if (pos == 0)
  697. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  698. if (pos + 10 > buf_size)
  699. pos = buf_size; // oops ;)
  700. return pos;
  701. }
  702. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  703. {
  704. int i;
  705. int ret = av_frame_ref(dst, src);
  706. if (ret < 0)
  707. return ret;
  708. if (!h->ps.sps || !h->ps.sps->crop)
  709. return 0;
  710. for (i = 0; i < 3; i++) {
  711. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  712. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  713. int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
  714. (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
  715. dst->data[i] += off;
  716. }
  717. return 0;
  718. }
  719. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  720. int *got_frame, AVPacket *avpkt)
  721. {
  722. const uint8_t *buf = avpkt->data;
  723. int buf_size = avpkt->size;
  724. H264Context *h = avctx->priv_data;
  725. AVFrame *pict = data;
  726. int buf_index = 0;
  727. int ret;
  728. const uint8_t *new_extradata;
  729. int new_extradata_size;
  730. h->flags = avctx->flags;
  731. h->setup_finished = 0;
  732. /* end of stream, output what is still in the buffers */
  733. out:
  734. if (buf_size == 0) {
  735. H264Picture *out;
  736. int i, out_idx;
  737. h->cur_pic_ptr = NULL;
  738. // FIXME factorize this with the output code below
  739. out = h->delayed_pic[0];
  740. out_idx = 0;
  741. for (i = 1;
  742. h->delayed_pic[i] &&
  743. !h->delayed_pic[i]->f->key_frame &&
  744. !h->delayed_pic[i]->mmco_reset;
  745. i++)
  746. if (h->delayed_pic[i]->poc < out->poc) {
  747. out = h->delayed_pic[i];
  748. out_idx = i;
  749. }
  750. for (i = out_idx; h->delayed_pic[i]; i++)
  751. h->delayed_pic[i] = h->delayed_pic[i + 1];
  752. if (out) {
  753. ret = output_frame(h, pict, out->f);
  754. if (ret < 0)
  755. return ret;
  756. *got_frame = 1;
  757. }
  758. return buf_index;
  759. }
  760. new_extradata_size = 0;
  761. new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
  762. &new_extradata_size);
  763. if (new_extradata_size > 0 && new_extradata) {
  764. ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,
  765. &h->ps, &h->is_avc, &h->nal_length_size,
  766. avctx->err_recognition, avctx);
  767. if (ret < 0)
  768. return ret;
  769. }
  770. buf_index = decode_nal_units(h, buf, buf_size);
  771. if (buf_index < 0)
  772. return AVERROR_INVALIDDATA;
  773. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  774. buf_size = 0;
  775. goto out;
  776. }
  777. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  778. if (avctx->skip_frame >= AVDISCARD_NONREF)
  779. return 0;
  780. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  781. return AVERROR_INVALIDDATA;
  782. }
  783. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  784. (h->mb_y >= h->mb_height && h->mb_height)) {
  785. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  786. decode_postinit(h, 1);
  787. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  788. *got_frame = 0;
  789. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  790. h->next_output_pic->recovered)) {
  791. if (!h->next_output_pic->recovered)
  792. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  793. ret = output_frame(h, pict, h->next_output_pic->f);
  794. if (ret < 0)
  795. return ret;
  796. *got_frame = 1;
  797. }
  798. }
  799. assert(pict->buf[0] || !*got_frame);
  800. return get_consumed_bytes(buf_index, buf_size);
  801. }
  802. #define OFFSET(x) offsetof(H264Context, x)
  803. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  804. static const AVOption h264_options[] = {
  805. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  806. { NULL },
  807. };
  808. static const AVClass h264_class = {
  809. .class_name = "h264",
  810. .item_name = av_default_item_name,
  811. .option = h264_options,
  812. .version = LIBAVUTIL_VERSION_INT,
  813. };
  814. AVCodec ff_h264_decoder = {
  815. .name = "h264",
  816. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  817. .type = AVMEDIA_TYPE_VIDEO,
  818. .id = AV_CODEC_ID_H264,
  819. .priv_data_size = sizeof(H264Context),
  820. .init = ff_h264_decode_init,
  821. .close = h264_decode_end,
  822. .decode = h264_decode_frame,
  823. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  824. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  825. AV_CODEC_CAP_FRAME_THREADS,
  826. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  827. .flush = flush_dpb,
  828. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  829. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  830. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  831. .priv_class = &h264_class,
  832. };