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.

2871 lines
108KB

  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. #include "libavutil/avassert.h"
  27. #include "libavutil/display.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/stereo3d.h"
  30. #include "libavutil/timer.h"
  31. #include "internal.h"
  32. #include "cabac.h"
  33. #include "cabac_functions.h"
  34. #include "error_resilience.h"
  35. #include "avcodec.h"
  36. #include "h264.h"
  37. #include "h264dec.h"
  38. #include "h264data.h"
  39. #include "h264chroma.h"
  40. #include "h264_mvpred.h"
  41. #include "h264_ps.h"
  42. #include "golomb.h"
  43. #include "mathops.h"
  44. #include "mpegutils.h"
  45. #include "mpegvideo.h"
  46. #include "rectangle.h"
  47. #include "thread.h"
  48. static const uint8_t field_scan[16+1] = {
  49. 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
  50. 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
  51. 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
  52. 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
  53. };
  54. static const uint8_t field_scan8x8[64+1] = {
  55. 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
  56. 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
  57. 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
  58. 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
  59. 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
  60. 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
  61. 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
  62. 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
  63. 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
  64. 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
  65. 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
  66. 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
  67. 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
  68. 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
  69. 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
  70. 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
  71. };
  72. static const uint8_t field_scan8x8_cavlc[64+1] = {
  73. 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
  74. 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
  75. 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
  76. 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
  77. 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
  78. 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
  79. 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
  80. 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
  81. 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
  82. 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
  83. 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
  84. 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
  85. 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
  86. 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
  87. 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
  88. 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
  89. };
  90. // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
  91. static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
  92. 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
  93. 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
  94. 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
  95. 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
  96. 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
  97. 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
  98. 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
  99. 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
  100. 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
  101. 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
  102. 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
  103. 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
  104. 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
  105. 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
  106. 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
  107. 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
  108. };
  109. static void release_unused_pictures(H264Context *h, int remove_current)
  110. {
  111. int i;
  112. /* release non reference frames */
  113. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  114. if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
  115. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  116. ff_h264_unref_picture(h, &h->DPB[i]);
  117. }
  118. }
  119. }
  120. static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
  121. {
  122. const H264Context *h = sl->h264;
  123. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  124. av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
  125. // edge emu needs blocksize + filter length - 1
  126. // (= 21x21 for H.264)
  127. av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
  128. av_fast_mallocz(&sl->top_borders[0], &sl->top_borders_allocated[0],
  129. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
  130. av_fast_mallocz(&sl->top_borders[1], &sl->top_borders_allocated[1],
  131. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
  132. if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
  133. !sl->top_borders[0] || !sl->top_borders[1]) {
  134. av_freep(&sl->bipred_scratchpad);
  135. av_freep(&sl->edge_emu_buffer);
  136. av_freep(&sl->top_borders[0]);
  137. av_freep(&sl->top_borders[1]);
  138. sl->bipred_scratchpad_allocated = 0;
  139. sl->edge_emu_buffer_allocated = 0;
  140. sl->top_borders_allocated[0] = 0;
  141. sl->top_borders_allocated[1] = 0;
  142. return AVERROR(ENOMEM);
  143. }
  144. return 0;
  145. }
  146. static int init_table_pools(H264Context *h)
  147. {
  148. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  149. const int mb_array_size = h->mb_stride * h->mb_height;
  150. const int b4_stride = h->mb_width * 4 + 1;
  151. const int b4_array_size = b4_stride * h->mb_height * 4;
  152. h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
  153. av_buffer_allocz);
  154. h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
  155. sizeof(uint32_t), av_buffer_allocz);
  156. h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
  157. sizeof(int16_t), av_buffer_allocz);
  158. h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
  159. if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
  160. !h->ref_index_pool) {
  161. av_buffer_pool_uninit(&h->qscale_table_pool);
  162. av_buffer_pool_uninit(&h->mb_type_pool);
  163. av_buffer_pool_uninit(&h->motion_val_pool);
  164. av_buffer_pool_uninit(&h->ref_index_pool);
  165. return AVERROR(ENOMEM);
  166. }
  167. return 0;
  168. }
  169. static int alloc_picture(H264Context *h, H264Picture *pic)
  170. {
  171. int i, ret = 0;
  172. av_assert0(!pic->f->data[0]);
  173. pic->tf.f = pic->f;
  174. ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
  175. AV_GET_BUFFER_FLAG_REF : 0);
  176. if (ret < 0)
  177. goto fail;
  178. if (h->avctx->hwaccel) {
  179. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  180. av_assert0(!pic->hwaccel_picture_private);
  181. if (hwaccel->frame_priv_data_size) {
  182. pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
  183. if (!pic->hwaccel_priv_buf)
  184. return AVERROR(ENOMEM);
  185. pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
  186. }
  187. }
  188. if (CONFIG_GRAY && !h->avctx->hwaccel && h->flags & AV_CODEC_FLAG_GRAY && pic->f->data[2]) {
  189. int h_chroma_shift, v_chroma_shift;
  190. av_pix_fmt_get_chroma_sub_sample(pic->f->format,
  191. &h_chroma_shift, &v_chroma_shift);
  192. for(i=0; i<AV_CEIL_RSHIFT(pic->f->height, v_chroma_shift); i++) {
  193. memset(pic->f->data[1] + pic->f->linesize[1]*i,
  194. 0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
  195. memset(pic->f->data[2] + pic->f->linesize[2]*i,
  196. 0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
  197. }
  198. }
  199. if (!h->qscale_table_pool) {
  200. ret = init_table_pools(h);
  201. if (ret < 0)
  202. goto fail;
  203. }
  204. pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
  205. pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
  206. if (!pic->qscale_table_buf || !pic->mb_type_buf)
  207. goto fail;
  208. pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
  209. pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
  210. for (i = 0; i < 2; i++) {
  211. pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
  212. pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
  213. if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
  214. goto fail;
  215. pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
  216. pic->ref_index[i] = pic->ref_index_buf[i]->data;
  217. }
  218. return 0;
  219. fail:
  220. ff_h264_unref_picture(h, pic);
  221. return (ret < 0) ? ret : AVERROR(ENOMEM);
  222. }
  223. static int find_unused_picture(H264Context *h)
  224. {
  225. int i;
  226. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  227. if (!h->DPB[i].f->buf[0])
  228. return i;
  229. }
  230. return AVERROR_INVALIDDATA;
  231. }
  232. #define IN_RANGE(a, b, size) (((void*)(a) >= (void*)(b)) && ((void*)(a) < (void*)((b) + (size))))
  233. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  234. (((pic) && (pic) >= (old_ctx)->DPB && \
  235. (pic) < (old_ctx)->DPB + H264_MAX_PICTURE_COUNT) ? \
  236. &(new_ctx)->DPB[(pic) - (old_ctx)->DPB] : NULL)
  237. static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
  238. H264Context *new_base,
  239. H264Context *old_base)
  240. {
  241. int i;
  242. for (i = 0; i < count; i++) {
  243. av_assert1(!from[i] ||
  244. IN_RANGE(from[i], old_base, 1) ||
  245. IN_RANGE(from[i], old_base->DPB, H264_MAX_PICTURE_COUNT));
  246. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  247. }
  248. }
  249. static int h264_slice_header_init(H264Context *h);
  250. int ff_h264_update_thread_context(AVCodecContext *dst,
  251. const AVCodecContext *src)
  252. {
  253. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  254. int inited = h->context_initialized, err = 0;
  255. int need_reinit = 0;
  256. int i, ret;
  257. if (dst == src)
  258. return 0;
  259. // We can't fail if SPS isn't set at it breaks current skip_frame code
  260. //if (!h1->ps.sps)
  261. // return AVERROR_INVALIDDATA;
  262. if (inited &&
  263. (h->width != h1->width ||
  264. h->height != h1->height ||
  265. h->mb_width != h1->mb_width ||
  266. h->mb_height != h1->mb_height ||
  267. !h->ps.sps ||
  268. h->ps.sps->bit_depth_luma != h1->ps.sps->bit_depth_luma ||
  269. h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
  270. h->ps.sps->colorspace != h1->ps.sps->colorspace)) {
  271. need_reinit = 1;
  272. }
  273. /* copy block_offset since frame_start may not be called */
  274. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  275. // SPS/PPS
  276. for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {
  277. av_buffer_unref(&h->ps.sps_list[i]);
  278. if (h1->ps.sps_list[i]) {
  279. h->ps.sps_list[i] = av_buffer_ref(h1->ps.sps_list[i]);
  280. if (!h->ps.sps_list[i])
  281. return AVERROR(ENOMEM);
  282. }
  283. }
  284. for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
  285. av_buffer_unref(&h->ps.pps_list[i]);
  286. if (h1->ps.pps_list[i]) {
  287. h->ps.pps_list[i] = av_buffer_ref(h1->ps.pps_list[i]);
  288. if (!h->ps.pps_list[i])
  289. return AVERROR(ENOMEM);
  290. }
  291. }
  292. av_buffer_unref(&h->ps.pps_ref);
  293. av_buffer_unref(&h->ps.sps_ref);
  294. h->ps.pps = NULL;
  295. h->ps.sps = NULL;
  296. if (h1->ps.pps_ref) {
  297. h->ps.pps_ref = av_buffer_ref(h1->ps.pps_ref);
  298. if (!h->ps.pps_ref)
  299. return AVERROR(ENOMEM);
  300. h->ps.pps = (const PPS*)h->ps.pps_ref->data;
  301. }
  302. if (h1->ps.sps_ref) {
  303. h->ps.sps_ref = av_buffer_ref(h1->ps.sps_ref);
  304. if (!h->ps.sps_ref)
  305. return AVERROR(ENOMEM);
  306. h->ps.sps = (const SPS*)h->ps.sps_ref->data;
  307. }
  308. if (need_reinit || !inited) {
  309. h->width = h1->width;
  310. h->height = h1->height;
  311. h->mb_height = h1->mb_height;
  312. h->mb_width = h1->mb_width;
  313. h->mb_num = h1->mb_num;
  314. h->mb_stride = h1->mb_stride;
  315. h->b_stride = h1->b_stride;
  316. h->x264_build = h1->x264_build;
  317. if (h->context_initialized || h1->context_initialized) {
  318. if ((err = h264_slice_header_init(h)) < 0) {
  319. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  320. return err;
  321. }
  322. }
  323. /* copy block_offset since frame_start may not be called */
  324. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  325. }
  326. h->avctx->coded_height = h1->avctx->coded_height;
  327. h->avctx->coded_width = h1->avctx->coded_width;
  328. h->avctx->width = h1->avctx->width;
  329. h->avctx->height = h1->avctx->height;
  330. h->width_from_caller = h1->width_from_caller;
  331. h->height_from_caller = h1->height_from_caller;
  332. h->coded_picture_number = h1->coded_picture_number;
  333. h->first_field = h1->first_field;
  334. h->picture_structure = h1->picture_structure;
  335. h->mb_aff_frame = h1->mb_aff_frame;
  336. h->droppable = h1->droppable;
  337. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  338. ff_h264_unref_picture(h, &h->DPB[i]);
  339. if (h1->DPB[i].f->buf[0] &&
  340. (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
  341. return ret;
  342. }
  343. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  344. ff_h264_unref_picture(h, &h->cur_pic);
  345. if (h1->cur_pic.f->buf[0]) {
  346. ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
  347. if (ret < 0)
  348. return ret;
  349. }
  350. h->enable_er = h1->enable_er;
  351. h->workaround_bugs = h1->workaround_bugs;
  352. h->droppable = h1->droppable;
  353. // extradata/NAL handling
  354. h->is_avc = h1->is_avc;
  355. h->nal_length_size = h1->nal_length_size;
  356. memcpy(&h->poc, &h1->poc, sizeof(h->poc));
  357. memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
  358. memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
  359. memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
  360. memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
  361. h->next_output_pic = h1->next_output_pic;
  362. h->next_outputed_poc = h1->next_outputed_poc;
  363. memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
  364. h->nb_mmco = h1->nb_mmco;
  365. h->mmco_reset = h1->mmco_reset;
  366. h->explicit_ref_marking = h1->explicit_ref_marking;
  367. h->long_ref_count = h1->long_ref_count;
  368. h->short_ref_count = h1->short_ref_count;
  369. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  370. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  371. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  372. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  373. h->frame_recovered = h1->frame_recovered;
  374. av_buffer_unref(&h->sei.a53_caption.buf_ref);
  375. if (h1->sei.a53_caption.buf_ref) {
  376. h->sei.a53_caption.buf_ref = av_buffer_ref(h1->sei.a53_caption.buf_ref);
  377. if (!h->sei.a53_caption.buf_ref)
  378. return AVERROR(ENOMEM);
  379. }
  380. if (!h->cur_pic_ptr)
  381. return 0;
  382. if (!h->droppable) {
  383. err = ff_h264_execute_ref_pic_marking(h);
  384. h->poc.prev_poc_msb = h->poc.poc_msb;
  385. h->poc.prev_poc_lsb = h->poc.poc_lsb;
  386. }
  387. h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
  388. h->poc.prev_frame_num = h->poc.frame_num;
  389. h->recovery_frame = h1->recovery_frame;
  390. return err;
  391. }
  392. static int h264_frame_start(H264Context *h)
  393. {
  394. H264Picture *pic;
  395. int i, ret;
  396. const int pixel_shift = h->pixel_shift;
  397. int c[4] = {
  398. 1<<(h->ps.sps->bit_depth_luma-1),
  399. 1<<(h->ps.sps->bit_depth_chroma-1),
  400. 1<<(h->ps.sps->bit_depth_chroma-1),
  401. -1
  402. };
  403. if (!ff_thread_can_start_frame(h->avctx)) {
  404. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  405. return -1;
  406. }
  407. release_unused_pictures(h, 1);
  408. h->cur_pic_ptr = NULL;
  409. i = find_unused_picture(h);
  410. if (i < 0) {
  411. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  412. return i;
  413. }
  414. pic = &h->DPB[i];
  415. pic->reference = h->droppable ? 0 : h->picture_structure;
  416. pic->f->coded_picture_number = h->coded_picture_number++;
  417. pic->field_picture = h->picture_structure != PICT_FRAME;
  418. pic->frame_num = h->poc.frame_num;
  419. /*
  420. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  421. * in later.
  422. * See decode_nal_units().
  423. */
  424. pic->f->key_frame = 0;
  425. pic->mmco_reset = 0;
  426. pic->recovered = 0;
  427. pic->invalid_gap = 0;
  428. pic->sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  429. pic->f->pict_type = h->slice_ctx[0].slice_type;
  430. pic->f->crop_left = h->crop_left;
  431. pic->f->crop_right = h->crop_right;
  432. pic->f->crop_top = h->crop_top;
  433. pic->f->crop_bottom = h->crop_bottom;
  434. if ((ret = alloc_picture(h, pic)) < 0)
  435. return ret;
  436. if(!h->frame_recovered && !h->avctx->hwaccel)
  437. ff_color_frame(pic->f, c);
  438. h->cur_pic_ptr = pic;
  439. ff_h264_unref_picture(h, &h->cur_pic);
  440. if (CONFIG_ERROR_RESILIENCE) {
  441. ff_h264_set_erpic(&h->slice_ctx[0].er.cur_pic, NULL);
  442. }
  443. if ((ret = ff_h264_ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
  444. return ret;
  445. for (i = 0; i < h->nb_slice_ctx; i++) {
  446. h->slice_ctx[i].linesize = h->cur_pic_ptr->f->linesize[0];
  447. h->slice_ctx[i].uvlinesize = h->cur_pic_ptr->f->linesize[1];
  448. }
  449. if (CONFIG_ERROR_RESILIENCE && h->enable_er) {
  450. ff_er_frame_start(&h->slice_ctx[0].er);
  451. ff_h264_set_erpic(&h->slice_ctx[0].er.last_pic, NULL);
  452. ff_h264_set_erpic(&h->slice_ctx[0].er.next_pic, NULL);
  453. }
  454. for (i = 0; i < 16; i++) {
  455. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
  456. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
  457. }
  458. for (i = 0; i < 16; i++) {
  459. h->block_offset[16 + i] =
  460. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
  461. h->block_offset[48 + 16 + i] =
  462. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
  463. }
  464. /* We mark the current picture as non-reference after allocating it, so
  465. * that if we break out due to an error it can be released automatically
  466. * in the next ff_mpv_frame_start().
  467. */
  468. h->cur_pic_ptr->reference = 0;
  469. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  470. h->next_output_pic = NULL;
  471. h->postpone_filter = 0;
  472. h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
  473. if (h->sei.unregistered.x264_build >= 0)
  474. h->x264_build = h->sei.unregistered.x264_build;
  475. assert(h->cur_pic_ptr->long_ref == 0);
  476. return 0;
  477. }
  478. static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
  479. uint8_t *src_y,
  480. uint8_t *src_cb, uint8_t *src_cr,
  481. int linesize, int uvlinesize,
  482. int simple)
  483. {
  484. uint8_t *top_border;
  485. int top_idx = 1;
  486. const int pixel_shift = h->pixel_shift;
  487. int chroma444 = CHROMA444(h);
  488. int chroma422 = CHROMA422(h);
  489. src_y -= linesize;
  490. src_cb -= uvlinesize;
  491. src_cr -= uvlinesize;
  492. if (!simple && FRAME_MBAFF(h)) {
  493. if (sl->mb_y & 1) {
  494. if (!MB_MBAFF(sl)) {
  495. top_border = sl->top_borders[0][sl->mb_x];
  496. AV_COPY128(top_border, src_y + 15 * linesize);
  497. if (pixel_shift)
  498. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  499. if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
  500. if (chroma444) {
  501. if (pixel_shift) {
  502. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  503. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  504. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  505. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  506. } else {
  507. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  508. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  509. }
  510. } else if (chroma422) {
  511. if (pixel_shift) {
  512. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  513. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  514. } else {
  515. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  516. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  517. }
  518. } else {
  519. if (pixel_shift) {
  520. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  521. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  522. } else {
  523. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  524. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  525. }
  526. }
  527. }
  528. }
  529. } else if (MB_MBAFF(sl)) {
  530. top_idx = 0;
  531. } else
  532. return;
  533. }
  534. top_border = sl->top_borders[top_idx][sl->mb_x];
  535. /* There are two lines saved, the line above the top macroblock
  536. * of a pair, and the line above the bottom macroblock. */
  537. AV_COPY128(top_border, src_y + 16 * linesize);
  538. if (pixel_shift)
  539. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  540. if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
  541. if (chroma444) {
  542. if (pixel_shift) {
  543. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  544. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  545. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  546. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  547. } else {
  548. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  549. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  550. }
  551. } else if (chroma422) {
  552. if (pixel_shift) {
  553. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  554. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  555. } else {
  556. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  557. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  558. }
  559. } else {
  560. if (pixel_shift) {
  561. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  562. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  563. } else {
  564. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  565. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  566. }
  567. }
  568. }
  569. }
  570. /**
  571. * Initialize implicit_weight table.
  572. * @param field 0/1 initialize the weight for interlaced MBAFF
  573. * -1 initializes the rest
  574. */
  575. static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
  576. {
  577. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  578. for (i = 0; i < 2; i++) {
  579. sl->pwt.luma_weight_flag[i] = 0;
  580. sl->pwt.chroma_weight_flag[i] = 0;
  581. }
  582. if (field < 0) {
  583. if (h->picture_structure == PICT_FRAME) {
  584. cur_poc = h->cur_pic_ptr->poc;
  585. } else {
  586. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  587. }
  588. if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
  589. sl->ref_list[0][0].poc + (int64_t)sl->ref_list[1][0].poc == 2LL * cur_poc) {
  590. sl->pwt.use_weight = 0;
  591. sl->pwt.use_weight_chroma = 0;
  592. return;
  593. }
  594. ref_start = 0;
  595. ref_count0 = sl->ref_count[0];
  596. ref_count1 = sl->ref_count[1];
  597. } else {
  598. cur_poc = h->cur_pic_ptr->field_poc[field];
  599. ref_start = 16;
  600. ref_count0 = 16 + 2 * sl->ref_count[0];
  601. ref_count1 = 16 + 2 * sl->ref_count[1];
  602. }
  603. sl->pwt.use_weight = 2;
  604. sl->pwt.use_weight_chroma = 2;
  605. sl->pwt.luma_log2_weight_denom = 5;
  606. sl->pwt.chroma_log2_weight_denom = 5;
  607. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  608. int64_t poc0 = sl->ref_list[0][ref0].poc;
  609. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  610. int w = 32;
  611. if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
  612. int poc1 = sl->ref_list[1][ref1].poc;
  613. int td = av_clip_int8(poc1 - poc0);
  614. if (td) {
  615. int tb = av_clip_int8(cur_poc - poc0);
  616. int tx = (16384 + (FFABS(td) >> 1)) / td;
  617. int dist_scale_factor = (tb * tx + 32) >> 8;
  618. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  619. w = 64 - dist_scale_factor;
  620. }
  621. }
  622. if (field < 0) {
  623. sl->pwt.implicit_weight[ref0][ref1][0] =
  624. sl->pwt.implicit_weight[ref0][ref1][1] = w;
  625. } else {
  626. sl->pwt.implicit_weight[ref0][ref1][field] = w;
  627. }
  628. }
  629. }
  630. }
  631. /**
  632. * initialize scan tables
  633. */
  634. static void init_scan_tables(H264Context *h)
  635. {
  636. int i;
  637. for (i = 0; i < 16; i++) {
  638. #define TRANSPOSE(x) ((x) >> 2) | (((x) << 2) & 0xF)
  639. h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
  640. h->field_scan[i] = TRANSPOSE(field_scan[i]);
  641. #undef TRANSPOSE
  642. }
  643. for (i = 0; i < 64; i++) {
  644. #define TRANSPOSE(x) ((x) >> 3) | (((x) & 7) << 3)
  645. h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
  646. h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
  647. h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
  648. h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
  649. #undef TRANSPOSE
  650. }
  651. if (h->ps.sps->transform_bypass) { // FIXME same ugly
  652. memcpy(h->zigzag_scan_q0 , ff_zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  653. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  654. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  655. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  656. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  657. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  658. } else {
  659. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  660. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  661. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  662. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  663. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  664. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  665. }
  666. }
  667. static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
  668. {
  669. #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
  670. (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
  671. CONFIG_H264_NVDEC_HWACCEL + \
  672. CONFIG_H264_VAAPI_HWACCEL + \
  673. CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
  674. CONFIG_H264_VDPAU_HWACCEL)
  675. enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
  676. const enum AVPixelFormat *choices = pix_fmts;
  677. int i;
  678. switch (h->ps.sps->bit_depth_luma) {
  679. case 9:
  680. if (CHROMA444(h)) {
  681. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  682. *fmt++ = AV_PIX_FMT_GBRP9;
  683. } else
  684. *fmt++ = AV_PIX_FMT_YUV444P9;
  685. } else if (CHROMA422(h))
  686. *fmt++ = AV_PIX_FMT_YUV422P9;
  687. else
  688. *fmt++ = AV_PIX_FMT_YUV420P9;
  689. break;
  690. case 10:
  691. if (CHROMA444(h)) {
  692. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  693. *fmt++ = AV_PIX_FMT_GBRP10;
  694. } else
  695. *fmt++ = AV_PIX_FMT_YUV444P10;
  696. } else if (CHROMA422(h))
  697. *fmt++ = AV_PIX_FMT_YUV422P10;
  698. else
  699. *fmt++ = AV_PIX_FMT_YUV420P10;
  700. break;
  701. case 12:
  702. if (CHROMA444(h)) {
  703. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  704. *fmt++ = AV_PIX_FMT_GBRP12;
  705. } else
  706. *fmt++ = AV_PIX_FMT_YUV444P12;
  707. } else if (CHROMA422(h))
  708. *fmt++ = AV_PIX_FMT_YUV422P12;
  709. else
  710. *fmt++ = AV_PIX_FMT_YUV420P12;
  711. break;
  712. case 14:
  713. if (CHROMA444(h)) {
  714. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  715. *fmt++ = AV_PIX_FMT_GBRP14;
  716. } else
  717. *fmt++ = AV_PIX_FMT_YUV444P14;
  718. } else if (CHROMA422(h))
  719. *fmt++ = AV_PIX_FMT_YUV422P14;
  720. else
  721. *fmt++ = AV_PIX_FMT_YUV420P14;
  722. break;
  723. case 8:
  724. #if CONFIG_H264_VDPAU_HWACCEL
  725. *fmt++ = AV_PIX_FMT_VDPAU;
  726. #endif
  727. #if CONFIG_H264_NVDEC_HWACCEL
  728. *fmt++ = AV_PIX_FMT_CUDA;
  729. #endif
  730. if (CHROMA444(h)) {
  731. if (h->avctx->colorspace == AVCOL_SPC_RGB)
  732. *fmt++ = AV_PIX_FMT_GBRP;
  733. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  734. *fmt++ = AV_PIX_FMT_YUVJ444P;
  735. else
  736. *fmt++ = AV_PIX_FMT_YUV444P;
  737. } else if (CHROMA422(h)) {
  738. if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  739. *fmt++ = AV_PIX_FMT_YUVJ422P;
  740. else
  741. *fmt++ = AV_PIX_FMT_YUV422P;
  742. } else {
  743. #if CONFIG_H264_DXVA2_HWACCEL
  744. *fmt++ = AV_PIX_FMT_DXVA2_VLD;
  745. #endif
  746. #if CONFIG_H264_D3D11VA_HWACCEL
  747. *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
  748. *fmt++ = AV_PIX_FMT_D3D11;
  749. #endif
  750. #if CONFIG_H264_VAAPI_HWACCEL
  751. *fmt++ = AV_PIX_FMT_VAAPI;
  752. #endif
  753. #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
  754. *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
  755. #endif
  756. if (h->avctx->codec->pix_fmts)
  757. choices = h->avctx->codec->pix_fmts;
  758. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  759. *fmt++ = AV_PIX_FMT_YUVJ420P;
  760. else
  761. *fmt++ = AV_PIX_FMT_YUV420P;
  762. }
  763. break;
  764. default:
  765. av_log(h->avctx, AV_LOG_ERROR,
  766. "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
  767. return AVERROR_INVALIDDATA;
  768. }
  769. *fmt = AV_PIX_FMT_NONE;
  770. for (i=0; choices[i] != AV_PIX_FMT_NONE; i++)
  771. if (choices[i] == h->avctx->pix_fmt && !force_callback)
  772. return choices[i];
  773. return ff_thread_get_format(h->avctx, choices);
  774. }
  775. /* export coded and cropped frame dimensions to AVCodecContext */
  776. static int init_dimensions(H264Context *h)
  777. {
  778. const SPS *sps = (const SPS*)h->ps.sps;
  779. int cr = sps->crop_right;
  780. int cl = sps->crop_left;
  781. int ct = sps->crop_top;
  782. int cb = sps->crop_bottom;
  783. int width = h->width - (cr + cl);
  784. int height = h->height - (ct + cb);
  785. av_assert0(sps->crop_right + sps->crop_left < (unsigned)h->width);
  786. av_assert0(sps->crop_top + sps->crop_bottom < (unsigned)h->height);
  787. /* handle container cropping */
  788. if (h->width_from_caller > 0 && h->height_from_caller > 0 &&
  789. !sps->crop_top && !sps->crop_left &&
  790. FFALIGN(h->width_from_caller, 16) == FFALIGN(width, 16) &&
  791. FFALIGN(h->height_from_caller, 16) == FFALIGN(height, 16) &&
  792. h->width_from_caller <= width &&
  793. h->height_from_caller <= height) {
  794. width = h->width_from_caller;
  795. height = h->height_from_caller;
  796. cl = 0;
  797. ct = 0;
  798. cr = h->width - width;
  799. cb = h->height - height;
  800. } else {
  801. h->width_from_caller = 0;
  802. h->height_from_caller = 0;
  803. }
  804. h->avctx->coded_width = h->width;
  805. h->avctx->coded_height = h->height;
  806. h->avctx->width = width;
  807. h->avctx->height = height;
  808. h->crop_right = cr;
  809. h->crop_left = cl;
  810. h->crop_top = ct;
  811. h->crop_bottom = cb;
  812. return 0;
  813. }
  814. static int h264_slice_header_init(H264Context *h)
  815. {
  816. const SPS *sps = h->ps.sps;
  817. int i, ret;
  818. ff_set_sar(h->avctx, sps->sar);
  819. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  820. &h->chroma_x_shift, &h->chroma_y_shift);
  821. if (sps->timing_info_present_flag) {
  822. int64_t den = sps->time_scale;
  823. if (h->x264_build < 44U)
  824. den *= 2;
  825. av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
  826. sps->num_units_in_tick * h->avctx->ticks_per_frame, den, 1 << 30);
  827. }
  828. ff_h264_free_tables(h);
  829. h->first_field = 0;
  830. h->prev_interlaced_frame = 1;
  831. init_scan_tables(h);
  832. ret = ff_h264_alloc_tables(h);
  833. if (ret < 0) {
  834. av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
  835. goto fail;
  836. }
  837. if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 14 ||
  838. sps->bit_depth_luma == 11 || sps->bit_depth_luma == 13
  839. ) {
  840. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  841. sps->bit_depth_luma);
  842. ret = AVERROR_INVALIDDATA;
  843. goto fail;
  844. }
  845. h->cur_bit_depth_luma =
  846. h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
  847. h->cur_chroma_format_idc = sps->chroma_format_idc;
  848. h->pixel_shift = sps->bit_depth_luma > 8;
  849. h->chroma_format_idc = sps->chroma_format_idc;
  850. h->bit_depth_luma = sps->bit_depth_luma;
  851. ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
  852. sps->chroma_format_idc);
  853. ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
  854. ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
  855. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
  856. sps->chroma_format_idc);
  857. ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
  858. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  859. ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
  860. if (ret < 0) {
  861. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  862. goto fail;
  863. }
  864. } else {
  865. for (i = 0; i < h->nb_slice_ctx; i++) {
  866. H264SliceContext *sl = &h->slice_ctx[i];
  867. sl->h264 = h;
  868. sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
  869. sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
  870. sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
  871. if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
  872. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  873. goto fail;
  874. }
  875. }
  876. }
  877. h->context_initialized = 1;
  878. return 0;
  879. fail:
  880. ff_h264_free_tables(h);
  881. h->context_initialized = 0;
  882. return ret;
  883. }
  884. static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
  885. {
  886. switch (a) {
  887. case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
  888. case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
  889. case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
  890. default:
  891. return a;
  892. }
  893. }
  894. static int h264_init_ps(H264Context *h, const H264SliceContext *sl, int first_slice)
  895. {
  896. const SPS *sps;
  897. int needs_reinit = 0, must_reinit, ret;
  898. if (first_slice) {
  899. av_buffer_unref(&h->ps.pps_ref);
  900. h->ps.pps = NULL;
  901. h->ps.pps_ref = av_buffer_ref(h->ps.pps_list[sl->pps_id]);
  902. if (!h->ps.pps_ref)
  903. return AVERROR(ENOMEM);
  904. h->ps.pps = (const PPS*)h->ps.pps_ref->data;
  905. }
  906. if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
  907. av_buffer_unref(&h->ps.sps_ref);
  908. h->ps.sps = NULL;
  909. h->ps.sps_ref = av_buffer_ref(h->ps.sps_list[h->ps.pps->sps_id]);
  910. if (!h->ps.sps_ref)
  911. return AVERROR(ENOMEM);
  912. h->ps.sps = (const SPS*)h->ps.sps_ref->data;
  913. if (h->mb_width != h->ps.sps->mb_width ||
  914. h->mb_height != h->ps.sps->mb_height ||
  915. h->cur_bit_depth_luma != h->ps.sps->bit_depth_luma ||
  916. h->cur_chroma_format_idc != h->ps.sps->chroma_format_idc
  917. )
  918. needs_reinit = 1;
  919. if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
  920. h->chroma_format_idc != h->ps.sps->chroma_format_idc)
  921. needs_reinit = 1;
  922. }
  923. sps = h->ps.sps;
  924. must_reinit = (h->context_initialized &&
  925. ( 16*sps->mb_width != h->avctx->coded_width
  926. || 16*sps->mb_height != h->avctx->coded_height
  927. || h->cur_bit_depth_luma != sps->bit_depth_luma
  928. || h->cur_chroma_format_idc != sps->chroma_format_idc
  929. || h->mb_width != sps->mb_width
  930. || h->mb_height != sps->mb_height
  931. ));
  932. if (h->avctx->pix_fmt == AV_PIX_FMT_NONE
  933. || (non_j_pixfmt(h->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h, 0))))
  934. must_reinit = 1;
  935. if (first_slice && av_cmp_q(sps->sar, h->avctx->sample_aspect_ratio))
  936. must_reinit = 1;
  937. if (!h->setup_finished) {
  938. h->avctx->profile = ff_h264_get_profile(sps);
  939. h->avctx->level = sps->level_idc;
  940. h->avctx->refs = sps->ref_frame_count;
  941. h->mb_width = sps->mb_width;
  942. h->mb_height = sps->mb_height;
  943. h->mb_num = h->mb_width * h->mb_height;
  944. h->mb_stride = h->mb_width + 1;
  945. h->b_stride = h->mb_width * 4;
  946. h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
  947. h->width = 16 * h->mb_width;
  948. h->height = 16 * h->mb_height;
  949. ret = init_dimensions(h);
  950. if (ret < 0)
  951. return ret;
  952. if (sps->video_signal_type_present_flag) {
  953. h->avctx->color_range = sps->full_range > 0 ? AVCOL_RANGE_JPEG
  954. : AVCOL_RANGE_MPEG;
  955. if (sps->colour_description_present_flag) {
  956. if (h->avctx->colorspace != sps->colorspace)
  957. needs_reinit = 1;
  958. h->avctx->color_primaries = sps->color_primaries;
  959. h->avctx->color_trc = sps->color_trc;
  960. h->avctx->colorspace = sps->colorspace;
  961. }
  962. }
  963. if (h->sei.alternative_transfer.present &&
  964. av_color_transfer_name(h->sei.alternative_transfer.preferred_transfer_characteristics) &&
  965. h->sei.alternative_transfer.preferred_transfer_characteristics != AVCOL_TRC_UNSPECIFIED) {
  966. h->avctx->color_trc = h->sei.alternative_transfer.preferred_transfer_characteristics;
  967. }
  968. }
  969. if (!h->context_initialized || must_reinit || needs_reinit) {
  970. int flush_changes = h->context_initialized;
  971. h->context_initialized = 0;
  972. if (sl != h->slice_ctx) {
  973. av_log(h->avctx, AV_LOG_ERROR,
  974. "changing width %d -> %d / height %d -> %d on "
  975. "slice %d\n",
  976. h->width, h->avctx->coded_width,
  977. h->height, h->avctx->coded_height,
  978. h->current_slice + 1);
  979. return AVERROR_INVALIDDATA;
  980. }
  981. av_assert1(first_slice);
  982. if (flush_changes)
  983. ff_h264_flush_change(h);
  984. if ((ret = get_pixel_format(h, 1)) < 0)
  985. return ret;
  986. h->avctx->pix_fmt = ret;
  987. av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
  988. "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
  989. if ((ret = h264_slice_header_init(h)) < 0) {
  990. av_log(h->avctx, AV_LOG_ERROR,
  991. "h264_slice_header_init() failed\n");
  992. return ret;
  993. }
  994. }
  995. return 0;
  996. }
  997. static int h264_export_frame_props(H264Context *h)
  998. {
  999. const SPS *sps = h->ps.sps;
  1000. H264Picture *cur = h->cur_pic_ptr;
  1001. cur->f->interlaced_frame = 0;
  1002. cur->f->repeat_pict = 0;
  1003. /* Signal interlacing information externally. */
  1004. /* Prioritize picture timing SEI information over used
  1005. * decoding process if it exists. */
  1006. if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
  1007. H264SEIPictureTiming *pt = &h->sei.picture_timing;
  1008. switch (pt->pic_struct) {
  1009. case H264_SEI_PIC_STRUCT_FRAME:
  1010. break;
  1011. case H264_SEI_PIC_STRUCT_TOP_FIELD:
  1012. case H264_SEI_PIC_STRUCT_BOTTOM_FIELD:
  1013. cur->f->interlaced_frame = 1;
  1014. break;
  1015. case H264_SEI_PIC_STRUCT_TOP_BOTTOM:
  1016. case H264_SEI_PIC_STRUCT_BOTTOM_TOP:
  1017. if (FIELD_OR_MBAFF_PICTURE(h))
  1018. cur->f->interlaced_frame = 1;
  1019. else
  1020. // try to flag soft telecine progressive
  1021. cur->f->interlaced_frame = h->prev_interlaced_frame;
  1022. break;
  1023. case H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1024. case H264_SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1025. /* Signal the possibility of telecined film externally
  1026. * (pic_struct 5,6). From these hints, let the applications
  1027. * decide if they apply deinterlacing. */
  1028. cur->f->repeat_pict = 1;
  1029. break;
  1030. case H264_SEI_PIC_STRUCT_FRAME_DOUBLING:
  1031. cur->f->repeat_pict = 2;
  1032. break;
  1033. case H264_SEI_PIC_STRUCT_FRAME_TRIPLING:
  1034. cur->f->repeat_pict = 4;
  1035. break;
  1036. }
  1037. if ((pt->ct_type & 3) &&
  1038. pt->pic_struct <= H264_SEI_PIC_STRUCT_BOTTOM_TOP)
  1039. cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
  1040. } else {
  1041. /* Derive interlacing flag from used decoding process. */
  1042. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  1043. }
  1044. h->prev_interlaced_frame = cur->f->interlaced_frame;
  1045. if (cur->field_poc[0] != cur->field_poc[1]) {
  1046. /* Derive top_field_first from field pocs. */
  1047. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1048. } else {
  1049. if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
  1050. /* Use picture timing SEI information. Even if it is a
  1051. * information of a past frame, better than nothing. */
  1052. if (h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM ||
  1053. h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1054. cur->f->top_field_first = 1;
  1055. else
  1056. cur->f->top_field_first = 0;
  1057. } else if (cur->f->interlaced_frame) {
  1058. /* Default to top field first when pic_struct_present_flag
  1059. * is not set but interlaced frame detected */
  1060. cur->f->top_field_first = 1;
  1061. } else {
  1062. /* Most likely progressive */
  1063. cur->f->top_field_first = 0;
  1064. }
  1065. }
  1066. if (h->sei.frame_packing.present &&
  1067. h->sei.frame_packing.arrangement_type <= 6 &&
  1068. h->sei.frame_packing.content_interpretation_type > 0 &&
  1069. h->sei.frame_packing.content_interpretation_type < 3) {
  1070. H264SEIFramePacking *fp = &h->sei.frame_packing;
  1071. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  1072. if (stereo) {
  1073. switch (fp->arrangement_type) {
  1074. case H264_SEI_FPA_TYPE_CHECKERBOARD:
  1075. stereo->type = AV_STEREO3D_CHECKERBOARD;
  1076. break;
  1077. case H264_SEI_FPA_TYPE_INTERLEAVE_COLUMN:
  1078. stereo->type = AV_STEREO3D_COLUMNS;
  1079. break;
  1080. case H264_SEI_FPA_TYPE_INTERLEAVE_ROW:
  1081. stereo->type = AV_STEREO3D_LINES;
  1082. break;
  1083. case H264_SEI_FPA_TYPE_SIDE_BY_SIDE:
  1084. if (fp->quincunx_sampling_flag)
  1085. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  1086. else
  1087. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  1088. break;
  1089. case H264_SEI_FPA_TYPE_TOP_BOTTOM:
  1090. stereo->type = AV_STEREO3D_TOPBOTTOM;
  1091. break;
  1092. case H264_SEI_FPA_TYPE_INTERLEAVE_TEMPORAL:
  1093. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  1094. break;
  1095. case H264_SEI_FPA_TYPE_2D:
  1096. stereo->type = AV_STEREO3D_2D;
  1097. break;
  1098. }
  1099. if (fp->content_interpretation_type == 2)
  1100. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  1101. if (fp->arrangement_type == H264_SEI_FPA_TYPE_INTERLEAVE_TEMPORAL) {
  1102. if (fp->current_frame_is_frame0_flag)
  1103. stereo->view = AV_STEREO3D_VIEW_LEFT;
  1104. else
  1105. stereo->view = AV_STEREO3D_VIEW_RIGHT;
  1106. }
  1107. }
  1108. }
  1109. if (h->sei.display_orientation.present &&
  1110. (h->sei.display_orientation.anticlockwise_rotation ||
  1111. h->sei.display_orientation.hflip ||
  1112. h->sei.display_orientation.vflip)) {
  1113. H264SEIDisplayOrientation *o = &h->sei.display_orientation;
  1114. double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
  1115. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  1116. AV_FRAME_DATA_DISPLAYMATRIX,
  1117. sizeof(int32_t) * 9);
  1118. if (rotation) {
  1119. av_display_rotation_set((int32_t *)rotation->data, angle);
  1120. av_display_matrix_flip((int32_t *)rotation->data,
  1121. o->hflip, o->vflip);
  1122. }
  1123. }
  1124. if (h->sei.afd.present) {
  1125. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  1126. sizeof(uint8_t));
  1127. if (sd) {
  1128. *sd->data = h->sei.afd.active_format_description;
  1129. h->sei.afd.present = 0;
  1130. }
  1131. }
  1132. if (h->sei.a53_caption.buf_ref) {
  1133. H264SEIA53Caption *a53 = &h->sei.a53_caption;
  1134. AVFrameSideData *sd = av_frame_new_side_data_from_buf(cur->f, AV_FRAME_DATA_A53_CC, a53->buf_ref);
  1135. if (!sd)
  1136. av_buffer_unref(&a53->buf_ref);
  1137. a53->buf_ref = NULL;
  1138. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  1139. }
  1140. if (h->sei.picture_timing.timecode_cnt > 0) {
  1141. uint32_t tc = 0;
  1142. uint32_t *tc_sd;
  1143. AVFrameSideData *tcside = av_frame_new_side_data(cur->f,
  1144. AV_FRAME_DATA_S12M_TIMECODE,
  1145. sizeof(uint32_t)*4);
  1146. if (!tcside)
  1147. return AVERROR(ENOMEM);
  1148. tc_sd = (uint32_t*)tcside->data;
  1149. tc_sd[0] = h->sei.picture_timing.timecode_cnt;
  1150. for (int i = 0; i < tc_sd[0]; i++) {
  1151. uint32_t frames;
  1152. /* For SMPTE 12-M timecodes, frame count is a special case if > 30 FPS.
  1153. See SMPTE ST 12-1:2014 Sec 12.1 for more info. */
  1154. if (av_cmp_q(h->avctx->framerate, (AVRational) {30, 1}) == 1) {
  1155. frames = h->sei.picture_timing.timecode[i].frame / 2;
  1156. if (h->sei.picture_timing.timecode[i].frame % 2 == 1) {
  1157. if (av_cmp_q(h->avctx->framerate, (AVRational) {50, 1}) == 0)
  1158. tc |= (1 << 7);
  1159. else
  1160. tc |= (1 << 23);
  1161. }
  1162. } else {
  1163. frames = h->sei.picture_timing.timecode[i].frame;
  1164. }
  1165. tc |= h->sei.picture_timing.timecode[i].dropframe << 30;
  1166. tc |= (frames / 10) << 28;
  1167. tc |= (frames % 10) << 24;
  1168. tc |= (h->sei.picture_timing.timecode[i].seconds / 10) << 20;
  1169. tc |= (h->sei.picture_timing.timecode[i].seconds % 10) << 16;
  1170. tc |= (h->sei.picture_timing.timecode[i].minutes / 10) << 12;
  1171. tc |= (h->sei.picture_timing.timecode[i].minutes % 10) << 8;
  1172. tc |= (h->sei.picture_timing.timecode[i].hours / 10) << 4;
  1173. tc |= (h->sei.picture_timing.timecode[i].hours % 10);
  1174. tc_sd[i + 1] = tc;
  1175. }
  1176. h->sei.picture_timing.timecode_cnt = 0;
  1177. }
  1178. return 0;
  1179. }
  1180. static int h264_select_output_frame(H264Context *h)
  1181. {
  1182. const SPS *sps = h->ps.sps;
  1183. H264Picture *out = h->cur_pic_ptr;
  1184. H264Picture *cur = h->cur_pic_ptr;
  1185. int i, pics, out_of_order, out_idx;
  1186. cur->mmco_reset = h->mmco_reset;
  1187. h->mmco_reset = 0;
  1188. if (sps->bitstream_restriction_flag ||
  1189. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  1190. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  1191. }
  1192. for (i = 0; 1; i++) {
  1193. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1194. if(i)
  1195. h->last_pocs[i-1] = cur->poc;
  1196. break;
  1197. } else if(i) {
  1198. h->last_pocs[i-1]= h->last_pocs[i];
  1199. }
  1200. }
  1201. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1202. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  1203. || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - (int64_t)h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
  1204. out_of_order = FFMAX(out_of_order, 1);
  1205. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1206. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1207. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1208. h->last_pocs[i] = INT_MIN;
  1209. h->last_pocs[0] = cur->poc;
  1210. cur->mmco_reset = 1;
  1211. } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
  1212. int loglevel = h->avctx->frame_number > 1 ? AV_LOG_WARNING : AV_LOG_VERBOSE;
  1213. av_log(h->avctx, loglevel, "Increasing reorder buffer to %d\n", out_of_order);
  1214. h->avctx->has_b_frames = out_of_order;
  1215. }
  1216. pics = 0;
  1217. while (h->delayed_pic[pics])
  1218. pics++;
  1219. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1220. h->delayed_pic[pics++] = cur;
  1221. if (cur->reference == 0)
  1222. cur->reference = DELAYED_PIC_REF;
  1223. out = h->delayed_pic[0];
  1224. out_idx = 0;
  1225. for (i = 1; h->delayed_pic[i] &&
  1226. !h->delayed_pic[i]->f->key_frame &&
  1227. !h->delayed_pic[i]->mmco_reset;
  1228. i++)
  1229. if (h->delayed_pic[i]->poc < out->poc) {
  1230. out = h->delayed_pic[i];
  1231. out_idx = i;
  1232. }
  1233. if (h->avctx->has_b_frames == 0 &&
  1234. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  1235. h->next_outputed_poc = INT_MIN;
  1236. out_of_order = out->poc < h->next_outputed_poc;
  1237. if (out_of_order || pics > h->avctx->has_b_frames) {
  1238. out->reference &= ~DELAYED_PIC_REF;
  1239. for (i = out_idx; h->delayed_pic[i]; i++)
  1240. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1241. }
  1242. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1243. h->next_output_pic = out;
  1244. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  1245. h->next_outputed_poc = INT_MIN;
  1246. } else
  1247. h->next_outputed_poc = out->poc;
  1248. if (out->recovered) {
  1249. // We have reached an recovery point and all frames after it in
  1250. // display order are "recovered".
  1251. h->frame_recovered |= FRAME_RECOVERED_SEI;
  1252. }
  1253. out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  1254. if (!out->recovered) {
  1255. if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) &&
  1256. !(h->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL)) {
  1257. h->next_output_pic = NULL;
  1258. } else {
  1259. out->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1260. }
  1261. }
  1262. } else {
  1263. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1264. }
  1265. return 0;
  1266. }
  1267. /* This function is called right after decoding the slice header for a first
  1268. * slice in a field (or a frame). It decides whether we are decoding a new frame
  1269. * or a second field in a pair and does the necessary setup.
  1270. */
  1271. static int h264_field_start(H264Context *h, const H264SliceContext *sl,
  1272. const H2645NAL *nal, int first_slice)
  1273. {
  1274. int i;
  1275. const SPS *sps;
  1276. int last_pic_structure, last_pic_droppable, ret;
  1277. ret = h264_init_ps(h, sl, first_slice);
  1278. if (ret < 0)
  1279. return ret;
  1280. sps = h->ps.sps;
  1281. if (sps && sps->bitstream_restriction_flag &&
  1282. h->avctx->has_b_frames < sps->num_reorder_frames) {
  1283. h->avctx->has_b_frames = sps->num_reorder_frames;
  1284. }
  1285. last_pic_droppable = h->droppable;
  1286. last_pic_structure = h->picture_structure;
  1287. h->droppable = (nal->ref_idc == 0);
  1288. h->picture_structure = sl->picture_structure;
  1289. h->poc.frame_num = sl->frame_num;
  1290. h->poc.poc_lsb = sl->poc_lsb;
  1291. h->poc.delta_poc_bottom = sl->delta_poc_bottom;
  1292. h->poc.delta_poc[0] = sl->delta_poc[0];
  1293. h->poc.delta_poc[1] = sl->delta_poc[1];
  1294. /* Shorten frame num gaps so we don't have to allocate reference
  1295. * frames just to throw them away */
  1296. if (h->poc.frame_num != h->poc.prev_frame_num) {
  1297. int unwrap_prev_frame_num = h->poc.prev_frame_num;
  1298. int max_frame_num = 1 << sps->log2_max_frame_num;
  1299. if (unwrap_prev_frame_num > h->poc.frame_num)
  1300. unwrap_prev_frame_num -= max_frame_num;
  1301. if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
  1302. unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
  1303. if (unwrap_prev_frame_num < 0)
  1304. unwrap_prev_frame_num += max_frame_num;
  1305. h->poc.prev_frame_num = unwrap_prev_frame_num;
  1306. }
  1307. }
  1308. /* See if we have a decoded first field looking for a pair...
  1309. * Here, we're using that to see if we should mark previously
  1310. * decode frames as "finished".
  1311. * We have to do that before the "dummy" in-between frame allocation,
  1312. * since that can modify h->cur_pic_ptr. */
  1313. if (h->first_field) {
  1314. int last_field = last_pic_structure == PICT_BOTTOM_FIELD;
  1315. av_assert0(h->cur_pic_ptr);
  1316. av_assert0(h->cur_pic_ptr->f->buf[0]);
  1317. assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1318. /* Mark old field/frame as completed */
  1319. if (h->cur_pic_ptr->tf.owner[last_field] == h->avctx) {
  1320. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, last_field);
  1321. }
  1322. /* figure out if we have a complementary field pair */
  1323. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1324. /* Previous field is unmatched. Don't display it, but let it
  1325. * remain for reference if marked as such. */
  1326. if (last_pic_structure != PICT_FRAME) {
  1327. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1328. last_pic_structure == PICT_TOP_FIELD);
  1329. }
  1330. } else {
  1331. if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
  1332. /* This and previous field were reference, but had
  1333. * different frame_nums. Consider this field first in
  1334. * pair. Throw away previous field except for reference
  1335. * purposes. */
  1336. if (last_pic_structure != PICT_FRAME) {
  1337. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1338. last_pic_structure == PICT_TOP_FIELD);
  1339. }
  1340. } else {
  1341. /* Second field in complementary pair */
  1342. if (!((last_pic_structure == PICT_TOP_FIELD &&
  1343. h->picture_structure == PICT_BOTTOM_FIELD) ||
  1344. (last_pic_structure == PICT_BOTTOM_FIELD &&
  1345. h->picture_structure == PICT_TOP_FIELD))) {
  1346. av_log(h->avctx, AV_LOG_ERROR,
  1347. "Invalid field mode combination %d/%d\n",
  1348. last_pic_structure, h->picture_structure);
  1349. h->picture_structure = last_pic_structure;
  1350. h->droppable = last_pic_droppable;
  1351. return AVERROR_INVALIDDATA;
  1352. } else if (last_pic_droppable != h->droppable) {
  1353. avpriv_request_sample(h->avctx,
  1354. "Found reference and non-reference fields in the same frame, which");
  1355. h->picture_structure = last_pic_structure;
  1356. h->droppable = last_pic_droppable;
  1357. return AVERROR_PATCHWELCOME;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. while (h->poc.frame_num != h->poc.prev_frame_num && !h->first_field &&
  1363. h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
  1364. H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  1365. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  1366. h->poc.frame_num, h->poc.prev_frame_num);
  1367. if (!sps->gaps_in_frame_num_allowed_flag)
  1368. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  1369. h->last_pocs[i] = INT_MIN;
  1370. ret = h264_frame_start(h);
  1371. if (ret < 0) {
  1372. h->first_field = 0;
  1373. return ret;
  1374. }
  1375. h->poc.prev_frame_num++;
  1376. h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
  1377. h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
  1378. h->cur_pic_ptr->invalid_gap = !sps->gaps_in_frame_num_allowed_flag;
  1379. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  1380. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  1381. h->explicit_ref_marking = 0;
  1382. ret = ff_h264_execute_ref_pic_marking(h);
  1383. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1384. return ret;
  1385. /* Error concealment: If a ref is missing, copy the previous ref
  1386. * in its place.
  1387. * FIXME: Avoiding a memcpy would be nice, but ref handling makes
  1388. * many assumptions about there being no actual duplicates.
  1389. * FIXME: This does not copy padding for out-of-frame motion
  1390. * vectors. Given we are concealing a lost frame, this probably
  1391. * is not noticeable by comparison, but it should be fixed. */
  1392. if (h->short_ref_count) {
  1393. if (prev &&
  1394. h->short_ref[0]->f->width == prev->f->width &&
  1395. h->short_ref[0]->f->height == prev->f->height &&
  1396. h->short_ref[0]->f->format == prev->f->format) {
  1397. ff_thread_await_progress(&prev->tf, INT_MAX, 0);
  1398. if (prev->field_picture)
  1399. ff_thread_await_progress(&prev->tf, INT_MAX, 1);
  1400. av_image_copy(h->short_ref[0]->f->data,
  1401. h->short_ref[0]->f->linesize,
  1402. (const uint8_t **)prev->f->data,
  1403. prev->f->linesize,
  1404. prev->f->format,
  1405. prev->f->width,
  1406. prev->f->height);
  1407. h->short_ref[0]->poc = prev->poc + 2;
  1408. }
  1409. h->short_ref[0]->frame_num = h->poc.prev_frame_num;
  1410. }
  1411. }
  1412. /* See if we have a decoded first field looking for a pair...
  1413. * We're using that to see whether to continue decoding in that
  1414. * frame, or to allocate a new one. */
  1415. if (h->first_field) {
  1416. av_assert0(h->cur_pic_ptr);
  1417. av_assert0(h->cur_pic_ptr->f->buf[0]);
  1418. assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1419. /* figure out if we have a complementary field pair */
  1420. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1421. /* Previous field is unmatched. Don't display it, but let it
  1422. * remain for reference if marked as such. */
  1423. h->missing_fields ++;
  1424. h->cur_pic_ptr = NULL;
  1425. h->first_field = FIELD_PICTURE(h);
  1426. } else {
  1427. h->missing_fields = 0;
  1428. if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
  1429. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1430. h->picture_structure==PICT_BOTTOM_FIELD);
  1431. /* This and the previous field had different frame_nums.
  1432. * Consider this field first in pair. Throw away previous
  1433. * one except for reference purposes. */
  1434. h->first_field = 1;
  1435. h->cur_pic_ptr = NULL;
  1436. } else if (h->cur_pic_ptr->reference & DELAYED_PIC_REF) {
  1437. /* This frame was already output, we cannot draw into it
  1438. * anymore.
  1439. */
  1440. h->first_field = 1;
  1441. h->cur_pic_ptr = NULL;
  1442. } else {
  1443. /* Second field in complementary pair */
  1444. h->first_field = 0;
  1445. }
  1446. }
  1447. } else {
  1448. /* Frame or first field in a potentially complementary pair */
  1449. h->first_field = FIELD_PICTURE(h);
  1450. }
  1451. if (!FIELD_PICTURE(h) || h->first_field) {
  1452. if (h264_frame_start(h) < 0) {
  1453. h->first_field = 0;
  1454. return AVERROR_INVALIDDATA;
  1455. }
  1456. } else {
  1457. int field = h->picture_structure == PICT_BOTTOM_FIELD;
  1458. release_unused_pictures(h, 0);
  1459. h->cur_pic_ptr->tf.owner[field] = h->avctx;
  1460. }
  1461. /* Some macroblocks can be accessed before they're available in case
  1462. * of lost slices, MBAFF or threading. */
  1463. if (FIELD_PICTURE(h)) {
  1464. for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
  1465. memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
  1466. } else {
  1467. memset(h->slice_table, -1,
  1468. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1469. }
  1470. ret = ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
  1471. h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
  1472. if (ret < 0)
  1473. return ret;
  1474. memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
  1475. h->nb_mmco = sl->nb_mmco;
  1476. h->explicit_ref_marking = sl->explicit_ref_marking;
  1477. h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
  1478. if (h->sei.recovery_point.recovery_frame_cnt >= 0) {
  1479. const int sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  1480. if (h->poc.frame_num != sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  1481. h->valid_recovery_point = 1;
  1482. if ( h->recovery_frame < 0
  1483. || av_mod_uintp2(h->recovery_frame - h->poc.frame_num, h->ps.sps->log2_max_frame_num) > sei_recovery_frame_cnt) {
  1484. h->recovery_frame = av_mod_uintp2(h->poc.frame_num + sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
  1485. if (!h->valid_recovery_point)
  1486. h->recovery_frame = h->poc.frame_num;
  1487. }
  1488. }
  1489. h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE);
  1490. if (nal->type == H264_NAL_IDR_SLICE ||
  1491. (h->recovery_frame == h->poc.frame_num && nal->ref_idc)) {
  1492. h->recovery_frame = -1;
  1493. h->cur_pic_ptr->recovered = 1;
  1494. }
  1495. // If we have an IDR, all frames after it in decoded order are
  1496. // "recovered".
  1497. if (nal->type == H264_NAL_IDR_SLICE)
  1498. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1499. #if 1
  1500. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1501. #else
  1502. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1503. #endif
  1504. /* Set the frame properties/side data. Only done for the second field in
  1505. * field coded frames, since some SEI information is present for each field
  1506. * and is merged by the SEI parsing code. */
  1507. if (!FIELD_PICTURE(h) || !h->first_field || h->missing_fields > 1) {
  1508. ret = h264_export_frame_props(h);
  1509. if (ret < 0)
  1510. return ret;
  1511. ret = h264_select_output_frame(h);
  1512. if (ret < 0)
  1513. return ret;
  1514. }
  1515. return 0;
  1516. }
  1517. static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
  1518. const H2645NAL *nal)
  1519. {
  1520. const SPS *sps;
  1521. const PPS *pps;
  1522. int ret;
  1523. unsigned int slice_type, tmp, i;
  1524. int field_pic_flag, bottom_field_flag;
  1525. int first_slice = sl == h->slice_ctx && !h->current_slice;
  1526. int picture_structure;
  1527. if (first_slice)
  1528. av_assert0(!h->setup_finished);
  1529. sl->first_mb_addr = get_ue_golomb_long(&sl->gb);
  1530. slice_type = get_ue_golomb_31(&sl->gb);
  1531. if (slice_type > 9) {
  1532. av_log(h->avctx, AV_LOG_ERROR,
  1533. "slice type %d too large at %d\n",
  1534. slice_type, sl->first_mb_addr);
  1535. return AVERROR_INVALIDDATA;
  1536. }
  1537. if (slice_type > 4) {
  1538. slice_type -= 5;
  1539. sl->slice_type_fixed = 1;
  1540. } else
  1541. sl->slice_type_fixed = 0;
  1542. slice_type = ff_h264_golomb_to_pict_type[slice_type];
  1543. sl->slice_type = slice_type;
  1544. sl->slice_type_nos = slice_type & 3;
  1545. if (nal->type == H264_NAL_IDR_SLICE &&
  1546. sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1547. av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
  1548. return AVERROR_INVALIDDATA;
  1549. }
  1550. sl->pps_id = get_ue_golomb(&sl->gb);
  1551. if (sl->pps_id >= MAX_PPS_COUNT) {
  1552. av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
  1553. return AVERROR_INVALIDDATA;
  1554. }
  1555. if (!h->ps.pps_list[sl->pps_id]) {
  1556. av_log(h->avctx, AV_LOG_ERROR,
  1557. "non-existing PPS %u referenced\n",
  1558. sl->pps_id);
  1559. return AVERROR_INVALIDDATA;
  1560. }
  1561. pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
  1562. if (!h->ps.sps_list[pps->sps_id]) {
  1563. av_log(h->avctx, AV_LOG_ERROR,
  1564. "non-existing SPS %u referenced\n", pps->sps_id);
  1565. return AVERROR_INVALIDDATA;
  1566. }
  1567. sps = (const SPS*)h->ps.sps_list[pps->sps_id]->data;
  1568. sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
  1569. if (!first_slice) {
  1570. if (h->poc.frame_num != sl->frame_num) {
  1571. av_log(h->avctx, AV_LOG_ERROR, "Frame num change from %d to %d\n",
  1572. h->poc.frame_num, sl->frame_num);
  1573. return AVERROR_INVALIDDATA;
  1574. }
  1575. }
  1576. sl->mb_mbaff = 0;
  1577. if (sps->frame_mbs_only_flag) {
  1578. picture_structure = PICT_FRAME;
  1579. } else {
  1580. if (!sps->direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  1581. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  1582. return -1;
  1583. }
  1584. field_pic_flag = get_bits1(&sl->gb);
  1585. if (field_pic_flag) {
  1586. bottom_field_flag = get_bits1(&sl->gb);
  1587. picture_structure = PICT_TOP_FIELD + bottom_field_flag;
  1588. } else {
  1589. picture_structure = PICT_FRAME;
  1590. }
  1591. }
  1592. sl->picture_structure = picture_structure;
  1593. sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
  1594. if (picture_structure == PICT_FRAME) {
  1595. sl->curr_pic_num = sl->frame_num;
  1596. sl->max_pic_num = 1 << sps->log2_max_frame_num;
  1597. } else {
  1598. sl->curr_pic_num = 2 * sl->frame_num + 1;
  1599. sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
  1600. }
  1601. if (nal->type == H264_NAL_IDR_SLICE)
  1602. get_ue_golomb_long(&sl->gb); /* idr_pic_id */
  1603. if (sps->poc_type == 0) {
  1604. sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
  1605. if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
  1606. sl->delta_poc_bottom = get_se_golomb(&sl->gb);
  1607. }
  1608. if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
  1609. sl->delta_poc[0] = get_se_golomb(&sl->gb);
  1610. if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
  1611. sl->delta_poc[1] = get_se_golomb(&sl->gb);
  1612. }
  1613. sl->redundant_pic_count = 0;
  1614. if (pps->redundant_pic_cnt_present)
  1615. sl->redundant_pic_count = get_ue_golomb(&sl->gb);
  1616. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1617. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1618. ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
  1619. &sl->gb, pps, sl->slice_type_nos,
  1620. picture_structure, h->avctx);
  1621. if (ret < 0)
  1622. return ret;
  1623. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1624. ret = ff_h264_decode_ref_pic_list_reordering(sl, h->avctx);
  1625. if (ret < 0) {
  1626. sl->ref_count[1] = sl->ref_count[0] = 0;
  1627. return ret;
  1628. }
  1629. }
  1630. sl->pwt.use_weight = 0;
  1631. for (i = 0; i < 2; i++) {
  1632. sl->pwt.luma_weight_flag[i] = 0;
  1633. sl->pwt.chroma_weight_flag[i] = 0;
  1634. }
  1635. if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
  1636. (pps->weighted_bipred_idc == 1 &&
  1637. sl->slice_type_nos == AV_PICTURE_TYPE_B)) {
  1638. ret = ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
  1639. sl->slice_type_nos, &sl->pwt,
  1640. picture_structure, h->avctx);
  1641. if (ret < 0)
  1642. return ret;
  1643. }
  1644. sl->explicit_ref_marking = 0;
  1645. if (nal->ref_idc) {
  1646. ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, h->avctx);
  1647. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1648. return AVERROR_INVALIDDATA;
  1649. }
  1650. if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
  1651. tmp = get_ue_golomb_31(&sl->gb);
  1652. if (tmp > 2) {
  1653. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
  1654. return AVERROR_INVALIDDATA;
  1655. }
  1656. sl->cabac_init_idc = tmp;
  1657. }
  1658. sl->last_qscale_diff = 0;
  1659. tmp = pps->init_qp + (unsigned)get_se_golomb(&sl->gb);
  1660. if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
  1661. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  1662. return AVERROR_INVALIDDATA;
  1663. }
  1664. sl->qscale = tmp;
  1665. sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
  1666. sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
  1667. // FIXME qscale / qp ... stuff
  1668. if (sl->slice_type == AV_PICTURE_TYPE_SP)
  1669. get_bits1(&sl->gb); /* sp_for_switch_flag */
  1670. if (sl->slice_type == AV_PICTURE_TYPE_SP ||
  1671. sl->slice_type == AV_PICTURE_TYPE_SI)
  1672. get_se_golomb(&sl->gb); /* slice_qs_delta */
  1673. sl->deblocking_filter = 1;
  1674. sl->slice_alpha_c0_offset = 0;
  1675. sl->slice_beta_offset = 0;
  1676. if (pps->deblocking_filter_parameters_present) {
  1677. tmp = get_ue_golomb_31(&sl->gb);
  1678. if (tmp > 2) {
  1679. av_log(h->avctx, AV_LOG_ERROR,
  1680. "deblocking_filter_idc %u out of range\n", tmp);
  1681. return AVERROR_INVALIDDATA;
  1682. }
  1683. sl->deblocking_filter = tmp;
  1684. if (sl->deblocking_filter < 2)
  1685. sl->deblocking_filter ^= 1; // 1<->0
  1686. if (sl->deblocking_filter) {
  1687. int slice_alpha_c0_offset_div2 = get_se_golomb(&sl->gb);
  1688. int slice_beta_offset_div2 = get_se_golomb(&sl->gb);
  1689. if (slice_alpha_c0_offset_div2 > 6 ||
  1690. slice_alpha_c0_offset_div2 < -6 ||
  1691. slice_beta_offset_div2 > 6 ||
  1692. slice_beta_offset_div2 < -6) {
  1693. av_log(h->avctx, AV_LOG_ERROR,
  1694. "deblocking filter parameters %d %d out of range\n",
  1695. slice_alpha_c0_offset_div2, slice_beta_offset_div2);
  1696. return AVERROR_INVALIDDATA;
  1697. }
  1698. sl->slice_alpha_c0_offset = slice_alpha_c0_offset_div2 * 2;
  1699. sl->slice_beta_offset = slice_beta_offset_div2 * 2;
  1700. }
  1701. }
  1702. return 0;
  1703. }
  1704. /* do all the per-slice initialization needed before we can start decoding the
  1705. * actual MBs */
  1706. static int h264_slice_init(H264Context *h, H264SliceContext *sl,
  1707. const H2645NAL *nal)
  1708. {
  1709. int i, j, ret = 0;
  1710. if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
  1711. av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
  1712. return AVERROR_INVALIDDATA;
  1713. }
  1714. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  1715. if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
  1716. sl->first_mb_addr >= h->mb_num) {
  1717. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  1718. return AVERROR_INVALIDDATA;
  1719. }
  1720. sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
  1721. sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
  1722. FIELD_OR_MBAFF_PICTURE(h);
  1723. if (h->picture_structure == PICT_BOTTOM_FIELD)
  1724. sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
  1725. av_assert1(sl->mb_y < h->mb_height);
  1726. ret = ff_h264_build_ref_list(h, sl);
  1727. if (ret < 0)
  1728. return ret;
  1729. if (h->ps.pps->weighted_bipred_idc == 2 &&
  1730. sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1731. implicit_weight_table(h, sl, -1);
  1732. if (FRAME_MBAFF(h)) {
  1733. implicit_weight_table(h, sl, 0);
  1734. implicit_weight_table(h, sl, 1);
  1735. }
  1736. }
  1737. if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
  1738. ff_h264_direct_dist_scale_factor(h, sl);
  1739. if (!h->setup_finished)
  1740. ff_h264_direct_ref_list_init(h, sl);
  1741. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  1742. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  1743. h->nal_unit_type != H264_NAL_IDR_SLICE) ||
  1744. (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&
  1745. sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
  1746. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  1747. sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
  1748. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  1749. nal->ref_idc == 0))
  1750. sl->deblocking_filter = 0;
  1751. if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
  1752. if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
  1753. /* Cheat slightly for speed:
  1754. * Do not bother to deblock across slices. */
  1755. sl->deblocking_filter = 2;
  1756. } else {
  1757. h->postpone_filter = 1;
  1758. }
  1759. }
  1760. sl->qp_thresh = 15 -
  1761. FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
  1762. FFMAX3(0,
  1763. h->ps.pps->chroma_qp_index_offset[0],
  1764. h->ps.pps->chroma_qp_index_offset[1]) +
  1765. 6 * (h->ps.sps->bit_depth_luma - 8);
  1766. sl->slice_num = ++h->current_slice;
  1767. if (sl->slice_num)
  1768. h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;
  1769. if ( h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y
  1770. && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y
  1771. && sl->slice_num >= MAX_SLICES) {
  1772. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  1773. av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);
  1774. }
  1775. for (j = 0; j < 2; j++) {
  1776. int id_list[16];
  1777. int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
  1778. for (i = 0; i < 16; i++) {
  1779. id_list[i] = 60;
  1780. if (j < sl->list_count && i < sl->ref_count[j] &&
  1781. sl->ref_list[j][i].parent->f->buf[0]) {
  1782. int k;
  1783. AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
  1784. for (k = 0; k < h->short_ref_count; k++)
  1785. if (h->short_ref[k]->f->buf[0]->buffer == buf) {
  1786. id_list[i] = k;
  1787. break;
  1788. }
  1789. for (k = 0; k < h->long_ref_count; k++)
  1790. if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
  1791. id_list[i] = h->short_ref_count + k;
  1792. break;
  1793. }
  1794. }
  1795. }
  1796. ref2frm[0] =
  1797. ref2frm[1] = -1;
  1798. for (i = 0; i < 16; i++)
  1799. ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
  1800. ref2frm[18 + 0] =
  1801. ref2frm[18 + 1] = -1;
  1802. for (i = 16; i < 48; i++)
  1803. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  1804. (sl->ref_list[j][i].reference & 3);
  1805. }
  1806. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  1807. av_log(h->avctx, AV_LOG_DEBUG,
  1808. "slice:%d %s mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  1809. sl->slice_num,
  1810. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  1811. sl->mb_y * h->mb_width + sl->mb_x,
  1812. av_get_picture_type_char(sl->slice_type),
  1813. sl->slice_type_fixed ? " fix" : "",
  1814. nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
  1815. h->poc.frame_num,
  1816. h->cur_pic_ptr->field_poc[0],
  1817. h->cur_pic_ptr->field_poc[1],
  1818. sl->ref_count[0], sl->ref_count[1],
  1819. sl->qscale,
  1820. sl->deblocking_filter,
  1821. sl->slice_alpha_c0_offset, sl->slice_beta_offset,
  1822. sl->pwt.use_weight,
  1823. sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
  1824. sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  1825. }
  1826. return 0;
  1827. }
  1828. int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
  1829. {
  1830. H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
  1831. int first_slice = sl == h->slice_ctx && !h->current_slice;
  1832. int ret;
  1833. sl->gb = nal->gb;
  1834. ret = h264_slice_header_parse(h, sl, nal);
  1835. if (ret < 0)
  1836. return ret;
  1837. // discard redundant pictures
  1838. if (sl->redundant_pic_count > 0) {
  1839. sl->ref_count[0] = sl->ref_count[1] = 0;
  1840. return 0;
  1841. }
  1842. if (sl->first_mb_addr == 0 || !h->current_slice) {
  1843. if (h->setup_finished) {
  1844. av_log(h->avctx, AV_LOG_ERROR, "Too many fields\n");
  1845. return AVERROR_INVALIDDATA;
  1846. }
  1847. }
  1848. if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
  1849. if (h->current_slice) {
  1850. // this slice starts a new field
  1851. // first decode any pending queued slices
  1852. if (h->nb_slice_ctx_queued) {
  1853. H264SliceContext tmp_ctx;
  1854. ret = ff_h264_execute_decode_slices(h);
  1855. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1856. return ret;
  1857. memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
  1858. memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
  1859. memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
  1860. sl = h->slice_ctx;
  1861. }
  1862. if (h->cur_pic_ptr && FIELD_PICTURE(h) && h->first_field) {
  1863. ret = ff_h264_field_end(h, h->slice_ctx, 1);
  1864. if (ret < 0)
  1865. return ret;
  1866. } else if (h->cur_pic_ptr && !FIELD_PICTURE(h) && !h->first_field && h->nal_unit_type == H264_NAL_IDR_SLICE) {
  1867. av_log(h, AV_LOG_WARNING, "Broken frame packetizing\n");
  1868. ret = ff_h264_field_end(h, h->slice_ctx, 1);
  1869. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  1870. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  1871. h->cur_pic_ptr = NULL;
  1872. if (ret < 0)
  1873. return ret;
  1874. } else
  1875. return AVERROR_INVALIDDATA;
  1876. }
  1877. if (!h->first_field) {
  1878. if (h->cur_pic_ptr && !h->droppable) {
  1879. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1880. h->picture_structure == PICT_BOTTOM_FIELD);
  1881. }
  1882. h->cur_pic_ptr = NULL;
  1883. }
  1884. }
  1885. if (!h->current_slice)
  1886. av_assert0(sl == h->slice_ctx);
  1887. if (h->current_slice == 0 && !h->first_field) {
  1888. if (
  1889. (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||
  1890. (h->avctx->skip_frame >= AVDISCARD_BIDIR && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
  1891. (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
  1892. (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != H264_NAL_IDR_SLICE && h->sei.recovery_point.recovery_frame_cnt < 0) ||
  1893. h->avctx->skip_frame >= AVDISCARD_ALL) {
  1894. return 0;
  1895. }
  1896. }
  1897. if (!first_slice) {
  1898. const PPS *pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
  1899. if (h->ps.pps->sps_id != pps->sps_id ||
  1900. h->ps.pps->transform_8x8_mode != pps->transform_8x8_mode /*||
  1901. (h->setup_finished && h->ps.pps != pps)*/) {
  1902. av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
  1903. return AVERROR_INVALIDDATA;
  1904. }
  1905. if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
  1906. av_log(h->avctx, AV_LOG_ERROR,
  1907. "SPS changed in the middle of the frame\n");
  1908. return AVERROR_INVALIDDATA;
  1909. }
  1910. }
  1911. if (h->current_slice == 0) {
  1912. ret = h264_field_start(h, sl, nal, first_slice);
  1913. if (ret < 0)
  1914. return ret;
  1915. } else {
  1916. if (h->picture_structure != sl->picture_structure ||
  1917. h->droppable != (nal->ref_idc == 0)) {
  1918. av_log(h->avctx, AV_LOG_ERROR,
  1919. "Changing field mode (%d -> %d) between slices is not allowed\n",
  1920. h->picture_structure, sl->picture_structure);
  1921. return AVERROR_INVALIDDATA;
  1922. } else if (!h->cur_pic_ptr) {
  1923. av_log(h->avctx, AV_LOG_ERROR,
  1924. "unset cur_pic_ptr on slice %d\n",
  1925. h->current_slice + 1);
  1926. return AVERROR_INVALIDDATA;
  1927. }
  1928. }
  1929. ret = h264_slice_init(h, sl, nal);
  1930. if (ret < 0)
  1931. return ret;
  1932. h->nb_slice_ctx_queued++;
  1933. return 0;
  1934. }
  1935. int ff_h264_get_slice_type(const H264SliceContext *sl)
  1936. {
  1937. switch (sl->slice_type) {
  1938. case AV_PICTURE_TYPE_P:
  1939. return 0;
  1940. case AV_PICTURE_TYPE_B:
  1941. return 1;
  1942. case AV_PICTURE_TYPE_I:
  1943. return 2;
  1944. case AV_PICTURE_TYPE_SP:
  1945. return 3;
  1946. case AV_PICTURE_TYPE_SI:
  1947. return 4;
  1948. default:
  1949. return AVERROR_INVALIDDATA;
  1950. }
  1951. }
  1952. static av_always_inline void fill_filter_caches_inter(const H264Context *h,
  1953. H264SliceContext *sl,
  1954. int mb_type, int top_xy,
  1955. int left_xy[LEFT_MBS],
  1956. int top_type,
  1957. int left_type[LEFT_MBS],
  1958. int mb_xy, int list)
  1959. {
  1960. int b_stride = h->b_stride;
  1961. int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
  1962. int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
  1963. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  1964. if (USES_LIST(top_type, list)) {
  1965. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  1966. const int b8_xy = 4 * top_xy + 2;
  1967. const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  1968. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
  1969. ref_cache[0 - 1 * 8] =
  1970. ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
  1971. ref_cache[2 - 1 * 8] =
  1972. ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
  1973. } else {
  1974. AV_ZERO128(mv_dst - 1 * 8);
  1975. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1976. }
  1977. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  1978. if (USES_LIST(left_type[LTOP], list)) {
  1979. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  1980. const int b8_xy = 4 * left_xy[LTOP] + 1;
  1981. const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  1982. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
  1983. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
  1984. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
  1985. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
  1986. ref_cache[-1 + 0] =
  1987. ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
  1988. ref_cache[-1 + 16] =
  1989. ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
  1990. } else {
  1991. AV_ZERO32(mv_dst - 1 + 0);
  1992. AV_ZERO32(mv_dst - 1 + 8);
  1993. AV_ZERO32(mv_dst - 1 + 16);
  1994. AV_ZERO32(mv_dst - 1 + 24);
  1995. ref_cache[-1 + 0] =
  1996. ref_cache[-1 + 8] =
  1997. ref_cache[-1 + 16] =
  1998. ref_cache[-1 + 24] = LIST_NOT_USED;
  1999. }
  2000. }
  2001. }
  2002. if (!USES_LIST(mb_type, list)) {
  2003. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  2004. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2005. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2006. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2007. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2008. return;
  2009. }
  2010. {
  2011. int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
  2012. const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  2013. uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
  2014. uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
  2015. AV_WN32A(&ref_cache[0 * 8], ref01);
  2016. AV_WN32A(&ref_cache[1 * 8], ref01);
  2017. AV_WN32A(&ref_cache[2 * 8], ref23);
  2018. AV_WN32A(&ref_cache[3 * 8], ref23);
  2019. }
  2020. {
  2021. int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
  2022. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  2023. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  2024. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  2025. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  2026. }
  2027. }
  2028. /**
  2029. * @return non zero if the loop filter can be skipped
  2030. */
  2031. static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
  2032. {
  2033. const int mb_xy = sl->mb_xy;
  2034. int top_xy, left_xy[LEFT_MBS];
  2035. int top_type, left_type[LEFT_MBS];
  2036. uint8_t *nnz;
  2037. uint8_t *nnz_cache;
  2038. top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
  2039. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  2040. if (FRAME_MBAFF(h)) {
  2041. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
  2042. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2043. if (sl->mb_y & 1) {
  2044. if (left_mb_field_flag != curr_mb_field_flag)
  2045. left_xy[LTOP] -= h->mb_stride;
  2046. } else {
  2047. if (curr_mb_field_flag)
  2048. top_xy += h->mb_stride &
  2049. (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
  2050. if (left_mb_field_flag != curr_mb_field_flag)
  2051. left_xy[LBOT] += h->mb_stride;
  2052. }
  2053. }
  2054. sl->top_mb_xy = top_xy;
  2055. sl->left_mb_xy[LTOP] = left_xy[LTOP];
  2056. sl->left_mb_xy[LBOT] = left_xy[LBOT];
  2057. {
  2058. /* For sufficiently low qp, filtering wouldn't do anything.
  2059. * This is a conservative estimate: could also check beta_offset
  2060. * and more accurate chroma_qp. */
  2061. int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  2062. int qp = h->cur_pic.qscale_table[mb_xy];
  2063. if (qp <= qp_thresh &&
  2064. (left_xy[LTOP] < 0 ||
  2065. ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  2066. (top_xy < 0 ||
  2067. ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  2068. if (!FRAME_MBAFF(h))
  2069. return 1;
  2070. if ((left_xy[LTOP] < 0 ||
  2071. ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  2072. (top_xy < h->mb_stride ||
  2073. ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  2074. return 1;
  2075. }
  2076. }
  2077. top_type = h->cur_pic.mb_type[top_xy];
  2078. left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
  2079. left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
  2080. if (sl->deblocking_filter == 2) {
  2081. if (h->slice_table[top_xy] != sl->slice_num)
  2082. top_type = 0;
  2083. if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
  2084. left_type[LTOP] = left_type[LBOT] = 0;
  2085. } else {
  2086. if (h->slice_table[top_xy] == 0xFFFF)
  2087. top_type = 0;
  2088. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  2089. left_type[LTOP] = left_type[LBOT] = 0;
  2090. }
  2091. sl->top_type = top_type;
  2092. sl->left_type[LTOP] = left_type[LTOP];
  2093. sl->left_type[LBOT] = left_type[LBOT];
  2094. if (IS_INTRA(mb_type))
  2095. return 0;
  2096. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  2097. top_type, left_type, mb_xy, 0);
  2098. if (sl->list_count == 2)
  2099. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  2100. top_type, left_type, mb_xy, 1);
  2101. nnz = h->non_zero_count[mb_xy];
  2102. nnz_cache = sl->non_zero_count_cache;
  2103. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  2104. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  2105. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  2106. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  2107. sl->cbp = h->cbp_table[mb_xy];
  2108. if (top_type) {
  2109. nnz = h->non_zero_count[top_xy];
  2110. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  2111. }
  2112. if (left_type[LTOP]) {
  2113. nnz = h->non_zero_count[left_xy[LTOP]];
  2114. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  2115. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  2116. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  2117. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  2118. }
  2119. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  2120. * from what the loop filter needs */
  2121. if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
  2122. if (IS_8x8DCT(top_type)) {
  2123. nnz_cache[4 + 8 * 0] =
  2124. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  2125. nnz_cache[6 + 8 * 0] =
  2126. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  2127. }
  2128. if (IS_8x8DCT(left_type[LTOP])) {
  2129. nnz_cache[3 + 8 * 1] =
  2130. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  2131. }
  2132. if (IS_8x8DCT(left_type[LBOT])) {
  2133. nnz_cache[3 + 8 * 3] =
  2134. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  2135. }
  2136. if (IS_8x8DCT(mb_type)) {
  2137. nnz_cache[scan8[0]] =
  2138. nnz_cache[scan8[1]] =
  2139. nnz_cache[scan8[2]] =
  2140. nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
  2141. nnz_cache[scan8[0 + 4]] =
  2142. nnz_cache[scan8[1 + 4]] =
  2143. nnz_cache[scan8[2 + 4]] =
  2144. nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
  2145. nnz_cache[scan8[0 + 8]] =
  2146. nnz_cache[scan8[1 + 8]] =
  2147. nnz_cache[scan8[2 + 8]] =
  2148. nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
  2149. nnz_cache[scan8[0 + 12]] =
  2150. nnz_cache[scan8[1 + 12]] =
  2151. nnz_cache[scan8[2 + 12]] =
  2152. nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
  2153. }
  2154. }
  2155. return 0;
  2156. }
  2157. static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
  2158. {
  2159. uint8_t *dest_y, *dest_cb, *dest_cr;
  2160. int linesize, uvlinesize, mb_x, mb_y;
  2161. const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
  2162. const int old_slice_type = sl->slice_type;
  2163. const int pixel_shift = h->pixel_shift;
  2164. const int block_h = 16 >> h->chroma_y_shift;
  2165. if (h->postpone_filter)
  2166. return;
  2167. if (sl->deblocking_filter) {
  2168. for (mb_x = start_x; mb_x < end_x; mb_x++)
  2169. for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
  2170. int mb_xy, mb_type;
  2171. mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
  2172. mb_type = h->cur_pic.mb_type[mb_xy];
  2173. if (FRAME_MBAFF(h))
  2174. sl->mb_mbaff =
  2175. sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2176. sl->mb_x = mb_x;
  2177. sl->mb_y = mb_y;
  2178. dest_y = h->cur_pic.f->data[0] +
  2179. ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
  2180. dest_cb = h->cur_pic.f->data[1] +
  2181. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  2182. mb_y * sl->uvlinesize * block_h;
  2183. dest_cr = h->cur_pic.f->data[2] +
  2184. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  2185. mb_y * sl->uvlinesize * block_h;
  2186. // FIXME simplify above
  2187. if (MB_FIELD(sl)) {
  2188. linesize = sl->mb_linesize = sl->linesize * 2;
  2189. uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
  2190. if (mb_y & 1) { // FIXME move out of this function?
  2191. dest_y -= sl->linesize * 15;
  2192. dest_cb -= sl->uvlinesize * (block_h - 1);
  2193. dest_cr -= sl->uvlinesize * (block_h - 1);
  2194. }
  2195. } else {
  2196. linesize = sl->mb_linesize = sl->linesize;
  2197. uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
  2198. }
  2199. backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
  2200. uvlinesize, 0);
  2201. if (fill_filter_caches(h, sl, mb_type))
  2202. continue;
  2203. sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
  2204. sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
  2205. if (FRAME_MBAFF(h)) {
  2206. ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  2207. linesize, uvlinesize);
  2208. } else {
  2209. ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
  2210. dest_cr, linesize, uvlinesize);
  2211. }
  2212. }
  2213. }
  2214. sl->slice_type = old_slice_type;
  2215. sl->mb_x = end_x;
  2216. sl->mb_y = end_mb_y - FRAME_MBAFF(h);
  2217. sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
  2218. sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
  2219. }
  2220. static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
  2221. {
  2222. const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
  2223. int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
  2224. h->cur_pic.mb_type[mb_xy - 1] :
  2225. (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
  2226. h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
  2227. sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2228. }
  2229. /**
  2230. * Draw edges and report progress for the last MB row.
  2231. */
  2232. static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
  2233. {
  2234. int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
  2235. int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
  2236. int height = 16 << FRAME_MBAFF(h);
  2237. int deblock_border = (16 + 4) << FRAME_MBAFF(h);
  2238. if (sl->deblocking_filter) {
  2239. if ((top + height) >= pic_height)
  2240. height += deblock_border;
  2241. top -= deblock_border;
  2242. }
  2243. if (top >= pic_height || (top + height) < 0)
  2244. return;
  2245. height = FFMIN(height, pic_height - top);
  2246. if (top < 0) {
  2247. height = top + height;
  2248. top = 0;
  2249. }
  2250. ff_h264_draw_horiz_band(h, sl, top, height);
  2251. if (h->droppable || sl->h264->slice_ctx[0].er.error_occurred)
  2252. return;
  2253. ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
  2254. h->picture_structure == PICT_BOTTOM_FIELD);
  2255. }
  2256. static void er_add_slice(H264SliceContext *sl,
  2257. int startx, int starty,
  2258. int endx, int endy, int status)
  2259. {
  2260. if (!sl->h264->enable_er)
  2261. return;
  2262. if (CONFIG_ERROR_RESILIENCE) {
  2263. ERContext *er = &sl->h264->slice_ctx[0].er;
  2264. ff_er_add_slice(er, startx, starty, endx, endy, status);
  2265. }
  2266. }
  2267. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  2268. {
  2269. H264SliceContext *sl = arg;
  2270. const H264Context *h = sl->h264;
  2271. int lf_x_start = sl->mb_x;
  2272. int orig_deblock = sl->deblocking_filter;
  2273. int ret;
  2274. sl->linesize = h->cur_pic_ptr->f->linesize[0];
  2275. sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
  2276. ret = alloc_scratch_buffers(sl, sl->linesize);
  2277. if (ret < 0)
  2278. return ret;
  2279. sl->mb_skip_run = -1;
  2280. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * sl->linesize * ((scan8[15] - scan8[0]) >> 3));
  2281. if (h->postpone_filter)
  2282. sl->deblocking_filter = 0;
  2283. sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
  2284. (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
  2285. if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->slice_ctx[0].er.error_status_table) {
  2286. const int start_i = av_clip(sl->resync_mb_x + sl->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
  2287. if (start_i) {
  2288. int prev_status = h->slice_ctx[0].er.error_status_table[h->slice_ctx[0].er.mb_index2xy[start_i - 1]];
  2289. prev_status &= ~ VP_START;
  2290. if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
  2291. h->slice_ctx[0].er.error_occurred = 1;
  2292. }
  2293. }
  2294. if (h->ps.pps->cabac) {
  2295. /* realign */
  2296. align_get_bits(&sl->gb);
  2297. /* init cabac */
  2298. ret = ff_init_cabac_decoder(&sl->cabac,
  2299. sl->gb.buffer + get_bits_count(&sl->gb) / 8,
  2300. (get_bits_left(&sl->gb) + 7) / 8);
  2301. if (ret < 0)
  2302. return ret;
  2303. ff_h264_init_cabac_states(h, sl);
  2304. for (;;) {
  2305. // START_TIMER
  2306. int ret, eos;
  2307. if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
  2308. av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
  2309. sl->next_slice_idx);
  2310. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2311. sl->mb_y, ER_MB_ERROR);
  2312. return AVERROR_INVALIDDATA;
  2313. }
  2314. ret = ff_h264_decode_mb_cabac(h, sl);
  2315. // STOP_TIMER("decode_mb_cabac")
  2316. if (ret >= 0)
  2317. ff_h264_hl_decode_mb(h, sl);
  2318. // FIXME optimal? or let mb_decode decode 16x32 ?
  2319. if (ret >= 0 && FRAME_MBAFF(h)) {
  2320. sl->mb_y++;
  2321. ret = ff_h264_decode_mb_cabac(h, sl);
  2322. if (ret >= 0)
  2323. ff_h264_hl_decode_mb(h, sl);
  2324. sl->mb_y--;
  2325. }
  2326. eos = get_cabac_terminate(&sl->cabac);
  2327. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  2328. sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
  2329. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
  2330. sl->mb_y, ER_MB_END);
  2331. if (sl->mb_x >= lf_x_start)
  2332. loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
  2333. goto finish;
  2334. }
  2335. if (sl->cabac.bytestream > sl->cabac.bytestream_end + 2 )
  2336. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %"PTRDIFF_SPECIFIER"\n", sl->cabac.bytestream_end - sl->cabac.bytestream);
  2337. if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 4) {
  2338. av_log(h->avctx, AV_LOG_ERROR,
  2339. "error while decoding MB %d %d, bytestream %"PTRDIFF_SPECIFIER"\n",
  2340. sl->mb_x, sl->mb_y,
  2341. sl->cabac.bytestream_end - sl->cabac.bytestream);
  2342. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2343. sl->mb_y, ER_MB_ERROR);
  2344. return AVERROR_INVALIDDATA;
  2345. }
  2346. if (++sl->mb_x >= h->mb_width) {
  2347. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2348. sl->mb_x = lf_x_start = 0;
  2349. decode_finish_row(h, sl);
  2350. ++sl->mb_y;
  2351. if (FIELD_OR_MBAFF_PICTURE(h)) {
  2352. ++sl->mb_y;
  2353. if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
  2354. predict_field_decoding_flag(h, sl);
  2355. }
  2356. }
  2357. if (eos || sl->mb_y >= h->mb_height) {
  2358. ff_tlog(h->avctx, "slice end %d %d\n",
  2359. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2360. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
  2361. sl->mb_y, ER_MB_END);
  2362. if (sl->mb_x > lf_x_start)
  2363. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2364. goto finish;
  2365. }
  2366. }
  2367. } else {
  2368. for (;;) {
  2369. int ret;
  2370. if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
  2371. av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
  2372. sl->next_slice_idx);
  2373. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2374. sl->mb_y, ER_MB_ERROR);
  2375. return AVERROR_INVALIDDATA;
  2376. }
  2377. ret = ff_h264_decode_mb_cavlc(h, sl);
  2378. if (ret >= 0)
  2379. ff_h264_hl_decode_mb(h, sl);
  2380. // FIXME optimal? or let mb_decode decode 16x32 ?
  2381. if (ret >= 0 && FRAME_MBAFF(h)) {
  2382. sl->mb_y++;
  2383. ret = ff_h264_decode_mb_cavlc(h, sl);
  2384. if (ret >= 0)
  2385. ff_h264_hl_decode_mb(h, sl);
  2386. sl->mb_y--;
  2387. }
  2388. if (ret < 0) {
  2389. av_log(h->avctx, AV_LOG_ERROR,
  2390. "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
  2391. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2392. sl->mb_y, ER_MB_ERROR);
  2393. return ret;
  2394. }
  2395. if (++sl->mb_x >= h->mb_width) {
  2396. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2397. sl->mb_x = lf_x_start = 0;
  2398. decode_finish_row(h, sl);
  2399. ++sl->mb_y;
  2400. if (FIELD_OR_MBAFF_PICTURE(h)) {
  2401. ++sl->mb_y;
  2402. if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
  2403. predict_field_decoding_flag(h, sl);
  2404. }
  2405. if (sl->mb_y >= h->mb_height) {
  2406. ff_tlog(h->avctx, "slice end %d %d\n",
  2407. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2408. if ( get_bits_left(&sl->gb) == 0
  2409. || get_bits_left(&sl->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  2410. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2411. sl->mb_x - 1, sl->mb_y, ER_MB_END);
  2412. goto finish;
  2413. } else {
  2414. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2415. sl->mb_x, sl->mb_y, ER_MB_END);
  2416. return AVERROR_INVALIDDATA;
  2417. }
  2418. }
  2419. }
  2420. if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
  2421. ff_tlog(h->avctx, "slice end %d %d\n",
  2422. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2423. if (get_bits_left(&sl->gb) == 0) {
  2424. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2425. sl->mb_x - 1, sl->mb_y, ER_MB_END);
  2426. if (sl->mb_x > lf_x_start)
  2427. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2428. goto finish;
  2429. } else {
  2430. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2431. sl->mb_y, ER_MB_ERROR);
  2432. return AVERROR_INVALIDDATA;
  2433. }
  2434. }
  2435. }
  2436. }
  2437. finish:
  2438. sl->deblocking_filter = orig_deblock;
  2439. return 0;
  2440. }
  2441. /**
  2442. * Call decode_slice() for each context.
  2443. *
  2444. * @param h h264 master context
  2445. */
  2446. int ff_h264_execute_decode_slices(H264Context *h)
  2447. {
  2448. AVCodecContext *const avctx = h->avctx;
  2449. H264SliceContext *sl;
  2450. int context_count = h->nb_slice_ctx_queued;
  2451. int ret = 0;
  2452. int i, j;
  2453. h->slice_ctx[0].next_slice_idx = INT_MAX;
  2454. if (h->avctx->hwaccel || context_count < 1)
  2455. return 0;
  2456. av_assert0(context_count && h->slice_ctx[context_count - 1].mb_y < h->mb_height);
  2457. if (context_count == 1) {
  2458. h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
  2459. h->postpone_filter = 0;
  2460. ret = decode_slice(avctx, &h->slice_ctx[0]);
  2461. h->mb_y = h->slice_ctx[0].mb_y;
  2462. if (ret < 0)
  2463. goto finish;
  2464. } else {
  2465. av_assert0(context_count > 0);
  2466. for (i = 0; i < context_count; i++) {
  2467. int next_slice_idx = h->mb_width * h->mb_height;
  2468. int slice_idx;
  2469. sl = &h->slice_ctx[i];
  2470. if (CONFIG_ERROR_RESILIENCE) {
  2471. sl->er.error_count = 0;
  2472. }
  2473. /* make sure none of those slices overlap */
  2474. slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
  2475. for (j = 0; j < context_count; j++) {
  2476. H264SliceContext *sl2 = &h->slice_ctx[j];
  2477. int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
  2478. if (i == j || slice_idx2 < slice_idx)
  2479. continue;
  2480. next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
  2481. }
  2482. sl->next_slice_idx = next_slice_idx;
  2483. }
  2484. avctx->execute(avctx, decode_slice, h->slice_ctx,
  2485. NULL, context_count, sizeof(h->slice_ctx[0]));
  2486. /* pull back stuff from slices to master context */
  2487. sl = &h->slice_ctx[context_count - 1];
  2488. h->mb_y = sl->mb_y;
  2489. if (CONFIG_ERROR_RESILIENCE) {
  2490. for (i = 1; i < context_count; i++)
  2491. h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
  2492. }
  2493. if (h->postpone_filter) {
  2494. h->postpone_filter = 0;
  2495. for (i = 0; i < context_count; i++) {
  2496. int y_end, x_end;
  2497. sl = &h->slice_ctx[i];
  2498. y_end = FFMIN(sl->mb_y + 1, h->mb_height);
  2499. x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
  2500. for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
  2501. sl->mb_y = j;
  2502. loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
  2503. j == y_end - 1 ? x_end : h->mb_width);
  2504. }
  2505. }
  2506. }
  2507. }
  2508. finish:
  2509. h->nb_slice_ctx_queued = 0;
  2510. return ret;
  2511. }