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.

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