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