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.

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