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.

2563 lines
93KB

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