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.

4643 lines
166KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/stereo3d.h"
  31. #include "libavutil/timer.h"
  32. #include "internal.h"
  33. #include "cabac.h"
  34. #include "cabac_functions.h"
  35. #include "dsputil.h"
  36. #include "error_resilience.h"
  37. #include "avcodec.h"
  38. #include "h264.h"
  39. #include "h264data.h"
  40. #include "h264chroma.h"
  41. #include "h264_mvpred.h"
  42. #include "golomb.h"
  43. #include "mathops.h"
  44. #include "mpegutils.h"
  45. #include "rectangle.h"
  46. #include "svq3.h"
  47. #include "thread.h"
  48. #include "vdpau_internal.h"
  49. #include <assert.h>
  50. static void flush_change(H264Context *h);
  51. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  52. static const uint8_t rem6[QP_MAX_NUM + 1] = {
  53. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  54. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  55. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  56. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  57. 0, 1, 2, 3,
  58. };
  59. static const uint8_t div6[QP_MAX_NUM + 1] = {
  60. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
  61. 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
  62. 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
  63. 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
  64. 14,14,14,14,
  65. };
  66. static const uint8_t field_scan[16+1] = {
  67. 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
  68. 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
  69. 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
  70. 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
  71. };
  72. static const uint8_t field_scan8x8[64+1] = {
  73. 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
  74. 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
  75. 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
  76. 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
  77. 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
  78. 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
  79. 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
  80. 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
  81. 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
  82. 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
  83. 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
  84. 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
  85. 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
  86. 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
  87. 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
  88. 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
  89. };
  90. static const uint8_t field_scan8x8_cavlc[64+1] = {
  91. 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
  92. 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
  93. 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
  94. 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
  95. 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
  96. 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
  97. 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
  98. 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
  99. 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
  100. 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
  101. 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
  102. 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
  103. 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
  104. 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
  105. 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
  106. 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
  107. };
  108. // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
  109. static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
  110. 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
  111. 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
  112. 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
  113. 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
  114. 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
  115. 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
  116. 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
  117. 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
  118. 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
  119. 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
  120. 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
  121. 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
  122. 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
  123. 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
  124. 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
  125. 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
  126. };
  127. static const uint8_t dequant4_coeff_init[6][3] = {
  128. { 10, 13, 16 },
  129. { 11, 14, 18 },
  130. { 13, 16, 20 },
  131. { 14, 18, 23 },
  132. { 16, 20, 25 },
  133. { 18, 23, 29 },
  134. };
  135. static const uint8_t dequant8_coeff_init_scan[16] = {
  136. 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
  137. };
  138. static const uint8_t dequant8_coeff_init[6][6] = {
  139. { 20, 18, 32, 19, 25, 24 },
  140. { 22, 19, 35, 21, 28, 26 },
  141. { 26, 23, 42, 24, 33, 31 },
  142. { 28, 25, 45, 26, 35, 33 },
  143. { 32, 28, 51, 30, 40, 38 },
  144. { 36, 32, 58, 34, 46, 43 },
  145. };
  146. static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
  147. #if CONFIG_H264_DXVA2_HWACCEL
  148. AV_PIX_FMT_DXVA2_VLD,
  149. #endif
  150. #if CONFIG_H264_VAAPI_HWACCEL
  151. AV_PIX_FMT_VAAPI_VLD,
  152. #endif
  153. #if CONFIG_H264_VDA_HWACCEL
  154. AV_PIX_FMT_VDA_VLD,
  155. #endif
  156. #if CONFIG_H264_VDPAU_HWACCEL
  157. AV_PIX_FMT_VDPAU,
  158. #endif
  159. AV_PIX_FMT_YUV420P,
  160. AV_PIX_FMT_NONE
  161. };
  162. static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
  163. #if CONFIG_H264_DXVA2_HWACCEL
  164. AV_PIX_FMT_DXVA2_VLD,
  165. #endif
  166. #if CONFIG_H264_VAAPI_HWACCEL
  167. AV_PIX_FMT_VAAPI_VLD,
  168. #endif
  169. #if CONFIG_H264_VDA_HWACCEL
  170. AV_PIX_FMT_VDA_VLD,
  171. #endif
  172. #if CONFIG_H264_VDPAU_HWACCEL
  173. AV_PIX_FMT_VDPAU,
  174. #endif
  175. AV_PIX_FMT_YUVJ420P,
  176. AV_PIX_FMT_NONE
  177. };
  178. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  179. {
  180. H264Context *h = avctx->priv_data;
  181. return h ? h->sps.num_reorder_frames : 0;
  182. }
  183. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  184. int (*mv)[2][4][2],
  185. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  186. {
  187. H264Context *h = opaque;
  188. h->mb_x = mb_x;
  189. h->mb_y = mb_y;
  190. h->mb_xy = mb_x + mb_y * h->mb_stride;
  191. memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
  192. av_assert1(ref >= 0);
  193. /* FIXME: It is possible albeit uncommon that slice references
  194. * differ between slices. We take the easy approach and ignore
  195. * it for now. If this turns out to have any relevance in
  196. * practice then correct remapping should be added. */
  197. if (ref >= h->ref_count[0])
  198. ref = 0;
  199. if (!h->ref_list[0][ref].f.data[0]) {
  200. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  201. ref = 0;
  202. }
  203. if ((h->ref_list[0][ref].reference&3) != 3) {
  204. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  205. return;
  206. }
  207. fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
  208. 2, 2, 2, ref, 1);
  209. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  210. fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
  211. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  212. h->mb_mbaff =
  213. h->mb_field_decoding_flag = 0;
  214. ff_h264_hl_decode_mb(h);
  215. }
  216. void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
  217. {
  218. AVCodecContext *avctx = h->avctx;
  219. AVFrame *cur = &h->cur_pic.f;
  220. AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
  221. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  222. int vshift = desc->log2_chroma_h;
  223. const int field_pic = h->picture_structure != PICT_FRAME;
  224. if (field_pic) {
  225. height <<= 1;
  226. y <<= 1;
  227. }
  228. height = FFMIN(height, avctx->height - y);
  229. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  230. return;
  231. if (avctx->draw_horiz_band) {
  232. AVFrame *src;
  233. int offset[AV_NUM_DATA_POINTERS];
  234. int i;
  235. if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
  236. (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
  237. src = cur;
  238. else if (last)
  239. src = last;
  240. else
  241. return;
  242. offset[0] = y * src->linesize[0];
  243. offset[1] =
  244. offset[2] = (y >> vshift) * src->linesize[1];
  245. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  246. offset[i] = 0;
  247. emms_c();
  248. avctx->draw_horiz_band(avctx, src, offset,
  249. y, h->picture_structure, height);
  250. }
  251. }
  252. static void unref_picture(H264Context *h, H264Picture *pic)
  253. {
  254. int off = offsetof(H264Picture, tf) + sizeof(pic->tf);
  255. int i;
  256. if (!pic->f.buf[0])
  257. return;
  258. ff_thread_release_buffer(h->avctx, &pic->tf);
  259. av_buffer_unref(&pic->hwaccel_priv_buf);
  260. av_buffer_unref(&pic->qscale_table_buf);
  261. av_buffer_unref(&pic->mb_type_buf);
  262. for (i = 0; i < 2; i++) {
  263. av_buffer_unref(&pic->motion_val_buf[i]);
  264. av_buffer_unref(&pic->ref_index_buf[i]);
  265. }
  266. memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
  267. }
  268. static void release_unused_pictures(H264Context *h, int remove_current)
  269. {
  270. int i;
  271. /* release non reference frames */
  272. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  273. if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
  274. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  275. unref_picture(h, &h->DPB[i]);
  276. }
  277. }
  278. }
  279. static int ref_picture(H264Context *h, H264Picture *dst, H264Picture *src)
  280. {
  281. int ret, i;
  282. av_assert0(!dst->f.buf[0]);
  283. av_assert0(src->f.buf[0]);
  284. src->tf.f = &src->f;
  285. dst->tf.f = &dst->f;
  286. ret = ff_thread_ref_frame(&dst->tf, &src->tf);
  287. if (ret < 0)
  288. goto fail;
  289. dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
  290. dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
  291. if (!dst->qscale_table_buf || !dst->mb_type_buf)
  292. goto fail;
  293. dst->qscale_table = src->qscale_table;
  294. dst->mb_type = src->mb_type;
  295. for (i = 0; i < 2; i++) {
  296. dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
  297. dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
  298. if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
  299. goto fail;
  300. dst->motion_val[i] = src->motion_val[i];
  301. dst->ref_index[i] = src->ref_index[i];
  302. }
  303. if (src->hwaccel_picture_private) {
  304. dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
  305. if (!dst->hwaccel_priv_buf)
  306. goto fail;
  307. dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
  308. }
  309. for (i = 0; i < 2; i++)
  310. dst->field_poc[i] = src->field_poc[i];
  311. memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
  312. memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
  313. dst->poc = src->poc;
  314. dst->frame_num = src->frame_num;
  315. dst->mmco_reset = src->mmco_reset;
  316. dst->pic_id = src->pic_id;
  317. dst->long_ref = src->long_ref;
  318. dst->mbaff = src->mbaff;
  319. dst->field_picture = src->field_picture;
  320. dst->needs_realloc = src->needs_realloc;
  321. dst->reference = src->reference;
  322. dst->crop = src->crop;
  323. dst->crop_left = src->crop_left;
  324. dst->crop_top = src->crop_top;
  325. dst->recovered = src->recovered;
  326. dst->invalid_gap = src->invalid_gap;
  327. return 0;
  328. fail:
  329. unref_picture(h, dst);
  330. return ret;
  331. }
  332. static int alloc_scratch_buffers(H264Context *h, int linesize)
  333. {
  334. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  335. if (h->bipred_scratchpad)
  336. return 0;
  337. h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
  338. // edge emu needs blocksize + filter length - 1
  339. // (= 21x21 for h264)
  340. h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
  341. if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
  342. av_freep(&h->bipred_scratchpad);
  343. av_freep(&h->edge_emu_buffer);
  344. return AVERROR(ENOMEM);
  345. }
  346. return 0;
  347. }
  348. static int init_table_pools(H264Context *h)
  349. {
  350. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  351. const int mb_array_size = h->mb_stride * h->mb_height;
  352. const int b4_stride = h->mb_width * 4 + 1;
  353. const int b4_array_size = b4_stride * h->mb_height * 4;
  354. h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
  355. av_buffer_allocz);
  356. h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
  357. sizeof(uint32_t), av_buffer_allocz);
  358. h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
  359. sizeof(int16_t), av_buffer_allocz);
  360. h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
  361. if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
  362. !h->ref_index_pool) {
  363. av_buffer_pool_uninit(&h->qscale_table_pool);
  364. av_buffer_pool_uninit(&h->mb_type_pool);
  365. av_buffer_pool_uninit(&h->motion_val_pool);
  366. av_buffer_pool_uninit(&h->ref_index_pool);
  367. return AVERROR(ENOMEM);
  368. }
  369. return 0;
  370. }
  371. static int alloc_picture(H264Context *h, H264Picture *pic)
  372. {
  373. int i, ret = 0;
  374. av_assert0(!pic->f.data[0]);
  375. pic->tf.f = &pic->f;
  376. ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
  377. AV_GET_BUFFER_FLAG_REF : 0);
  378. if (ret < 0)
  379. goto fail;
  380. h->linesize = pic->f.linesize[0];
  381. h->uvlinesize = pic->f.linesize[1];
  382. pic->crop = h->sps.crop;
  383. pic->crop_top = h->sps.crop_top;
  384. pic->crop_left= h->sps.crop_left;
  385. if (h->avctx->hwaccel) {
  386. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  387. av_assert0(!pic->hwaccel_picture_private);
  388. if (hwaccel->priv_data_size) {
  389. pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
  390. if (!pic->hwaccel_priv_buf)
  391. return AVERROR(ENOMEM);
  392. pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
  393. }
  394. }
  395. if (!h->avctx->hwaccel && CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY && pic->f.data[2]) {
  396. int h_chroma_shift, v_chroma_shift;
  397. av_pix_fmt_get_chroma_sub_sample(pic->f.format,
  398. &h_chroma_shift, &v_chroma_shift);
  399. for(i=0; i<FF_CEIL_RSHIFT(h->avctx->height, v_chroma_shift); i++) {
  400. memset(pic->f.data[1] + pic->f.linesize[1]*i,
  401. 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
  402. memset(pic->f.data[2] + pic->f.linesize[2]*i,
  403. 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
  404. }
  405. }
  406. if (!h->qscale_table_pool) {
  407. ret = init_table_pools(h);
  408. if (ret < 0)
  409. goto fail;
  410. }
  411. pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
  412. pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
  413. if (!pic->qscale_table_buf || !pic->mb_type_buf)
  414. goto fail;
  415. pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
  416. pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
  417. for (i = 0; i < 2; i++) {
  418. pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
  419. pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
  420. if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
  421. goto fail;
  422. pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
  423. pic->ref_index[i] = pic->ref_index_buf[i]->data;
  424. }
  425. return 0;
  426. fail:
  427. unref_picture(h, pic);
  428. return (ret < 0) ? ret : AVERROR(ENOMEM);
  429. }
  430. static inline int pic_is_unused(H264Context *h, H264Picture *pic)
  431. {
  432. if (!pic->f.buf[0])
  433. return 1;
  434. if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
  435. return 1;
  436. return 0;
  437. }
  438. static int find_unused_picture(H264Context *h)
  439. {
  440. int i;
  441. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  442. if (pic_is_unused(h, &h->DPB[i]))
  443. break;
  444. }
  445. if (i == H264_MAX_PICTURE_COUNT)
  446. return AVERROR_INVALIDDATA;
  447. if (h->DPB[i].needs_realloc) {
  448. h->DPB[i].needs_realloc = 0;
  449. unref_picture(h, &h->DPB[i]);
  450. }
  451. return i;
  452. }
  453. /**
  454. * Check if the top & left blocks are available if needed and
  455. * change the dc mode so it only uses the available blocks.
  456. */
  457. int ff_h264_check_intra4x4_pred_mode(H264Context *h)
  458. {
  459. static const int8_t top[12] = {
  460. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  461. };
  462. static const int8_t left[12] = {
  463. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  464. };
  465. int i;
  466. if (!(h->top_samples_available & 0x8000)) {
  467. for (i = 0; i < 4; i++) {
  468. int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
  469. if (status < 0) {
  470. av_log(h->avctx, AV_LOG_ERROR,
  471. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  472. status, h->mb_x, h->mb_y);
  473. return AVERROR_INVALIDDATA;
  474. } else if (status) {
  475. h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  476. }
  477. }
  478. }
  479. if ((h->left_samples_available & 0x8888) != 0x8888) {
  480. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  481. for (i = 0; i < 4; i++)
  482. if (!(h->left_samples_available & mask[i])) {
  483. int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  484. if (status < 0) {
  485. av_log(h->avctx, AV_LOG_ERROR,
  486. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  487. status, h->mb_x, h->mb_y);
  488. return AVERROR_INVALIDDATA;
  489. } else if (status) {
  490. h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  491. }
  492. }
  493. }
  494. return 0;
  495. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  496. /**
  497. * Check if the top & left blocks are available if needed and
  498. * change the dc mode so it only uses the available blocks.
  499. */
  500. int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
  501. {
  502. static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  503. static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  504. if (mode > 3U) {
  505. av_log(h->avctx, AV_LOG_ERROR,
  506. "out of range intra chroma pred mode at %d %d\n",
  507. h->mb_x, h->mb_y);
  508. return AVERROR_INVALIDDATA;
  509. }
  510. if (!(h->top_samples_available & 0x8000)) {
  511. mode = top[mode];
  512. if (mode < 0) {
  513. av_log(h->avctx, AV_LOG_ERROR,
  514. "top block unavailable for requested intra mode at %d %d\n",
  515. h->mb_x, h->mb_y);
  516. return AVERROR_INVALIDDATA;
  517. }
  518. }
  519. if ((h->left_samples_available & 0x8080) != 0x8080) {
  520. mode = left[mode];
  521. if (is_chroma && (h->left_samples_available & 0x8080)) {
  522. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  523. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  524. (!(h->left_samples_available & 0x8000)) +
  525. 2 * (mode == DC_128_PRED8x8);
  526. }
  527. if (mode < 0) {
  528. av_log(h->avctx, AV_LOG_ERROR,
  529. "left block unavailable for requested intra mode at %d %d\n",
  530. h->mb_x, h->mb_y);
  531. return AVERROR_INVALIDDATA;
  532. }
  533. }
  534. return mode;
  535. }
  536. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
  537. int *dst_length, int *consumed, int length)
  538. {
  539. int i, si, di;
  540. uint8_t *dst;
  541. int bufidx;
  542. // src[0]&0x80; // forbidden bit
  543. h->nal_ref_idc = src[0] >> 5;
  544. h->nal_unit_type = src[0] & 0x1F;
  545. src++;
  546. length--;
  547. #define STARTCODE_TEST \
  548. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  549. if (src[i + 2] != 3) { \
  550. /* startcode, so we must be past the end */ \
  551. length = i; \
  552. } \
  553. break; \
  554. }
  555. #if HAVE_FAST_UNALIGNED
  556. #define FIND_FIRST_ZERO \
  557. if (i > 0 && !src[i]) \
  558. i--; \
  559. while (src[i]) \
  560. i++
  561. #if HAVE_FAST_64BIT
  562. for (i = 0; i + 1 < length; i += 9) {
  563. if (!((~AV_RN64A(src + i) &
  564. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  565. 0x8000800080008080ULL))
  566. continue;
  567. FIND_FIRST_ZERO;
  568. STARTCODE_TEST;
  569. i -= 7;
  570. }
  571. #else
  572. for (i = 0; i + 1 < length; i += 5) {
  573. if (!((~AV_RN32A(src + i) &
  574. (AV_RN32A(src + i) - 0x01000101U)) &
  575. 0x80008080U))
  576. continue;
  577. FIND_FIRST_ZERO;
  578. STARTCODE_TEST;
  579. i -= 3;
  580. }
  581. #endif
  582. #else
  583. for (i = 0; i + 1 < length; i += 2) {
  584. if (src[i])
  585. continue;
  586. if (i > 0 && src[i - 1] == 0)
  587. i--;
  588. STARTCODE_TEST;
  589. }
  590. #endif
  591. // use second escape buffer for inter data
  592. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
  593. si = h->rbsp_buffer_size[bufidx];
  594. av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
  595. dst = h->rbsp_buffer[bufidx];
  596. if (dst == NULL)
  597. return NULL;
  598. if(i>=length-1){ //no escaped 0
  599. *dst_length= length;
  600. *consumed= length+1; //+1 for the header
  601. if(h->avctx->flags2 & CODEC_FLAG2_FAST){
  602. return src;
  603. }else{
  604. memcpy(dst, src, length);
  605. return dst;
  606. }
  607. }
  608. memcpy(dst, src, i);
  609. si = di = i;
  610. while (si + 2 < length) {
  611. // remove escapes (very rare 1:2^22)
  612. if (src[si + 2] > 3) {
  613. dst[di++] = src[si++];
  614. dst[di++] = src[si++];
  615. } else if (src[si] == 0 && src[si + 1] == 0) {
  616. if (src[si + 2] == 3) { // escape
  617. dst[di++] = 0;
  618. dst[di++] = 0;
  619. si += 3;
  620. continue;
  621. } else // next start code
  622. goto nsc;
  623. }
  624. dst[di++] = src[si++];
  625. }
  626. while (si < length)
  627. dst[di++] = src[si++];
  628. nsc:
  629. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  630. *dst_length = di;
  631. *consumed = si + 1; // +1 for the header
  632. /* FIXME store exact number of bits in the getbitcontext
  633. * (it is needed for decoding) */
  634. return dst;
  635. }
  636. /**
  637. * Identify the exact end of the bitstream
  638. * @return the length of the trailing, or 0 if damaged
  639. */
  640. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  641. {
  642. int v = *src;
  643. int r;
  644. tprintf(h->avctx, "rbsp trailing %X\n", v);
  645. for (r = 1; r < 9; r++) {
  646. if (v & 1)
  647. return r;
  648. v >>= 1;
  649. }
  650. return 0;
  651. }
  652. static void free_tables(H264Context *h, int free_rbsp)
  653. {
  654. int i;
  655. H264Context *hx;
  656. av_freep(&h->intra4x4_pred_mode);
  657. av_freep(&h->chroma_pred_mode_table);
  658. av_freep(&h->cbp_table);
  659. av_freep(&h->mvd_table[0]);
  660. av_freep(&h->mvd_table[1]);
  661. av_freep(&h->direct_table);
  662. av_freep(&h->non_zero_count);
  663. av_freep(&h->slice_table_base);
  664. h->slice_table = NULL;
  665. av_freep(&h->list_counts);
  666. av_freep(&h->mb2b_xy);
  667. av_freep(&h->mb2br_xy);
  668. av_buffer_pool_uninit(&h->qscale_table_pool);
  669. av_buffer_pool_uninit(&h->mb_type_pool);
  670. av_buffer_pool_uninit(&h->motion_val_pool);
  671. av_buffer_pool_uninit(&h->ref_index_pool);
  672. if (free_rbsp && h->DPB) {
  673. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  674. unref_picture(h, &h->DPB[i]);
  675. av_freep(&h->DPB);
  676. } else if (h->DPB) {
  677. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  678. h->DPB[i].needs_realloc = 1;
  679. }
  680. h->cur_pic_ptr = NULL;
  681. for (i = 0; i < H264_MAX_THREADS; i++) {
  682. hx = h->thread_context[i];
  683. if (!hx)
  684. continue;
  685. av_freep(&hx->top_borders[1]);
  686. av_freep(&hx->top_borders[0]);
  687. av_freep(&hx->bipred_scratchpad);
  688. av_freep(&hx->edge_emu_buffer);
  689. av_freep(&hx->dc_val_base);
  690. av_freep(&hx->er.mb_index2xy);
  691. av_freep(&hx->er.error_status_table);
  692. av_freep(&hx->er.er_temp_buffer);
  693. av_freep(&hx->er.mbintra_table);
  694. av_freep(&hx->er.mbskip_table);
  695. if (free_rbsp) {
  696. av_freep(&hx->rbsp_buffer[1]);
  697. av_freep(&hx->rbsp_buffer[0]);
  698. hx->rbsp_buffer_size[0] = 0;
  699. hx->rbsp_buffer_size[1] = 0;
  700. }
  701. if (i)
  702. av_freep(&h->thread_context[i]);
  703. }
  704. }
  705. static void init_dequant8_coeff_table(H264Context *h)
  706. {
  707. int i, j, q, x;
  708. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  709. for (i = 0; i < 6; i++) {
  710. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  711. for (j = 0; j < i; j++)
  712. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  713. 64 * sizeof(uint8_t))) {
  714. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  715. break;
  716. }
  717. if (j < i)
  718. continue;
  719. for (q = 0; q < max_qp + 1; q++) {
  720. int shift = div6[q];
  721. int idx = rem6[q];
  722. for (x = 0; x < 64; x++)
  723. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  724. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  725. h->pps.scaling_matrix8[i][x]) << shift;
  726. }
  727. }
  728. }
  729. static void init_dequant4_coeff_table(H264Context *h)
  730. {
  731. int i, j, q, x;
  732. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  733. for (i = 0; i < 6; i++) {
  734. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  735. for (j = 0; j < i; j++)
  736. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  737. 16 * sizeof(uint8_t))) {
  738. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  739. break;
  740. }
  741. if (j < i)
  742. continue;
  743. for (q = 0; q < max_qp + 1; q++) {
  744. int shift = div6[q] + 2;
  745. int idx = rem6[q];
  746. for (x = 0; x < 16; x++)
  747. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  748. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  749. h->pps.scaling_matrix4[i][x]) << shift;
  750. }
  751. }
  752. }
  753. static void init_dequant_tables(H264Context *h)
  754. {
  755. int i, x;
  756. init_dequant4_coeff_table(h);
  757. memset(h->dequant8_coeff, 0, sizeof(h->dequant8_coeff));
  758. if (h->pps.transform_8x8_mode)
  759. init_dequant8_coeff_table(h);
  760. if (h->sps.transform_bypass) {
  761. for (i = 0; i < 6; i++)
  762. for (x = 0; x < 16; x++)
  763. h->dequant4_coeff[i][0][x] = 1 << 6;
  764. if (h->pps.transform_8x8_mode)
  765. for (i = 0; i < 6; i++)
  766. for (x = 0; x < 64; x++)
  767. h->dequant8_coeff[i][0][x] = 1 << 6;
  768. }
  769. }
  770. int ff_h264_alloc_tables(H264Context *h)
  771. {
  772. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  773. const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
  774. int x, y, i;
  775. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  776. row_mb_num * 8 * sizeof(uint8_t), fail)
  777. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  778. big_mb_num * 48 * sizeof(uint8_t), fail)
  779. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  780. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  781. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  782. big_mb_num * sizeof(uint16_t), fail)
  783. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  784. big_mb_num * sizeof(uint8_t), fail)
  785. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  786. 16 * row_mb_num * sizeof(uint8_t), fail);
  787. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  788. 16 * row_mb_num * sizeof(uint8_t), fail);
  789. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  790. 4 * big_mb_num * sizeof(uint8_t), fail);
  791. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  792. big_mb_num * sizeof(uint8_t), fail)
  793. memset(h->slice_table_base, -1,
  794. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  795. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  796. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  797. big_mb_num * sizeof(uint32_t), fail);
  798. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  799. big_mb_num * sizeof(uint32_t), fail);
  800. for (y = 0; y < h->mb_height; y++)
  801. for (x = 0; x < h->mb_width; x++) {
  802. const int mb_xy = x + y * h->mb_stride;
  803. const int b_xy = 4 * x + 4 * y * h->b_stride;
  804. h->mb2b_xy[mb_xy] = b_xy;
  805. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  806. }
  807. if (!h->dequant4_coeff[0])
  808. init_dequant_tables(h);
  809. if (!h->DPB) {
  810. h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
  811. if (!h->DPB)
  812. return AVERROR(ENOMEM);
  813. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  814. av_frame_unref(&h->DPB[i].f);
  815. av_frame_unref(&h->cur_pic.f);
  816. }
  817. return 0;
  818. fail:
  819. free_tables(h, 1);
  820. return AVERROR(ENOMEM);
  821. }
  822. /**
  823. * Mimic alloc_tables(), but for every context thread.
  824. */
  825. static void clone_tables(H264Context *dst, H264Context *src, int i)
  826. {
  827. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
  828. dst->non_zero_count = src->non_zero_count;
  829. dst->slice_table = src->slice_table;
  830. dst->cbp_table = src->cbp_table;
  831. dst->mb2b_xy = src->mb2b_xy;
  832. dst->mb2br_xy = src->mb2br_xy;
  833. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  834. dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
  835. dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
  836. dst->direct_table = src->direct_table;
  837. dst->list_counts = src->list_counts;
  838. dst->DPB = src->DPB;
  839. dst->cur_pic_ptr = src->cur_pic_ptr;
  840. dst->cur_pic = src->cur_pic;
  841. dst->bipred_scratchpad = NULL;
  842. dst->edge_emu_buffer = NULL;
  843. ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
  844. src->sps.chroma_format_idc);
  845. }
  846. /**
  847. * Init context
  848. * Allocate buffers which are not shared amongst multiple threads.
  849. */
  850. static int context_init(H264Context *h)
  851. {
  852. ERContext *er = &h->er;
  853. int mb_array_size = h->mb_height * h->mb_stride;
  854. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  855. int c_size = h->mb_stride * (h->mb_height + 1);
  856. int yc_size = y_size + 2 * c_size;
  857. int x, y, i;
  858. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
  859. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  860. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
  861. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  862. h->ref_cache[0][scan8[5] + 1] =
  863. h->ref_cache[0][scan8[7] + 1] =
  864. h->ref_cache[0][scan8[13] + 1] =
  865. h->ref_cache[1][scan8[5] + 1] =
  866. h->ref_cache[1][scan8[7] + 1] =
  867. h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  868. if (CONFIG_ERROR_RESILIENCE) {
  869. /* init ER */
  870. er->avctx = h->avctx;
  871. er->dsp = &h->dsp;
  872. er->decode_mb = h264_er_decode_mb;
  873. er->opaque = h;
  874. er->quarter_sample = 1;
  875. er->mb_num = h->mb_num;
  876. er->mb_width = h->mb_width;
  877. er->mb_height = h->mb_height;
  878. er->mb_stride = h->mb_stride;
  879. er->b8_stride = h->mb_width * 2 + 1;
  880. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
  881. fail); // error ressilience code looks cleaner with this
  882. for (y = 0; y < h->mb_height; y++)
  883. for (x = 0; x < h->mb_width; x++)
  884. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  885. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  886. h->mb_stride + h->mb_width;
  887. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  888. mb_array_size * sizeof(uint8_t), fail);
  889. FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
  890. memset(er->mbintra_table, 1, mb_array_size);
  891. FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
  892. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
  893. fail);
  894. FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
  895. er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
  896. er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
  897. er->dc_val[2] = er->dc_val[1] + c_size;
  898. for (i = 0; i < yc_size; i++)
  899. h->dc_val_base[i] = 1024;
  900. }
  901. return 0;
  902. fail:
  903. return AVERROR(ENOMEM); // free_tables will clean up for us
  904. }
  905. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  906. int parse_extradata);
  907. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  908. {
  909. AVCodecContext *avctx = h->avctx;
  910. int ret;
  911. if (!buf || size <= 0)
  912. return -1;
  913. if (buf[0] == 1) {
  914. int i, cnt, nalsize;
  915. const unsigned char *p = buf;
  916. h->is_avc = 1;
  917. if (size < 7) {
  918. av_log(avctx, AV_LOG_ERROR,
  919. "avcC %d too short\n", size);
  920. return AVERROR_INVALIDDATA;
  921. }
  922. /* sps and pps in the avcC always have length coded with 2 bytes,
  923. * so put a fake nal_length_size = 2 while parsing them */
  924. h->nal_length_size = 2;
  925. // Decode sps from avcC
  926. cnt = *(p + 5) & 0x1f; // Number of sps
  927. p += 6;
  928. for (i = 0; i < cnt; i++) {
  929. nalsize = AV_RB16(p) + 2;
  930. if(nalsize > size - (p-buf))
  931. return AVERROR_INVALIDDATA;
  932. ret = decode_nal_units(h, p, nalsize, 1);
  933. if (ret < 0) {
  934. av_log(avctx, AV_LOG_ERROR,
  935. "Decoding sps %d from avcC failed\n", i);
  936. return ret;
  937. }
  938. p += nalsize;
  939. }
  940. // Decode pps from avcC
  941. cnt = *(p++); // Number of pps
  942. for (i = 0; i < cnt; i++) {
  943. nalsize = AV_RB16(p) + 2;
  944. if(nalsize > size - (p-buf))
  945. return AVERROR_INVALIDDATA;
  946. ret = decode_nal_units(h, p, nalsize, 1);
  947. if (ret < 0) {
  948. av_log(avctx, AV_LOG_ERROR,
  949. "Decoding pps %d from avcC failed\n", i);
  950. return ret;
  951. }
  952. p += nalsize;
  953. }
  954. // Now store right nal length size, that will be used to parse all other nals
  955. h->nal_length_size = (buf[4] & 0x03) + 1;
  956. } else {
  957. h->is_avc = 0;
  958. ret = decode_nal_units(h, buf, size, 1);
  959. if (ret < 0)
  960. return ret;
  961. }
  962. return size;
  963. }
  964. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  965. {
  966. H264Context *h = avctx->priv_data;
  967. int i;
  968. int ret;
  969. h->avctx = avctx;
  970. h->bit_depth_luma = 8;
  971. h->chroma_format_idc = 1;
  972. h->avctx->bits_per_raw_sample = 8;
  973. h->cur_chroma_format_idc = 1;
  974. ff_h264dsp_init(&h->h264dsp, 8, 1);
  975. av_assert0(h->sps.bit_depth_chroma == 0);
  976. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  977. ff_h264qpel_init(&h->h264qpel, 8);
  978. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
  979. h->dequant_coeff_pps = -1;
  980. h->current_sps_id = -1;
  981. /* needed so that IDCT permutation is known early */
  982. if (CONFIG_ERROR_RESILIENCE)
  983. ff_dsputil_init(&h->dsp, h->avctx);
  984. ff_videodsp_init(&h->vdsp, 8);
  985. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  986. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  987. h->picture_structure = PICT_FRAME;
  988. h->slice_context_count = 1;
  989. h->workaround_bugs = avctx->workaround_bugs;
  990. h->flags = avctx->flags;
  991. /* set defaults */
  992. // s->decode_mb = ff_h263_decode_mb;
  993. if (!avctx->has_b_frames)
  994. h->low_delay = 1;
  995. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  996. ff_h264_decode_init_vlc();
  997. ff_init_cabac_states();
  998. h->pixel_shift = 0;
  999. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  1000. h->thread_context[0] = h;
  1001. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1002. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1003. h->last_pocs[i] = INT_MIN;
  1004. h->prev_poc_msb = 1 << 16;
  1005. h->prev_frame_num = -1;
  1006. h->x264_build = -1;
  1007. h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
  1008. ff_h264_reset_sei(h);
  1009. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1010. if (avctx->ticks_per_frame == 1) {
  1011. if(h->avctx->time_base.den < INT_MAX/2) {
  1012. h->avctx->time_base.den *= 2;
  1013. } else
  1014. h->avctx->time_base.num /= 2;
  1015. }
  1016. avctx->ticks_per_frame = 2;
  1017. }
  1018. if (avctx->extradata_size > 0 && avctx->extradata) {
  1019. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  1020. if (ret < 0) {
  1021. ff_h264_free_context(h);
  1022. return ret;
  1023. }
  1024. }
  1025. if (h->sps.bitstream_restriction_flag &&
  1026. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1027. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1028. h->low_delay = 0;
  1029. }
  1030. avctx->internal->allocate_progress = 1;
  1031. flush_change(h);
  1032. return 0;
  1033. }
  1034. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  1035. #undef REBASE_PICTURE
  1036. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  1037. ((pic && pic >= old_ctx->DPB && \
  1038. pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
  1039. &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
  1040. static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
  1041. H264Context *new_base,
  1042. H264Context *old_base)
  1043. {
  1044. int i;
  1045. for (i = 0; i < count; i++) {
  1046. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1047. IN_RANGE(from[i], old_base->DPB,
  1048. sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
  1049. !from[i]));
  1050. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1051. }
  1052. }
  1053. static int copy_parameter_set(void **to, void **from, int count, int size)
  1054. {
  1055. int i;
  1056. for (i = 0; i < count; i++) {
  1057. if (to[i] && !from[i]) {
  1058. av_freep(&to[i]);
  1059. } else if (from[i] && !to[i]) {
  1060. to[i] = av_malloc(size);
  1061. if (!to[i])
  1062. return AVERROR(ENOMEM);
  1063. }
  1064. if (from[i])
  1065. memcpy(to[i], from[i], size);
  1066. }
  1067. return 0;
  1068. }
  1069. static int decode_init_thread_copy(AVCodecContext *avctx)
  1070. {
  1071. H264Context *h = avctx->priv_data;
  1072. if (!avctx->internal->is_copy)
  1073. return 0;
  1074. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1075. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1076. h->rbsp_buffer[0] = NULL;
  1077. h->rbsp_buffer[1] = NULL;
  1078. h->rbsp_buffer_size[0] = 0;
  1079. h->rbsp_buffer_size[1] = 0;
  1080. h->context_initialized = 0;
  1081. return 0;
  1082. }
  1083. #define copy_fields(to, from, start_field, end_field) \
  1084. memcpy(&to->start_field, &from->start_field, \
  1085. (char *)&to->end_field - (char *)&to->start_field)
  1086. static int h264_slice_header_init(H264Context *, int);
  1087. static int h264_set_parameter_from_sps(H264Context *h);
  1088. static int decode_update_thread_context(AVCodecContext *dst,
  1089. const AVCodecContext *src)
  1090. {
  1091. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1092. int inited = h->context_initialized, err = 0;
  1093. int context_reinitialized = 0;
  1094. int i, ret;
  1095. if (dst == src)
  1096. return 0;
  1097. if (inited &&
  1098. (h->width != h1->width ||
  1099. h->height != h1->height ||
  1100. h->mb_width != h1->mb_width ||
  1101. h->mb_height != h1->mb_height ||
  1102. h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
  1103. h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
  1104. h->sps.colorspace != h1->sps.colorspace)) {
  1105. /* set bits_per_raw_sample to the previous value. the check for changed
  1106. * bit depth in h264_set_parameter_from_sps() uses it and sets it to
  1107. * the current value */
  1108. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1109. av_freep(&h->bipred_scratchpad);
  1110. h->width = h1->width;
  1111. h->height = h1->height;
  1112. h->mb_height = h1->mb_height;
  1113. h->mb_width = h1->mb_width;
  1114. h->mb_num = h1->mb_num;
  1115. h->mb_stride = h1->mb_stride;
  1116. h->b_stride = h1->b_stride;
  1117. // SPS/PPS
  1118. if ((ret = copy_parameter_set((void **)h->sps_buffers,
  1119. (void **)h1->sps_buffers,
  1120. MAX_SPS_COUNT, sizeof(SPS))) < 0)
  1121. return ret;
  1122. h->sps = h1->sps;
  1123. if ((ret = copy_parameter_set((void **)h->pps_buffers,
  1124. (void **)h1->pps_buffers,
  1125. MAX_PPS_COUNT, sizeof(PPS))) < 0)
  1126. return ret;
  1127. h->pps = h1->pps;
  1128. if ((err = h264_slice_header_init(h, 1)) < 0) {
  1129. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  1130. return err;
  1131. }
  1132. context_reinitialized = 1;
  1133. #if 0
  1134. h264_set_parameter_from_sps(h);
  1135. //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
  1136. h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
  1137. #endif
  1138. }
  1139. /* update linesize on resize for h264. The h264 decoder doesn't
  1140. * necessarily call ff_MPV_frame_start in the new thread */
  1141. h->linesize = h1->linesize;
  1142. h->uvlinesize = h1->uvlinesize;
  1143. /* copy block_offset since frame_start may not be called */
  1144. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  1145. if (!inited) {
  1146. for (i = 0; i < MAX_SPS_COUNT; i++)
  1147. av_freep(h->sps_buffers + i);
  1148. for (i = 0; i < MAX_PPS_COUNT; i++)
  1149. av_freep(h->pps_buffers + i);
  1150. av_freep(&h->rbsp_buffer[0]);
  1151. av_freep(&h->rbsp_buffer[1]);
  1152. memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
  1153. memcpy(&h->cabac, &h1->cabac,
  1154. sizeof(H264Context) - offsetof(H264Context, cabac));
  1155. av_assert0((void*)&h->cabac == &h->mb_padding + 1);
  1156. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1157. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1158. memset(&h->er, 0, sizeof(h->er));
  1159. memset(&h->mb, 0, sizeof(h->mb));
  1160. memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
  1161. memset(&h->mb_padding, 0, sizeof(h->mb_padding));
  1162. h->avctx = dst;
  1163. h->DPB = NULL;
  1164. h->qscale_table_pool = NULL;
  1165. h->mb_type_pool = NULL;
  1166. h->ref_index_pool = NULL;
  1167. h->motion_val_pool = NULL;
  1168. for (i = 0; i < 2; i++) {
  1169. h->rbsp_buffer[i] = NULL;
  1170. h->rbsp_buffer_size[i] = 0;
  1171. }
  1172. if (h1->context_initialized) {
  1173. h->context_initialized = 0;
  1174. memset(&h->cur_pic, 0, sizeof(h->cur_pic));
  1175. av_frame_unref(&h->cur_pic.f);
  1176. h->cur_pic.tf.f = &h->cur_pic.f;
  1177. ret = ff_h264_alloc_tables(h);
  1178. if (ret < 0) {
  1179. av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
  1180. return ret;
  1181. }
  1182. ret = context_init(h);
  1183. if (ret < 0) {
  1184. av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
  1185. return ret;
  1186. }
  1187. }
  1188. h->bipred_scratchpad = NULL;
  1189. h->edge_emu_buffer = NULL;
  1190. h->thread_context[0] = h;
  1191. h->context_initialized = h1->context_initialized;
  1192. }
  1193. h->avctx->coded_height = h1->avctx->coded_height;
  1194. h->avctx->coded_width = h1->avctx->coded_width;
  1195. h->avctx->width = h1->avctx->width;
  1196. h->avctx->height = h1->avctx->height;
  1197. h->coded_picture_number = h1->coded_picture_number;
  1198. h->first_field = h1->first_field;
  1199. h->picture_structure = h1->picture_structure;
  1200. h->qscale = h1->qscale;
  1201. h->droppable = h1->droppable;
  1202. h->low_delay = h1->low_delay;
  1203. for (i = 0; h->DPB && i < H264_MAX_PICTURE_COUNT; i++) {
  1204. unref_picture(h, &h->DPB[i]);
  1205. if (h1->DPB && h1->DPB[i].f.buf[0] &&
  1206. (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
  1207. return ret;
  1208. }
  1209. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  1210. unref_picture(h, &h->cur_pic);
  1211. if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
  1212. return ret;
  1213. h->workaround_bugs = h1->workaround_bugs;
  1214. h->low_delay = h1->low_delay;
  1215. h->droppable = h1->droppable;
  1216. // extradata/NAL handling
  1217. h->is_avc = h1->is_avc;
  1218. // SPS/PPS
  1219. if ((ret = copy_parameter_set((void **)h->sps_buffers,
  1220. (void **)h1->sps_buffers,
  1221. MAX_SPS_COUNT, sizeof(SPS))) < 0)
  1222. return ret;
  1223. h->sps = h1->sps;
  1224. if ((ret = copy_parameter_set((void **)h->pps_buffers,
  1225. (void **)h1->pps_buffers,
  1226. MAX_PPS_COUNT, sizeof(PPS))) < 0)
  1227. return ret;
  1228. h->pps = h1->pps;
  1229. // Dequantization matrices
  1230. // FIXME these are big - can they be only copied when PPS changes?
  1231. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1232. for (i = 0; i < 6; i++)
  1233. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1234. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1235. for (i = 0; i < 6; i++)
  1236. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1237. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1238. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1239. // POC timing
  1240. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1241. // reference lists
  1242. copy_fields(h, h1, short_ref, cabac_init_idc);
  1243. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  1244. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  1245. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1246. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  1247. h->frame_recovered = h1->frame_recovered;
  1248. if (context_reinitialized)
  1249. h264_set_parameter_from_sps(h);
  1250. if (!h->cur_pic_ptr)
  1251. return 0;
  1252. if (!h->droppable) {
  1253. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1254. h->prev_poc_msb = h->poc_msb;
  1255. h->prev_poc_lsb = h->poc_lsb;
  1256. }
  1257. h->prev_frame_num_offset = h->frame_num_offset;
  1258. h->prev_frame_num = h->frame_num;
  1259. h->outputed_poc = h->next_outputed_poc;
  1260. h->recovery_frame = h1->recovery_frame;
  1261. return err;
  1262. }
  1263. static int h264_frame_start(H264Context *h)
  1264. {
  1265. H264Picture *pic;
  1266. int i, ret;
  1267. const int pixel_shift = h->pixel_shift;
  1268. int c[4] = {
  1269. 1<<(h->sps.bit_depth_luma-1),
  1270. 1<<(h->sps.bit_depth_chroma-1),
  1271. 1<<(h->sps.bit_depth_chroma-1),
  1272. -1
  1273. };
  1274. if (!ff_thread_can_start_frame(h->avctx)) {
  1275. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  1276. return -1;
  1277. }
  1278. release_unused_pictures(h, 1);
  1279. h->cur_pic_ptr = NULL;
  1280. i = find_unused_picture(h);
  1281. if (i < 0) {
  1282. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  1283. return i;
  1284. }
  1285. pic = &h->DPB[i];
  1286. pic->reference = h->droppable ? 0 : h->picture_structure;
  1287. pic->f.coded_picture_number = h->coded_picture_number++;
  1288. pic->field_picture = h->picture_structure != PICT_FRAME;
  1289. /*
  1290. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  1291. * in later.
  1292. * See decode_nal_units().
  1293. */
  1294. pic->f.key_frame = 0;
  1295. pic->mmco_reset = 0;
  1296. pic->recovered = 0;
  1297. pic->invalid_gap = 0;
  1298. if ((ret = alloc_picture(h, pic)) < 0)
  1299. return ret;
  1300. if(!h->frame_recovered && !h->avctx->hwaccel &&
  1301. !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
  1302. avpriv_color_frame(&pic->f, c);
  1303. h->cur_pic_ptr = pic;
  1304. unref_picture(h, &h->cur_pic);
  1305. if (CONFIG_ERROR_RESILIENCE) {
  1306. memset(&h->er.cur_pic, 0, sizeof(h->er.cur_pic));
  1307. }
  1308. if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
  1309. return ret;
  1310. if (CONFIG_ERROR_RESILIENCE) {
  1311. ff_er_frame_start(&h->er);
  1312. memset(&h->er.last_pic, 0, sizeof(h->er.last_pic));
  1313. memset(&h->er.next_pic, 0, sizeof(h->er.next_pic));
  1314. }
  1315. assert(h->linesize && h->uvlinesize);
  1316. for (i = 0; i < 16; i++) {
  1317. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1318. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1319. }
  1320. for (i = 0; i < 16; i++) {
  1321. h->block_offset[16 + i] =
  1322. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1323. h->block_offset[48 + 16 + i] =
  1324. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1325. }
  1326. // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1327. // h->cur_pic.reference /* || h->contains_intra */ || 1;
  1328. /* We mark the current picture as non-reference after allocating it, so
  1329. * that if we break out due to an error it can be released automatically
  1330. * in the next ff_MPV_frame_start().
  1331. */
  1332. h->cur_pic_ptr->reference = 0;
  1333. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1334. h->next_output_pic = NULL;
  1335. assert(h->cur_pic_ptr->long_ref == 0);
  1336. return 0;
  1337. }
  1338. /**
  1339. * Run setup operations that must be run after slice header decoding.
  1340. * This includes finding the next displayed frame.
  1341. *
  1342. * @param h h264 master context
  1343. * @param setup_finished enough NALs have been read that we can call
  1344. * ff_thread_finish_setup()
  1345. */
  1346. static void decode_postinit(H264Context *h, int setup_finished)
  1347. {
  1348. H264Picture *out = h->cur_pic_ptr;
  1349. H264Picture *cur = h->cur_pic_ptr;
  1350. int i, pics, out_of_order, out_idx;
  1351. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1352. if (h->next_output_pic)
  1353. return;
  1354. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1355. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1356. * the next thread here. If we have one field per packet, we can.
  1357. * The check in decode_nal_units() is not good enough to find this
  1358. * yet, so we assume the worst for now. */
  1359. // if (setup_finished)
  1360. // ff_thread_finish_setup(h->avctx);
  1361. return;
  1362. }
  1363. cur->f.interlaced_frame = 0;
  1364. cur->f.repeat_pict = 0;
  1365. /* Signal interlacing information externally. */
  1366. /* Prioritize picture timing SEI information over used
  1367. * decoding process if it exists. */
  1368. if (h->sps.pic_struct_present_flag) {
  1369. switch (h->sei_pic_struct) {
  1370. case SEI_PIC_STRUCT_FRAME:
  1371. break;
  1372. case SEI_PIC_STRUCT_TOP_FIELD:
  1373. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1374. cur->f.interlaced_frame = 1;
  1375. break;
  1376. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1377. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1378. if (FIELD_OR_MBAFF_PICTURE(h))
  1379. cur->f.interlaced_frame = 1;
  1380. else
  1381. // try to flag soft telecine progressive
  1382. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1383. break;
  1384. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1385. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1386. /* Signal the possibility of telecined film externally
  1387. * (pic_struct 5,6). From these hints, let the applications
  1388. * decide if they apply deinterlacing. */
  1389. cur->f.repeat_pict = 1;
  1390. break;
  1391. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1392. cur->f.repeat_pict = 2;
  1393. break;
  1394. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1395. cur->f.repeat_pict = 4;
  1396. break;
  1397. }
  1398. if ((h->sei_ct_type & 3) &&
  1399. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1400. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1401. } else {
  1402. /* Derive interlacing flag from used decoding process. */
  1403. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  1404. }
  1405. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1406. if (cur->field_poc[0] != cur->field_poc[1]) {
  1407. /* Derive top_field_first from field pocs. */
  1408. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1409. } else {
  1410. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1411. /* Use picture timing SEI information. Even if it is a
  1412. * information of a past frame, better than nothing. */
  1413. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1414. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1415. cur->f.top_field_first = 1;
  1416. else
  1417. cur->f.top_field_first = 0;
  1418. } else {
  1419. /* Most likely progressive */
  1420. cur->f.top_field_first = 0;
  1421. }
  1422. }
  1423. if (h->sei_frame_packing_present &&
  1424. h->frame_packing_arrangement_type >= 0 &&
  1425. h->frame_packing_arrangement_type <= 6 &&
  1426. h->content_interpretation_type > 0 &&
  1427. h->content_interpretation_type < 3) {
  1428. AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
  1429. if (!stereo)
  1430. return;
  1431. switch (h->frame_packing_arrangement_type) {
  1432. case 0:
  1433. stereo->type = AV_STEREO3D_CHECKERBOARD;
  1434. break;
  1435. case 1:
  1436. stereo->type = AV_STEREO3D_LINES;
  1437. break;
  1438. case 2:
  1439. stereo->type = AV_STEREO3D_COLUMNS;
  1440. break;
  1441. case 3:
  1442. if (h->quincunx_subsampling)
  1443. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  1444. else
  1445. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  1446. break;
  1447. case 4:
  1448. stereo->type = AV_STEREO3D_TOPBOTTOM;
  1449. break;
  1450. case 5:
  1451. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  1452. break;
  1453. case 6:
  1454. stereo->type = AV_STEREO3D_2D;
  1455. break;
  1456. }
  1457. if (h->content_interpretation_type == 2)
  1458. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  1459. }
  1460. cur->mmco_reset = h->mmco_reset;
  1461. h->mmco_reset = 0;
  1462. // FIXME do something with unavailable reference frames
  1463. /* Sort B-frames into display order */
  1464. if (h->sps.bitstream_restriction_flag &&
  1465. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1466. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1467. h->low_delay = 0;
  1468. }
  1469. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1470. !h->sps.bitstream_restriction_flag) {
  1471. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1472. h->low_delay = 0;
  1473. }
  1474. for (i = 0; 1; i++) {
  1475. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1476. if(i)
  1477. h->last_pocs[i-1] = cur->poc;
  1478. break;
  1479. } else if(i) {
  1480. h->last_pocs[i-1]= h->last_pocs[i];
  1481. }
  1482. }
  1483. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1484. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1485. || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
  1486. out_of_order = FFMAX(out_of_order, 1);
  1487. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1488. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1489. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1490. h->last_pocs[i] = INT_MIN;
  1491. h->last_pocs[0] = cur->poc;
  1492. cur->mmco_reset = 1;
  1493. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1494. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1495. h->avctx->has_b_frames = out_of_order;
  1496. h->low_delay = 0;
  1497. }
  1498. pics = 0;
  1499. while (h->delayed_pic[pics])
  1500. pics++;
  1501. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1502. h->delayed_pic[pics++] = cur;
  1503. if (cur->reference == 0)
  1504. cur->reference = DELAYED_PIC_REF;
  1505. out = h->delayed_pic[0];
  1506. out_idx = 0;
  1507. for (i = 1; h->delayed_pic[i] &&
  1508. !h->delayed_pic[i]->f.key_frame &&
  1509. !h->delayed_pic[i]->mmco_reset;
  1510. i++)
  1511. if (h->delayed_pic[i]->poc < out->poc) {
  1512. out = h->delayed_pic[i];
  1513. out_idx = i;
  1514. }
  1515. if (h->avctx->has_b_frames == 0 &&
  1516. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1517. h->next_outputed_poc = INT_MIN;
  1518. out_of_order = out->poc < h->next_outputed_poc;
  1519. if (out_of_order || pics > h->avctx->has_b_frames) {
  1520. out->reference &= ~DELAYED_PIC_REF;
  1521. // for frame threading, the owner must be the second field's thread or
  1522. // else the first thread can release the picture and reuse it unsafely
  1523. for (i = out_idx; h->delayed_pic[i]; i++)
  1524. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1525. }
  1526. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1527. h->next_output_pic = out;
  1528. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1529. h->next_outputed_poc = INT_MIN;
  1530. } else
  1531. h->next_outputed_poc = out->poc;
  1532. } else {
  1533. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1534. }
  1535. if (h->next_output_pic) {
  1536. if (h->next_output_pic->recovered) {
  1537. // We have reached an recovery point and all frames after it in
  1538. // display order are "recovered".
  1539. h->frame_recovered |= FRAME_RECOVERED_SEI;
  1540. }
  1541. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  1542. }
  1543. if (setup_finished && !h->avctx->hwaccel)
  1544. ff_thread_finish_setup(h->avctx);
  1545. }
  1546. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1547. uint8_t *src_cb, uint8_t *src_cr,
  1548. int linesize, int uvlinesize,
  1549. int simple)
  1550. {
  1551. uint8_t *top_border;
  1552. int top_idx = 1;
  1553. const int pixel_shift = h->pixel_shift;
  1554. int chroma444 = CHROMA444(h);
  1555. int chroma422 = CHROMA422(h);
  1556. src_y -= linesize;
  1557. src_cb -= uvlinesize;
  1558. src_cr -= uvlinesize;
  1559. if (!simple && FRAME_MBAFF(h)) {
  1560. if (h->mb_y & 1) {
  1561. if (!MB_MBAFF(h)) {
  1562. top_border = h->top_borders[0][h->mb_x];
  1563. AV_COPY128(top_border, src_y + 15 * linesize);
  1564. if (pixel_shift)
  1565. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1566. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1567. if (chroma444) {
  1568. if (pixel_shift) {
  1569. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1570. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1571. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1572. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1573. } else {
  1574. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1575. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1576. }
  1577. } else if (chroma422) {
  1578. if (pixel_shift) {
  1579. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1580. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1581. } else {
  1582. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1583. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1584. }
  1585. } else {
  1586. if (pixel_shift) {
  1587. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1588. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1589. } else {
  1590. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1591. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1592. }
  1593. }
  1594. }
  1595. }
  1596. } else if (MB_MBAFF(h)) {
  1597. top_idx = 0;
  1598. } else
  1599. return;
  1600. }
  1601. top_border = h->top_borders[top_idx][h->mb_x];
  1602. /* There are two lines saved, the line above the top macroblock
  1603. * of a pair, and the line above the bottom macroblock. */
  1604. AV_COPY128(top_border, src_y + 16 * linesize);
  1605. if (pixel_shift)
  1606. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1607. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1608. if (chroma444) {
  1609. if (pixel_shift) {
  1610. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1611. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1612. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1613. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1614. } else {
  1615. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1616. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1617. }
  1618. } else if (chroma422) {
  1619. if (pixel_shift) {
  1620. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1621. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1622. } else {
  1623. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1624. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1625. }
  1626. } else {
  1627. if (pixel_shift) {
  1628. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1629. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1630. } else {
  1631. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1632. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1633. }
  1634. }
  1635. }
  1636. }
  1637. int ff_pred_weight_table(H264Context *h)
  1638. {
  1639. int list, i;
  1640. int luma_def, chroma_def;
  1641. h->use_weight = 0;
  1642. h->use_weight_chroma = 0;
  1643. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  1644. if (h->sps.chroma_format_idc)
  1645. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  1646. luma_def = 1 << h->luma_log2_weight_denom;
  1647. chroma_def = 1 << h->chroma_log2_weight_denom;
  1648. for (list = 0; list < 2; list++) {
  1649. h->luma_weight_flag[list] = 0;
  1650. h->chroma_weight_flag[list] = 0;
  1651. for (i = 0; i < h->ref_count[list]; i++) {
  1652. int luma_weight_flag, chroma_weight_flag;
  1653. luma_weight_flag = get_bits1(&h->gb);
  1654. if (luma_weight_flag) {
  1655. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  1656. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  1657. if (h->luma_weight[i][list][0] != luma_def ||
  1658. h->luma_weight[i][list][1] != 0) {
  1659. h->use_weight = 1;
  1660. h->luma_weight_flag[list] = 1;
  1661. }
  1662. } else {
  1663. h->luma_weight[i][list][0] = luma_def;
  1664. h->luma_weight[i][list][1] = 0;
  1665. }
  1666. if (h->sps.chroma_format_idc) {
  1667. chroma_weight_flag = get_bits1(&h->gb);
  1668. if (chroma_weight_flag) {
  1669. int j;
  1670. for (j = 0; j < 2; j++) {
  1671. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  1672. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  1673. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  1674. h->chroma_weight[i][list][j][1] != 0) {
  1675. h->use_weight_chroma = 1;
  1676. h->chroma_weight_flag[list] = 1;
  1677. }
  1678. }
  1679. } else {
  1680. int j;
  1681. for (j = 0; j < 2; j++) {
  1682. h->chroma_weight[i][list][j][0] = chroma_def;
  1683. h->chroma_weight[i][list][j][1] = 0;
  1684. }
  1685. }
  1686. }
  1687. }
  1688. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  1689. break;
  1690. }
  1691. h->use_weight = h->use_weight || h->use_weight_chroma;
  1692. return 0;
  1693. }
  1694. /**
  1695. * Initialize implicit_weight table.
  1696. * @param field 0/1 initialize the weight for interlaced MBAFF
  1697. * -1 initializes the rest
  1698. */
  1699. static void implicit_weight_table(H264Context *h, int field)
  1700. {
  1701. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  1702. for (i = 0; i < 2; i++) {
  1703. h->luma_weight_flag[i] = 0;
  1704. h->chroma_weight_flag[i] = 0;
  1705. }
  1706. if (field < 0) {
  1707. if (h->picture_structure == PICT_FRAME) {
  1708. cur_poc = h->cur_pic_ptr->poc;
  1709. } else {
  1710. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  1711. }
  1712. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
  1713. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  1714. h->use_weight = 0;
  1715. h->use_weight_chroma = 0;
  1716. return;
  1717. }
  1718. ref_start = 0;
  1719. ref_count0 = h->ref_count[0];
  1720. ref_count1 = h->ref_count[1];
  1721. } else {
  1722. cur_poc = h->cur_pic_ptr->field_poc[field];
  1723. ref_start = 16;
  1724. ref_count0 = 16 + 2 * h->ref_count[0];
  1725. ref_count1 = 16 + 2 * h->ref_count[1];
  1726. }
  1727. h->use_weight = 2;
  1728. h->use_weight_chroma = 2;
  1729. h->luma_log2_weight_denom = 5;
  1730. h->chroma_log2_weight_denom = 5;
  1731. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  1732. int poc0 = h->ref_list[0][ref0].poc;
  1733. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  1734. int w = 32;
  1735. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  1736. int poc1 = h->ref_list[1][ref1].poc;
  1737. int td = av_clip(poc1 - poc0, -128, 127);
  1738. if (td) {
  1739. int tb = av_clip(cur_poc - poc0, -128, 127);
  1740. int tx = (16384 + (FFABS(td) >> 1)) / td;
  1741. int dist_scale_factor = (tb * tx + 32) >> 8;
  1742. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  1743. w = 64 - dist_scale_factor;
  1744. }
  1745. }
  1746. if (field < 0) {
  1747. h->implicit_weight[ref0][ref1][0] =
  1748. h->implicit_weight[ref0][ref1][1] = w;
  1749. } else {
  1750. h->implicit_weight[ref0][ref1][field] = w;
  1751. }
  1752. }
  1753. }
  1754. }
  1755. /**
  1756. * instantaneous decoder refresh.
  1757. */
  1758. static void idr(H264Context *h)
  1759. {
  1760. int i;
  1761. ff_h264_remove_all_refs(h);
  1762. h->prev_frame_num = 0;
  1763. h->prev_frame_num_offset = 0;
  1764. h->prev_poc_msb = 1<<16;
  1765. h->prev_poc_lsb = 0;
  1766. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1767. h->last_pocs[i] = INT_MIN;
  1768. }
  1769. /* forget old pics after a seek */
  1770. static void flush_change(H264Context *h)
  1771. {
  1772. int i, j;
  1773. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1774. h->prev_interlaced_frame = 1;
  1775. idr(h);
  1776. h->prev_frame_num = -1;
  1777. if (h->cur_pic_ptr) {
  1778. h->cur_pic_ptr->reference = 0;
  1779. for (j=i=0; h->delayed_pic[i]; i++)
  1780. if (h->delayed_pic[i] != h->cur_pic_ptr)
  1781. h->delayed_pic[j++] = h->delayed_pic[i];
  1782. h->delayed_pic[j] = NULL;
  1783. }
  1784. h->first_field = 0;
  1785. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  1786. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  1787. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  1788. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  1789. ff_h264_reset_sei(h);
  1790. h->recovery_frame = -1;
  1791. h->frame_recovered = 0;
  1792. h->list_count = 0;
  1793. h->current_slice = 0;
  1794. h->mmco_reset = 1;
  1795. }
  1796. /* forget old pics after a seek */
  1797. static void flush_dpb(AVCodecContext *avctx)
  1798. {
  1799. H264Context *h = avctx->priv_data;
  1800. int i;
  1801. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  1802. if (h->delayed_pic[i])
  1803. h->delayed_pic[i]->reference = 0;
  1804. h->delayed_pic[i] = NULL;
  1805. }
  1806. flush_change(h);
  1807. if (h->DPB)
  1808. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  1809. unref_picture(h, &h->DPB[i]);
  1810. h->cur_pic_ptr = NULL;
  1811. unref_picture(h, &h->cur_pic);
  1812. h->mb_x = h->mb_y = 0;
  1813. h->parse_context.state = -1;
  1814. h->parse_context.frame_start_found = 0;
  1815. h->parse_context.overread = 0;
  1816. h->parse_context.overread_index = 0;
  1817. h->parse_context.index = 0;
  1818. h->parse_context.last_index = 0;
  1819. free_tables(h, 1);
  1820. h->context_initialized = 0;
  1821. }
  1822. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  1823. {
  1824. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  1825. int field_poc[2];
  1826. h->frame_num_offset = h->prev_frame_num_offset;
  1827. if (h->frame_num < h->prev_frame_num)
  1828. h->frame_num_offset += max_frame_num;
  1829. if (h->sps.poc_type == 0) {
  1830. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  1831. if (h->poc_lsb < h->prev_poc_lsb &&
  1832. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  1833. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  1834. else if (h->poc_lsb > h->prev_poc_lsb &&
  1835. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  1836. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  1837. else
  1838. h->poc_msb = h->prev_poc_msb;
  1839. field_poc[0] =
  1840. field_poc[1] = h->poc_msb + h->poc_lsb;
  1841. if (h->picture_structure == PICT_FRAME)
  1842. field_poc[1] += h->delta_poc_bottom;
  1843. } else if (h->sps.poc_type == 1) {
  1844. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1845. int i;
  1846. if (h->sps.poc_cycle_length != 0)
  1847. abs_frame_num = h->frame_num_offset + h->frame_num;
  1848. else
  1849. abs_frame_num = 0;
  1850. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1851. abs_frame_num--;
  1852. expected_delta_per_poc_cycle = 0;
  1853. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1854. // FIXME integrate during sps parse
  1855. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1856. if (abs_frame_num > 0) {
  1857. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1858. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1859. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1860. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1861. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1862. } else
  1863. expectedpoc = 0;
  1864. if (h->nal_ref_idc == 0)
  1865. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1866. field_poc[0] = expectedpoc + h->delta_poc[0];
  1867. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1868. if (h->picture_structure == PICT_FRAME)
  1869. field_poc[1] += h->delta_poc[1];
  1870. } else {
  1871. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1872. if (!h->nal_ref_idc)
  1873. poc--;
  1874. field_poc[0] = poc;
  1875. field_poc[1] = poc;
  1876. }
  1877. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1878. pic_field_poc[0] = field_poc[0];
  1879. if (h->picture_structure != PICT_TOP_FIELD)
  1880. pic_field_poc[1] = field_poc[1];
  1881. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1882. return 0;
  1883. }
  1884. /**
  1885. * initialize scan tables
  1886. */
  1887. static void init_scan_tables(H264Context *h)
  1888. {
  1889. int i;
  1890. for (i = 0; i < 16; i++) {
  1891. #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
  1892. h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
  1893. h->field_scan[i] = TRANSPOSE(field_scan[i]);
  1894. #undef TRANSPOSE
  1895. }
  1896. for (i = 0; i < 64; i++) {
  1897. #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
  1898. h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
  1899. h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
  1900. h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
  1901. h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
  1902. #undef TRANSPOSE
  1903. }
  1904. if (h->sps.transform_bypass) { // FIXME same ugly
  1905. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  1906. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  1907. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  1908. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  1909. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  1910. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  1911. } else {
  1912. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  1913. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  1914. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  1915. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  1916. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  1917. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  1918. }
  1919. }
  1920. #if CONFIG_ERROR_RESILIENCE
  1921. static void h264_set_erpic(ERPicture *dst, H264Picture *src)
  1922. {
  1923. int i;
  1924. memset(dst, 0, sizeof(*dst));
  1925. if (!src)
  1926. return;
  1927. dst->f = &src->f;
  1928. dst->tf = &src->tf;
  1929. for (i = 0; i < 2; i++) {
  1930. dst->motion_val[i] = src->motion_val[i];
  1931. dst->ref_index[i] = src->ref_index[i];
  1932. }
  1933. dst->mb_type = src->mb_type;
  1934. dst->field_picture = src->field_picture;
  1935. }
  1936. #endif /* CONFIG_ERROR_RESILIENCE */
  1937. static int field_end(H264Context *h, int in_setup)
  1938. {
  1939. AVCodecContext *const avctx = h->avctx;
  1940. int err = 0;
  1941. h->mb_y = 0;
  1942. if (CONFIG_H264_VDPAU_DECODER &&
  1943. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  1944. ff_vdpau_h264_set_reference_frames(h);
  1945. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  1946. if (!h->droppable) {
  1947. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1948. h->prev_poc_msb = h->poc_msb;
  1949. h->prev_poc_lsb = h->poc_lsb;
  1950. }
  1951. h->prev_frame_num_offset = h->frame_num_offset;
  1952. h->prev_frame_num = h->frame_num;
  1953. h->outputed_poc = h->next_outputed_poc;
  1954. }
  1955. if (avctx->hwaccel) {
  1956. if (avctx->hwaccel->end_frame(avctx) < 0)
  1957. av_log(avctx, AV_LOG_ERROR,
  1958. "hardware accelerator failed to decode picture\n");
  1959. }
  1960. if (CONFIG_H264_VDPAU_DECODER &&
  1961. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  1962. ff_vdpau_h264_picture_complete(h);
  1963. /*
  1964. * FIXME: Error handling code does not seem to support interlaced
  1965. * when slices span multiple rows
  1966. * The ff_er_add_slice calls don't work right for bottom
  1967. * fields; they cause massive erroneous error concealing
  1968. * Error marking covers both fields (top and bottom).
  1969. * This causes a mismatched s->error_count
  1970. * and a bad error table. Further, the error count goes to
  1971. * INT_MAX when called for bottom field, because mb_y is
  1972. * past end by one (callers fault) and resync_mb_y != 0
  1973. * causes problems for the first MB line, too.
  1974. */
  1975. if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
  1976. h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
  1977. ff_er_frame_end(&h->er);
  1978. }
  1979. if (!in_setup && !h->droppable)
  1980. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1981. h->picture_structure == PICT_BOTTOM_FIELD);
  1982. emms_c();
  1983. h->current_slice = 0;
  1984. return err;
  1985. }
  1986. /**
  1987. * Replicate H264 "master" context to thread contexts.
  1988. */
  1989. static int clone_slice(H264Context *dst, H264Context *src)
  1990. {
  1991. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  1992. dst->cur_pic_ptr = src->cur_pic_ptr;
  1993. dst->cur_pic = src->cur_pic;
  1994. dst->linesize = src->linesize;
  1995. dst->uvlinesize = src->uvlinesize;
  1996. dst->first_field = src->first_field;
  1997. dst->prev_poc_msb = src->prev_poc_msb;
  1998. dst->prev_poc_lsb = src->prev_poc_lsb;
  1999. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2000. dst->prev_frame_num = src->prev_frame_num;
  2001. dst->short_ref_count = src->short_ref_count;
  2002. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2003. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2004. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2005. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2006. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2007. return 0;
  2008. }
  2009. /**
  2010. * Compute profile from profile_idc and constraint_set?_flags.
  2011. *
  2012. * @param sps SPS
  2013. *
  2014. * @return profile as defined by FF_PROFILE_H264_*
  2015. */
  2016. int ff_h264_get_profile(SPS *sps)
  2017. {
  2018. int profile = sps->profile_idc;
  2019. switch (sps->profile_idc) {
  2020. case FF_PROFILE_H264_BASELINE:
  2021. // constraint_set1_flag set to 1
  2022. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2023. break;
  2024. case FF_PROFILE_H264_HIGH_10:
  2025. case FF_PROFILE_H264_HIGH_422:
  2026. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2027. // constraint_set3_flag set to 1
  2028. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2029. break;
  2030. }
  2031. return profile;
  2032. }
  2033. static int h264_set_parameter_from_sps(H264Context *h)
  2034. {
  2035. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  2036. (h->sps.bitstream_restriction_flag &&
  2037. !h->sps.num_reorder_frames)) {
  2038. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2039. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2040. "Reenabling low delay requires a codec flush.\n");
  2041. else
  2042. h->low_delay = 1;
  2043. }
  2044. if (h->avctx->has_b_frames < 2)
  2045. h->avctx->has_b_frames = !h->low_delay;
  2046. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2047. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2048. if (h->avctx->codec &&
  2049. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2050. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2051. av_log(h->avctx, AV_LOG_ERROR,
  2052. "VDPAU decoding does not support video colorspace.\n");
  2053. return AVERROR_INVALIDDATA;
  2054. }
  2055. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  2056. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
  2057. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2058. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2059. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2060. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2061. h->sps.chroma_format_idc);
  2062. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  2063. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  2064. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  2065. h->sps.chroma_format_idc);
  2066. if (CONFIG_ERROR_RESILIENCE)
  2067. ff_dsputil_init(&h->dsp, h->avctx);
  2068. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  2069. } else {
  2070. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  2071. h->sps.bit_depth_luma);
  2072. return AVERROR_INVALIDDATA;
  2073. }
  2074. }
  2075. return 0;
  2076. }
  2077. static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
  2078. {
  2079. switch (h->sps.bit_depth_luma) {
  2080. case 9:
  2081. if (CHROMA444(h)) {
  2082. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2083. return AV_PIX_FMT_GBRP9;
  2084. } else
  2085. return AV_PIX_FMT_YUV444P9;
  2086. } else if (CHROMA422(h))
  2087. return AV_PIX_FMT_YUV422P9;
  2088. else
  2089. return AV_PIX_FMT_YUV420P9;
  2090. break;
  2091. case 10:
  2092. if (CHROMA444(h)) {
  2093. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2094. return AV_PIX_FMT_GBRP10;
  2095. } else
  2096. return AV_PIX_FMT_YUV444P10;
  2097. } else if (CHROMA422(h))
  2098. return AV_PIX_FMT_YUV422P10;
  2099. else
  2100. return AV_PIX_FMT_YUV420P10;
  2101. break;
  2102. case 12:
  2103. if (CHROMA444(h)) {
  2104. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2105. return AV_PIX_FMT_GBRP12;
  2106. } else
  2107. return AV_PIX_FMT_YUV444P12;
  2108. } else if (CHROMA422(h))
  2109. return AV_PIX_FMT_YUV422P12;
  2110. else
  2111. return AV_PIX_FMT_YUV420P12;
  2112. break;
  2113. case 14:
  2114. if (CHROMA444(h)) {
  2115. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2116. return AV_PIX_FMT_GBRP14;
  2117. } else
  2118. return AV_PIX_FMT_YUV444P14;
  2119. } else if (CHROMA422(h))
  2120. return AV_PIX_FMT_YUV422P14;
  2121. else
  2122. return AV_PIX_FMT_YUV420P14;
  2123. break;
  2124. case 8:
  2125. if (CHROMA444(h)) {
  2126. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2127. av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2128. return AV_PIX_FMT_GBR24P;
  2129. } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2130. av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2131. }
  2132. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2133. : AV_PIX_FMT_YUV444P;
  2134. } else if (CHROMA422(h)) {
  2135. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2136. : AV_PIX_FMT_YUV422P;
  2137. } else {
  2138. int i;
  2139. const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
  2140. h->avctx->codec->pix_fmts :
  2141. h->avctx->color_range == AVCOL_RANGE_JPEG ?
  2142. h264_hwaccel_pixfmt_list_jpeg_420 :
  2143. h264_hwaccel_pixfmt_list_420;
  2144. for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
  2145. if (fmt[i] == h->avctx->pix_fmt && !force_callback)
  2146. return fmt[i];
  2147. return ff_thread_get_format(h->avctx, fmt);
  2148. }
  2149. break;
  2150. default:
  2151. av_log(h->avctx, AV_LOG_ERROR,
  2152. "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
  2153. return AVERROR_INVALIDDATA;
  2154. }
  2155. }
  2156. /* export coded and cropped frame dimensions to AVCodecContext */
  2157. static int init_dimensions(H264Context *h)
  2158. {
  2159. int width = h->width - (h->sps.crop_right + h->sps.crop_left);
  2160. int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
  2161. av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
  2162. av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
  2163. /* handle container cropping */
  2164. if (!h->sps.crop &&
  2165. FFALIGN(h->avctx->width, 16) == h->width &&
  2166. FFALIGN(h->avctx->height, 16) == h->height) {
  2167. width = h->avctx->width;
  2168. height = h->avctx->height;
  2169. }
  2170. if (width <= 0 || height <= 0) {
  2171. av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
  2172. width, height);
  2173. if (h->avctx->err_recognition & AV_EF_EXPLODE)
  2174. return AVERROR_INVALIDDATA;
  2175. av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
  2176. h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
  2177. h->sps.crop = 0;
  2178. width = h->width;
  2179. height = h->height;
  2180. }
  2181. h->avctx->coded_width = h->width;
  2182. h->avctx->coded_height = h->height;
  2183. h->avctx->width = width;
  2184. h->avctx->height = height;
  2185. return 0;
  2186. }
  2187. static int h264_slice_header_init(H264Context *h, int reinit)
  2188. {
  2189. int nb_slices = (HAVE_THREADS &&
  2190. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  2191. h->avctx->thread_count : 1;
  2192. int i, ret;
  2193. h->avctx->sample_aspect_ratio = h->sps.sar;
  2194. av_assert0(h->avctx->sample_aspect_ratio.den);
  2195. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  2196. &h->chroma_x_shift, &h->chroma_y_shift);
  2197. if (h->sps.timing_info_present_flag) {
  2198. int64_t den = h->sps.time_scale;
  2199. if (h->x264_build < 44U)
  2200. den *= 2;
  2201. av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
  2202. h->sps.num_units_in_tick, den, 1 << 30);
  2203. }
  2204. h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
  2205. if (reinit)
  2206. free_tables(h, 0);
  2207. h->first_field = 0;
  2208. h->prev_interlaced_frame = 1;
  2209. init_scan_tables(h);
  2210. ret = ff_h264_alloc_tables(h);
  2211. if (ret < 0) {
  2212. av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
  2213. return ret;
  2214. }
  2215. if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  2216. int max_slices;
  2217. if (h->mb_height)
  2218. max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
  2219. else
  2220. max_slices = H264_MAX_THREADS;
  2221. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
  2222. " reducing to %d\n", nb_slices, max_slices);
  2223. nb_slices = max_slices;
  2224. }
  2225. h->slice_context_count = nb_slices;
  2226. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2227. ret = context_init(h);
  2228. if (ret < 0) {
  2229. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2230. return ret;
  2231. }
  2232. } else {
  2233. for (i = 1; i < h->slice_context_count; i++) {
  2234. H264Context *c;
  2235. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  2236. if (!c)
  2237. return AVERROR(ENOMEM);
  2238. c->avctx = h->avctx;
  2239. if (CONFIG_ERROR_RESILIENCE) {
  2240. c->dsp = h->dsp;
  2241. }
  2242. c->vdsp = h->vdsp;
  2243. c->h264dsp = h->h264dsp;
  2244. c->h264qpel = h->h264qpel;
  2245. c->h264chroma = h->h264chroma;
  2246. c->sps = h->sps;
  2247. c->pps = h->pps;
  2248. c->pixel_shift = h->pixel_shift;
  2249. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2250. c->width = h->width;
  2251. c->height = h->height;
  2252. c->linesize = h->linesize;
  2253. c->uvlinesize = h->uvlinesize;
  2254. c->chroma_x_shift = h->chroma_x_shift;
  2255. c->chroma_y_shift = h->chroma_y_shift;
  2256. c->qscale = h->qscale;
  2257. c->droppable = h->droppable;
  2258. c->data_partitioning = h->data_partitioning;
  2259. c->low_delay = h->low_delay;
  2260. c->mb_width = h->mb_width;
  2261. c->mb_height = h->mb_height;
  2262. c->mb_stride = h->mb_stride;
  2263. c->mb_num = h->mb_num;
  2264. c->flags = h->flags;
  2265. c->workaround_bugs = h->workaround_bugs;
  2266. c->pict_type = h->pict_type;
  2267. init_scan_tables(c);
  2268. clone_tables(c, h, i);
  2269. c->context_initialized = 1;
  2270. }
  2271. for (i = 0; i < h->slice_context_count; i++)
  2272. if ((ret = context_init(h->thread_context[i])) < 0) {
  2273. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2274. return ret;
  2275. }
  2276. }
  2277. h->context_initialized = 1;
  2278. return 0;
  2279. }
  2280. int ff_set_ref_count(H264Context *h)
  2281. {
  2282. int ref_count[2], list_count;
  2283. int num_ref_idx_active_override_flag;
  2284. // set defaults, might be overridden a few lines later
  2285. ref_count[0] = h->pps.ref_count[0];
  2286. ref_count[1] = h->pps.ref_count[1];
  2287. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2288. unsigned max[2];
  2289. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  2290. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2291. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  2292. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  2293. if (num_ref_idx_active_override_flag) {
  2294. ref_count[0] = get_ue_golomb(&h->gb) + 1;
  2295. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2296. ref_count[1] = get_ue_golomb(&h->gb) + 1;
  2297. } else
  2298. // full range is spec-ok in this case, even for frames
  2299. ref_count[1] = 1;
  2300. }
  2301. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  2302. av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
  2303. h->ref_count[0] = h->ref_count[1] = 0;
  2304. h->list_count = 0;
  2305. return AVERROR_INVALIDDATA;
  2306. }
  2307. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2308. list_count = 2;
  2309. else
  2310. list_count = 1;
  2311. } else {
  2312. list_count = 0;
  2313. ref_count[0] = ref_count[1] = 0;
  2314. }
  2315. if (list_count != h->list_count ||
  2316. ref_count[0] != h->ref_count[0] ||
  2317. ref_count[1] != h->ref_count[1]) {
  2318. h->ref_count[0] = ref_count[0];
  2319. h->ref_count[1] = ref_count[1];
  2320. h->list_count = list_count;
  2321. return 1;
  2322. }
  2323. return 0;
  2324. }
  2325. static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
  2326. {
  2327. switch (a) {
  2328. case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
  2329. case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
  2330. case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
  2331. default:
  2332. return a;
  2333. }
  2334. }
  2335. /**
  2336. * Decode a slice header.
  2337. * This will (re)intialize the decoder and call h264_frame_start() as needed.
  2338. *
  2339. * @param h h264context
  2340. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2341. * parallel decoding)
  2342. *
  2343. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2344. */
  2345. static int decode_slice_header(H264Context *h, H264Context *h0)
  2346. {
  2347. unsigned int first_mb_in_slice;
  2348. unsigned int pps_id;
  2349. int ret;
  2350. unsigned int slice_type, tmp, i, j;
  2351. int last_pic_structure, last_pic_droppable;
  2352. int must_reinit;
  2353. int needs_reinit = 0;
  2354. int field_pic_flag, bottom_field_flag;
  2355. h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  2356. h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  2357. first_mb_in_slice = get_ue_golomb_long(&h->gb);
  2358. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2359. if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
  2360. field_end(h, 1);
  2361. }
  2362. h0->current_slice = 0;
  2363. if (!h0->first_field) {
  2364. if (h->cur_pic_ptr && !h->droppable) {
  2365. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  2366. h->picture_structure == PICT_BOTTOM_FIELD);
  2367. }
  2368. h->cur_pic_ptr = NULL;
  2369. }
  2370. }
  2371. slice_type = get_ue_golomb_31(&h->gb);
  2372. if (slice_type > 9) {
  2373. av_log(h->avctx, AV_LOG_ERROR,
  2374. "slice type %d too large at %d %d\n",
  2375. slice_type, h->mb_x, h->mb_y);
  2376. return AVERROR_INVALIDDATA;
  2377. }
  2378. if (slice_type > 4) {
  2379. slice_type -= 5;
  2380. h->slice_type_fixed = 1;
  2381. } else
  2382. h->slice_type_fixed = 0;
  2383. slice_type = golomb_to_pict_type[slice_type];
  2384. h->slice_type = slice_type;
  2385. h->slice_type_nos = slice_type & 3;
  2386. if (h->nal_unit_type == NAL_IDR_SLICE &&
  2387. h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2388. av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
  2389. return AVERROR_INVALIDDATA;
  2390. }
  2391. // to make a few old functions happy, it's wrong though
  2392. h->pict_type = h->slice_type;
  2393. pps_id = get_ue_golomb(&h->gb);
  2394. if (pps_id >= MAX_PPS_COUNT) {
  2395. av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
  2396. return AVERROR_INVALIDDATA;
  2397. }
  2398. if (!h0->pps_buffers[pps_id]) {
  2399. av_log(h->avctx, AV_LOG_ERROR,
  2400. "non-existing PPS %u referenced\n",
  2401. pps_id);
  2402. return AVERROR_INVALIDDATA;
  2403. }
  2404. if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
  2405. av_log(h->avctx, AV_LOG_ERROR,
  2406. "PPS change from %d to %d forbidden\n",
  2407. h0->au_pps_id, pps_id);
  2408. return AVERROR_INVALIDDATA;
  2409. }
  2410. h->pps = *h0->pps_buffers[pps_id];
  2411. if (!h0->sps_buffers[h->pps.sps_id]) {
  2412. av_log(h->avctx, AV_LOG_ERROR,
  2413. "non-existing SPS %u referenced\n",
  2414. h->pps.sps_id);
  2415. return AVERROR_INVALIDDATA;
  2416. }
  2417. if (h->pps.sps_id != h->sps.sps_id ||
  2418. h->pps.sps_id != h->current_sps_id ||
  2419. h0->sps_buffers[h->pps.sps_id]->new) {
  2420. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2421. if (h->mb_width != h->sps.mb_width ||
  2422. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
  2423. h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2424. h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2425. )
  2426. needs_reinit = 1;
  2427. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  2428. h->chroma_format_idc != h->sps.chroma_format_idc) {
  2429. h->bit_depth_luma = h->sps.bit_depth_luma;
  2430. h->chroma_format_idc = h->sps.chroma_format_idc;
  2431. needs_reinit = 1;
  2432. }
  2433. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  2434. return ret;
  2435. }
  2436. h->avctx->profile = ff_h264_get_profile(&h->sps);
  2437. h->avctx->level = h->sps.level_idc;
  2438. h->avctx->refs = h->sps.ref_frame_count;
  2439. must_reinit = (h->context_initialized &&
  2440. ( 16*h->sps.mb_width != h->avctx->coded_width
  2441. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
  2442. || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2443. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2444. || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
  2445. || h->mb_width != h->sps.mb_width
  2446. || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
  2447. ));
  2448. if (non_j_pixfmt(h0->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h0, 0)))
  2449. must_reinit = 1;
  2450. h->mb_width = h->sps.mb_width;
  2451. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2452. h->mb_num = h->mb_width * h->mb_height;
  2453. h->mb_stride = h->mb_width + 1;
  2454. h->b_stride = h->mb_width * 4;
  2455. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2456. h->width = 16 * h->mb_width;
  2457. h->height = 16 * h->mb_height;
  2458. ret = init_dimensions(h);
  2459. if (ret < 0)
  2460. return ret;
  2461. if (h->sps.video_signal_type_present_flag) {
  2462. h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  2463. : AVCOL_RANGE_MPEG;
  2464. if (h->sps.colour_description_present_flag) {
  2465. if (h->avctx->colorspace != h->sps.colorspace)
  2466. needs_reinit = 1;
  2467. h->avctx->color_primaries = h->sps.color_primaries;
  2468. h->avctx->color_trc = h->sps.color_trc;
  2469. h->avctx->colorspace = h->sps.colorspace;
  2470. }
  2471. }
  2472. if (h->context_initialized &&
  2473. (h->width != h->avctx->coded_width ||
  2474. h->height != h->avctx->coded_height ||
  2475. must_reinit ||
  2476. needs_reinit)) {
  2477. if (h != h0) {
  2478. av_log(h->avctx, AV_LOG_ERROR,
  2479. "changing width %d -> %d / height %d -> %d on "
  2480. "slice %d\n",
  2481. h->width, h->avctx->coded_width,
  2482. h->height, h->avctx->coded_height,
  2483. h0->current_slice + 1);
  2484. return AVERROR_INVALIDDATA;
  2485. }
  2486. flush_change(h);
  2487. if ((ret = get_pixel_format(h, 1)) < 0)
  2488. return ret;
  2489. h->avctx->pix_fmt = ret;
  2490. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  2491. "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
  2492. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  2493. av_log(h->avctx, AV_LOG_ERROR,
  2494. "h264_slice_header_init() failed\n");
  2495. return ret;
  2496. }
  2497. }
  2498. if (!h->context_initialized) {
  2499. if (h != h0) {
  2500. av_log(h->avctx, AV_LOG_ERROR,
  2501. "Cannot (re-)initialize context during parallel decoding.\n");
  2502. return AVERROR_PATCHWELCOME;
  2503. }
  2504. if ((ret = get_pixel_format(h, 1)) < 0)
  2505. return ret;
  2506. h->avctx->pix_fmt = ret;
  2507. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  2508. av_log(h->avctx, AV_LOG_ERROR,
  2509. "h264_slice_header_init() failed\n");
  2510. return ret;
  2511. }
  2512. }
  2513. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2514. h->dequant_coeff_pps = pps_id;
  2515. init_dequant_tables(h);
  2516. }
  2517. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  2518. h->mb_mbaff = 0;
  2519. h->mb_aff_frame = 0;
  2520. last_pic_structure = h0->picture_structure;
  2521. last_pic_droppable = h0->droppable;
  2522. h->droppable = h->nal_ref_idc == 0;
  2523. if (h->sps.frame_mbs_only_flag) {
  2524. h->picture_structure = PICT_FRAME;
  2525. } else {
  2526. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  2527. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2528. return -1;
  2529. }
  2530. field_pic_flag = get_bits1(&h->gb);
  2531. if (field_pic_flag) {
  2532. bottom_field_flag = get_bits1(&h->gb);
  2533. h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
  2534. } else {
  2535. h->picture_structure = PICT_FRAME;
  2536. h->mb_aff_frame = h->sps.mb_aff;
  2537. }
  2538. }
  2539. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  2540. if (h0->current_slice != 0) {
  2541. if (last_pic_structure != h->picture_structure ||
  2542. last_pic_droppable != h->droppable) {
  2543. av_log(h->avctx, AV_LOG_ERROR,
  2544. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2545. last_pic_structure, h->picture_structure);
  2546. h->picture_structure = last_pic_structure;
  2547. h->droppable = last_pic_droppable;
  2548. return AVERROR_INVALIDDATA;
  2549. } else if (!h0->cur_pic_ptr) {
  2550. av_log(h->avctx, AV_LOG_ERROR,
  2551. "unset cur_pic_ptr on slice %d\n",
  2552. h0->current_slice + 1);
  2553. return AVERROR_INVALIDDATA;
  2554. }
  2555. } else {
  2556. /* Shorten frame num gaps so we don't have to allocate reference
  2557. * frames just to throw them away */
  2558. if (h->frame_num != h->prev_frame_num) {
  2559. int unwrap_prev_frame_num = h->prev_frame_num;
  2560. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2561. if (unwrap_prev_frame_num > h->frame_num)
  2562. unwrap_prev_frame_num -= max_frame_num;
  2563. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2564. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2565. if (unwrap_prev_frame_num < 0)
  2566. unwrap_prev_frame_num += max_frame_num;
  2567. h->prev_frame_num = unwrap_prev_frame_num;
  2568. }
  2569. }
  2570. /* See if we have a decoded first field looking for a pair...
  2571. * Here, we're using that to see if we should mark previously
  2572. * decode frames as "finished".
  2573. * We have to do that before the "dummy" in-between frame allocation,
  2574. * since that can modify h->cur_pic_ptr. */
  2575. if (h0->first_field) {
  2576. assert(h0->cur_pic_ptr);
  2577. assert(h0->cur_pic_ptr->f.buf[0]);
  2578. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  2579. /* Mark old field/frame as completed */
  2580. if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
  2581. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  2582. last_pic_structure == PICT_BOTTOM_FIELD);
  2583. }
  2584. /* figure out if we have a complementary field pair */
  2585. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  2586. /* Previous field is unmatched. Don't display it, but let it
  2587. * remain for reference if marked as such. */
  2588. if (last_pic_structure != PICT_FRAME) {
  2589. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  2590. last_pic_structure == PICT_TOP_FIELD);
  2591. }
  2592. } else {
  2593. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2594. /* This and previous field were reference, but had
  2595. * different frame_nums. Consider this field first in
  2596. * pair. Throw away previous field except for reference
  2597. * purposes. */
  2598. if (last_pic_structure != PICT_FRAME) {
  2599. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  2600. last_pic_structure == PICT_TOP_FIELD);
  2601. }
  2602. } else {
  2603. /* Second field in complementary pair */
  2604. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2605. h->picture_structure == PICT_BOTTOM_FIELD) ||
  2606. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2607. h->picture_structure == PICT_TOP_FIELD))) {
  2608. av_log(h->avctx, AV_LOG_ERROR,
  2609. "Invalid field mode combination %d/%d\n",
  2610. last_pic_structure, h->picture_structure);
  2611. h->picture_structure = last_pic_structure;
  2612. h->droppable = last_pic_droppable;
  2613. return AVERROR_INVALIDDATA;
  2614. } else if (last_pic_droppable != h->droppable) {
  2615. avpriv_request_sample(h->avctx,
  2616. "Found reference and non-reference fields in the same frame, which");
  2617. h->picture_structure = last_pic_structure;
  2618. h->droppable = last_pic_droppable;
  2619. return AVERROR_PATCHWELCOME;
  2620. }
  2621. }
  2622. }
  2623. }
  2624. while (h->frame_num != h->prev_frame_num && !h0->first_field &&
  2625. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2626. H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2627. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2628. h->frame_num, h->prev_frame_num);
  2629. if (!h->sps.gaps_in_frame_num_allowed_flag)
  2630. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  2631. h->last_pocs[i] = INT_MIN;
  2632. ret = h264_frame_start(h);
  2633. if (ret < 0) {
  2634. h0->first_field = 0;
  2635. return ret;
  2636. }
  2637. h->prev_frame_num++;
  2638. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2639. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  2640. h->cur_pic_ptr->invalid_gap = !h->sps.gaps_in_frame_num_allowed_flag;
  2641. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  2642. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  2643. ret = ff_generate_sliding_window_mmcos(h, 1);
  2644. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  2645. return ret;
  2646. ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2647. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  2648. return ret;
  2649. /* Error concealment: If a ref is missing, copy the previous ref
  2650. * in its place.
  2651. * FIXME: Avoiding a memcpy would be nice, but ref handling makes
  2652. * many assumptions about there being no actual duplicates.
  2653. * FIXME: This does not copy padding for out-of-frame motion
  2654. * vectors. Given we are concealing a lost frame, this probably
  2655. * is not noticeable by comparison, but it should be fixed. */
  2656. if (h->short_ref_count) {
  2657. if (prev) {
  2658. av_image_copy(h->short_ref[0]->f.data,
  2659. h->short_ref[0]->f.linesize,
  2660. (const uint8_t **)prev->f.data,
  2661. prev->f.linesize,
  2662. h->avctx->pix_fmt,
  2663. h->mb_width * 16,
  2664. h->mb_height * 16);
  2665. h->short_ref[0]->poc = prev->poc + 2;
  2666. }
  2667. h->short_ref[0]->frame_num = h->prev_frame_num;
  2668. }
  2669. }
  2670. /* See if we have a decoded first field looking for a pair...
  2671. * We're using that to see whether to continue decoding in that
  2672. * frame, or to allocate a new one. */
  2673. if (h0->first_field) {
  2674. assert(h0->cur_pic_ptr);
  2675. assert(h0->cur_pic_ptr->f.buf[0]);
  2676. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  2677. /* figure out if we have a complementary field pair */
  2678. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  2679. /* Previous field is unmatched. Don't display it, but let it
  2680. * remain for reference if marked as such. */
  2681. h0->cur_pic_ptr = NULL;
  2682. h0->first_field = FIELD_PICTURE(h);
  2683. } else {
  2684. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2685. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  2686. h0->picture_structure==PICT_BOTTOM_FIELD);
  2687. /* This and the previous field had different frame_nums.
  2688. * Consider this field first in pair. Throw away previous
  2689. * one except for reference purposes. */
  2690. h0->first_field = 1;
  2691. h0->cur_pic_ptr = NULL;
  2692. } else {
  2693. /* Second field in complementary pair */
  2694. h0->first_field = 0;
  2695. }
  2696. }
  2697. } else {
  2698. /* Frame or first field in a potentially complementary pair */
  2699. h0->first_field = FIELD_PICTURE(h);
  2700. }
  2701. if (!FIELD_PICTURE(h) || h0->first_field) {
  2702. if (h264_frame_start(h) < 0) {
  2703. h0->first_field = 0;
  2704. return AVERROR_INVALIDDATA;
  2705. }
  2706. } else {
  2707. release_unused_pictures(h, 0);
  2708. }
  2709. /* Some macroblocks can be accessed before they're available in case
  2710. * of lost slices, MBAFF or threading. */
  2711. if (FIELD_PICTURE(h)) {
  2712. for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
  2713. memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
  2714. } else {
  2715. memset(h->slice_table, -1,
  2716. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  2717. }
  2718. h0->last_slice_type = -1;
  2719. }
  2720. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  2721. return ret;
  2722. /* can't be in alloc_tables because linesize isn't known there.
  2723. * FIXME: redo bipred weight to not require extra buffer? */
  2724. for (i = 0; i < h->slice_context_count; i++)
  2725. if (h->thread_context[i]) {
  2726. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  2727. if (ret < 0)
  2728. return ret;
  2729. }
  2730. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  2731. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  2732. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
  2733. first_mb_in_slice >= h->mb_num) {
  2734. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2735. return AVERROR_INVALIDDATA;
  2736. }
  2737. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  2738. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
  2739. FIELD_OR_MBAFF_PICTURE(h);
  2740. if (h->picture_structure == PICT_BOTTOM_FIELD)
  2741. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  2742. av_assert1(h->mb_y < h->mb_height);
  2743. if (h->picture_structure == PICT_FRAME) {
  2744. h->curr_pic_num = h->frame_num;
  2745. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  2746. } else {
  2747. h->curr_pic_num = 2 * h->frame_num + 1;
  2748. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  2749. }
  2750. if (h->nal_unit_type == NAL_IDR_SLICE)
  2751. get_ue_golomb(&h->gb); /* idr_pic_id */
  2752. if (h->sps.poc_type == 0) {
  2753. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  2754. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  2755. h->delta_poc_bottom = get_se_golomb(&h->gb);
  2756. }
  2757. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  2758. h->delta_poc[0] = get_se_golomb(&h->gb);
  2759. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  2760. h->delta_poc[1] = get_se_golomb(&h->gb);
  2761. }
  2762. ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
  2763. if (h->pps.redundant_pic_cnt_present)
  2764. h->redundant_pic_count = get_ue_golomb(&h->gb);
  2765. ret = ff_set_ref_count(h);
  2766. if (ret < 0)
  2767. return ret;
  2768. if (slice_type != AV_PICTURE_TYPE_I &&
  2769. (h0->current_slice == 0 ||
  2770. slice_type != h0->last_slice_type ||
  2771. memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
  2772. ff_h264_fill_default_ref_list(h);
  2773. }
  2774. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2775. ret = ff_h264_decode_ref_pic_list_reordering(h);
  2776. if (ret < 0) {
  2777. h->ref_count[1] = h->ref_count[0] = 0;
  2778. return ret;
  2779. }
  2780. }
  2781. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  2782. (h->pps.weighted_bipred_idc == 1 &&
  2783. h->slice_type_nos == AV_PICTURE_TYPE_B))
  2784. ff_pred_weight_table(h);
  2785. else if (h->pps.weighted_bipred_idc == 2 &&
  2786. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2787. implicit_weight_table(h, -1);
  2788. } else {
  2789. h->use_weight = 0;
  2790. for (i = 0; i < 2; i++) {
  2791. h->luma_weight_flag[i] = 0;
  2792. h->chroma_weight_flag[i] = 0;
  2793. }
  2794. }
  2795. // If frame-mt is enabled, only update mmco tables for the first slice
  2796. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  2797. // or h->mmco, which will cause ref list mix-ups and decoding errors
  2798. // further down the line. This may break decoding if the first slice is
  2799. // corrupt, thus we only do this if frame-mt is enabled.
  2800. if (h->nal_ref_idc) {
  2801. ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
  2802. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  2803. h0->current_slice == 0);
  2804. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  2805. return AVERROR_INVALIDDATA;
  2806. }
  2807. if (FRAME_MBAFF(h)) {
  2808. ff_h264_fill_mbaff_ref_list(h);
  2809. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2810. implicit_weight_table(h, 0);
  2811. implicit_weight_table(h, 1);
  2812. }
  2813. }
  2814. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2815. ff_h264_direct_dist_scale_factor(h);
  2816. ff_h264_direct_ref_list_init(h);
  2817. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  2818. tmp = get_ue_golomb_31(&h->gb);
  2819. if (tmp > 2) {
  2820. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
  2821. return AVERROR_INVALIDDATA;
  2822. }
  2823. h->cabac_init_idc = tmp;
  2824. }
  2825. h->last_qscale_diff = 0;
  2826. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  2827. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  2828. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2829. return AVERROR_INVALIDDATA;
  2830. }
  2831. h->qscale = tmp;
  2832. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  2833. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  2834. // FIXME qscale / qp ... stuff
  2835. if (h->slice_type == AV_PICTURE_TYPE_SP)
  2836. get_bits1(&h->gb); /* sp_for_switch_flag */
  2837. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  2838. h->slice_type == AV_PICTURE_TYPE_SI)
  2839. get_se_golomb(&h->gb); /* slice_qs_delta */
  2840. h->deblocking_filter = 1;
  2841. h->slice_alpha_c0_offset = 0;
  2842. h->slice_beta_offset = 0;
  2843. if (h->pps.deblocking_filter_parameters_present) {
  2844. tmp = get_ue_golomb_31(&h->gb);
  2845. if (tmp > 2) {
  2846. av_log(h->avctx, AV_LOG_ERROR,
  2847. "deblocking_filter_idc %u out of range\n", tmp);
  2848. return AVERROR_INVALIDDATA;
  2849. }
  2850. h->deblocking_filter = tmp;
  2851. if (h->deblocking_filter < 2)
  2852. h->deblocking_filter ^= 1; // 1<->0
  2853. if (h->deblocking_filter) {
  2854. h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
  2855. h->slice_beta_offset = get_se_golomb(&h->gb) * 2;
  2856. if (h->slice_alpha_c0_offset > 12 ||
  2857. h->slice_alpha_c0_offset < -12 ||
  2858. h->slice_beta_offset > 12 ||
  2859. h->slice_beta_offset < -12) {
  2860. av_log(h->avctx, AV_LOG_ERROR,
  2861. "deblocking filter parameters %d %d out of range\n",
  2862. h->slice_alpha_c0_offset, h->slice_beta_offset);
  2863. return AVERROR_INVALIDDATA;
  2864. }
  2865. }
  2866. }
  2867. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  2868. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  2869. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  2870. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  2871. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  2872. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  2873. h->nal_ref_idc == 0))
  2874. h->deblocking_filter = 0;
  2875. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2876. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  2877. /* Cheat slightly for speed:
  2878. * Do not bother to deblock across slices. */
  2879. h->deblocking_filter = 2;
  2880. } else {
  2881. h0->max_contexts = 1;
  2882. if (!h0->single_decode_warning) {
  2883. av_log(h->avctx, AV_LOG_INFO,
  2884. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2885. h0->single_decode_warning = 1;
  2886. }
  2887. if (h != h0) {
  2888. av_log(h->avctx, AV_LOG_ERROR,
  2889. "Deblocking switched inside frame.\n");
  2890. return 1;
  2891. }
  2892. }
  2893. }
  2894. h->qp_thresh = 15 -
  2895. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  2896. FFMAX3(0,
  2897. h->pps.chroma_qp_index_offset[0],
  2898. h->pps.chroma_qp_index_offset[1]) +
  2899. 6 * (h->sps.bit_depth_luma - 8);
  2900. h0->last_slice_type = slice_type;
  2901. memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
  2902. h->slice_num = ++h0->current_slice;
  2903. if (h->slice_num)
  2904. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
  2905. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
  2906. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
  2907. && h->slice_num >= MAX_SLICES) {
  2908. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  2909. av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
  2910. }
  2911. for (j = 0; j < 2; j++) {
  2912. int id_list[16];
  2913. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  2914. for (i = 0; i < 16; i++) {
  2915. id_list[i] = 60;
  2916. if (j < h->list_count && i < h->ref_count[j] &&
  2917. h->ref_list[j][i].f.buf[0]) {
  2918. int k;
  2919. AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
  2920. for (k = 0; k < h->short_ref_count; k++)
  2921. if (h->short_ref[k]->f.buf[0]->buffer == buf) {
  2922. id_list[i] = k;
  2923. break;
  2924. }
  2925. for (k = 0; k < h->long_ref_count; k++)
  2926. if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
  2927. id_list[i] = h->short_ref_count + k;
  2928. break;
  2929. }
  2930. }
  2931. }
  2932. ref2frm[0] =
  2933. ref2frm[1] = -1;
  2934. for (i = 0; i < 16; i++)
  2935. ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
  2936. ref2frm[18 + 0] =
  2937. ref2frm[18 + 1] = -1;
  2938. for (i = 16; i < 48; i++)
  2939. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  2940. (h->ref_list[j][i].reference & 3);
  2941. }
  2942. if (h->ref_count[0]) h264_set_erpic(&h->er.last_pic, &h->ref_list[0][0]);
  2943. if (h->ref_count[1]) h264_set_erpic(&h->er.next_pic, &h->ref_list[1][0]);
  2944. h->er.ref_count = h->ref_count[0];
  2945. h0->au_pps_id = pps_id;
  2946. h->sps.new =
  2947. h0->sps_buffers[h->pps.sps_id]->new = 0;
  2948. h->current_sps_id = h->pps.sps_id;
  2949. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  2950. av_log(h->avctx, AV_LOG_DEBUG,
  2951. "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  2952. h->slice_num,
  2953. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  2954. first_mb_in_slice,
  2955. av_get_picture_type_char(h->slice_type),
  2956. h->slice_type_fixed ? " fix" : "",
  2957. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2958. pps_id, h->frame_num,
  2959. h->cur_pic_ptr->field_poc[0],
  2960. h->cur_pic_ptr->field_poc[1],
  2961. h->ref_count[0], h->ref_count[1],
  2962. h->qscale,
  2963. h->deblocking_filter,
  2964. h->slice_alpha_c0_offset, h->slice_beta_offset,
  2965. h->use_weight,
  2966. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  2967. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  2968. }
  2969. return 0;
  2970. }
  2971. int ff_h264_get_slice_type(const H264Context *h)
  2972. {
  2973. switch (h->slice_type) {
  2974. case AV_PICTURE_TYPE_P:
  2975. return 0;
  2976. case AV_PICTURE_TYPE_B:
  2977. return 1;
  2978. case AV_PICTURE_TYPE_I:
  2979. return 2;
  2980. case AV_PICTURE_TYPE_SP:
  2981. return 3;
  2982. case AV_PICTURE_TYPE_SI:
  2983. return 4;
  2984. default:
  2985. return AVERROR_INVALIDDATA;
  2986. }
  2987. }
  2988. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  2989. int mb_type, int top_xy,
  2990. int left_xy[LEFT_MBS],
  2991. int top_type,
  2992. int left_type[LEFT_MBS],
  2993. int mb_xy, int list)
  2994. {
  2995. int b_stride = h->b_stride;
  2996. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  2997. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  2998. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  2999. if (USES_LIST(top_type, list)) {
  3000. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3001. const int b8_xy = 4 * top_xy + 2;
  3002. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3003. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
  3004. ref_cache[0 - 1 * 8] =
  3005. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
  3006. ref_cache[2 - 1 * 8] =
  3007. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
  3008. } else {
  3009. AV_ZERO128(mv_dst - 1 * 8);
  3010. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3011. }
  3012. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3013. if (USES_LIST(left_type[LTOP], list)) {
  3014. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3015. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3016. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3017. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
  3018. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
  3019. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
  3020. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
  3021. ref_cache[-1 + 0] =
  3022. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
  3023. ref_cache[-1 + 16] =
  3024. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
  3025. } else {
  3026. AV_ZERO32(mv_dst - 1 + 0);
  3027. AV_ZERO32(mv_dst - 1 + 8);
  3028. AV_ZERO32(mv_dst - 1 + 16);
  3029. AV_ZERO32(mv_dst - 1 + 24);
  3030. ref_cache[-1 + 0] =
  3031. ref_cache[-1 + 8] =
  3032. ref_cache[-1 + 16] =
  3033. ref_cache[-1 + 24] = LIST_NOT_USED;
  3034. }
  3035. }
  3036. }
  3037. if (!USES_LIST(mb_type, list)) {
  3038. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3039. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3040. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3041. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3042. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3043. return;
  3044. }
  3045. {
  3046. int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
  3047. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3048. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3049. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3050. AV_WN32A(&ref_cache[0 * 8], ref01);
  3051. AV_WN32A(&ref_cache[1 * 8], ref01);
  3052. AV_WN32A(&ref_cache[2 * 8], ref23);
  3053. AV_WN32A(&ref_cache[3 * 8], ref23);
  3054. }
  3055. {
  3056. int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3057. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3058. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3059. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3060. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3061. }
  3062. }
  3063. /**
  3064. *
  3065. * @return non zero if the loop filter can be skipped
  3066. */
  3067. static int fill_filter_caches(H264Context *h, int mb_type)
  3068. {
  3069. const int mb_xy = h->mb_xy;
  3070. int top_xy, left_xy[LEFT_MBS];
  3071. int top_type, left_type[LEFT_MBS];
  3072. uint8_t *nnz;
  3073. uint8_t *nnz_cache;
  3074. top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
  3075. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3076. * stuff, I can't imagine that these complex rules are worth it. */
  3077. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3078. if (FRAME_MBAFF(h)) {
  3079. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
  3080. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3081. if (h->mb_y & 1) {
  3082. if (left_mb_field_flag != curr_mb_field_flag)
  3083. left_xy[LTOP] -= h->mb_stride;
  3084. } else {
  3085. if (curr_mb_field_flag)
  3086. top_xy += h->mb_stride &
  3087. (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
  3088. if (left_mb_field_flag != curr_mb_field_flag)
  3089. left_xy[LBOT] += h->mb_stride;
  3090. }
  3091. }
  3092. h->top_mb_xy = top_xy;
  3093. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3094. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3095. {
  3096. /* For sufficiently low qp, filtering wouldn't do anything.
  3097. * This is a conservative estimate: could also check beta_offset
  3098. * and more accurate chroma_qp. */
  3099. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3100. int qp = h->cur_pic.qscale_table[mb_xy];
  3101. if (qp <= qp_thresh &&
  3102. (left_xy[LTOP] < 0 ||
  3103. ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3104. (top_xy < 0 ||
  3105. ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3106. if (!FRAME_MBAFF(h))
  3107. return 1;
  3108. if ((left_xy[LTOP] < 0 ||
  3109. ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3110. (top_xy < h->mb_stride ||
  3111. ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3112. return 1;
  3113. }
  3114. }
  3115. top_type = h->cur_pic.mb_type[top_xy];
  3116. left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
  3117. left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
  3118. if (h->deblocking_filter == 2) {
  3119. if (h->slice_table[top_xy] != h->slice_num)
  3120. top_type = 0;
  3121. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3122. left_type[LTOP] = left_type[LBOT] = 0;
  3123. } else {
  3124. if (h->slice_table[top_xy] == 0xFFFF)
  3125. top_type = 0;
  3126. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3127. left_type[LTOP] = left_type[LBOT] = 0;
  3128. }
  3129. h->top_type = top_type;
  3130. h->left_type[LTOP] = left_type[LTOP];
  3131. h->left_type[LBOT] = left_type[LBOT];
  3132. if (IS_INTRA(mb_type))
  3133. return 0;
  3134. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3135. top_type, left_type, mb_xy, 0);
  3136. if (h->list_count == 2)
  3137. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3138. top_type, left_type, mb_xy, 1);
  3139. nnz = h->non_zero_count[mb_xy];
  3140. nnz_cache = h->non_zero_count_cache;
  3141. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3142. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3143. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3144. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3145. h->cbp = h->cbp_table[mb_xy];
  3146. if (top_type) {
  3147. nnz = h->non_zero_count[top_xy];
  3148. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3149. }
  3150. if (left_type[LTOP]) {
  3151. nnz = h->non_zero_count[left_xy[LTOP]];
  3152. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3153. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3154. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3155. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3156. }
  3157. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3158. * from what the loop filter needs */
  3159. if (!CABAC(h) && h->pps.transform_8x8_mode) {
  3160. if (IS_8x8DCT(top_type)) {
  3161. nnz_cache[4 + 8 * 0] =
  3162. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3163. nnz_cache[6 + 8 * 0] =
  3164. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3165. }
  3166. if (IS_8x8DCT(left_type[LTOP])) {
  3167. nnz_cache[3 + 8 * 1] =
  3168. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3169. }
  3170. if (IS_8x8DCT(left_type[LBOT])) {
  3171. nnz_cache[3 + 8 * 3] =
  3172. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3173. }
  3174. if (IS_8x8DCT(mb_type)) {
  3175. nnz_cache[scan8[0]] =
  3176. nnz_cache[scan8[1]] =
  3177. nnz_cache[scan8[2]] =
  3178. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3179. nnz_cache[scan8[0 + 4]] =
  3180. nnz_cache[scan8[1 + 4]] =
  3181. nnz_cache[scan8[2 + 4]] =
  3182. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3183. nnz_cache[scan8[0 + 8]] =
  3184. nnz_cache[scan8[1 + 8]] =
  3185. nnz_cache[scan8[2 + 8]] =
  3186. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3187. nnz_cache[scan8[0 + 12]] =
  3188. nnz_cache[scan8[1 + 12]] =
  3189. nnz_cache[scan8[2 + 12]] =
  3190. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3191. }
  3192. }
  3193. return 0;
  3194. }
  3195. static void loop_filter(H264Context *h, int start_x, int end_x)
  3196. {
  3197. uint8_t *dest_y, *dest_cb, *dest_cr;
  3198. int linesize, uvlinesize, mb_x, mb_y;
  3199. const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
  3200. const int old_slice_type = h->slice_type;
  3201. const int pixel_shift = h->pixel_shift;
  3202. const int block_h = 16 >> h->chroma_y_shift;
  3203. if (h->deblocking_filter) {
  3204. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3205. for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
  3206. int mb_xy, mb_type;
  3207. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3208. h->slice_num = h->slice_table[mb_xy];
  3209. mb_type = h->cur_pic.mb_type[mb_xy];
  3210. h->list_count = h->list_counts[mb_xy];
  3211. if (FRAME_MBAFF(h))
  3212. h->mb_mbaff =
  3213. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3214. h->mb_x = mb_x;
  3215. h->mb_y = mb_y;
  3216. dest_y = h->cur_pic.f.data[0] +
  3217. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3218. dest_cb = h->cur_pic.f.data[1] +
  3219. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  3220. mb_y * h->uvlinesize * block_h;
  3221. dest_cr = h->cur_pic.f.data[2] +
  3222. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  3223. mb_y * h->uvlinesize * block_h;
  3224. // FIXME simplify above
  3225. if (MB_FIELD(h)) {
  3226. linesize = h->mb_linesize = h->linesize * 2;
  3227. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3228. if (mb_y & 1) { // FIXME move out of this function?
  3229. dest_y -= h->linesize * 15;
  3230. dest_cb -= h->uvlinesize * (block_h - 1);
  3231. dest_cr -= h->uvlinesize * (block_h - 1);
  3232. }
  3233. } else {
  3234. linesize = h->mb_linesize = h->linesize;
  3235. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3236. }
  3237. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3238. uvlinesize, 0);
  3239. if (fill_filter_caches(h, mb_type))
  3240. continue;
  3241. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
  3242. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
  3243. if (FRAME_MBAFF(h)) {
  3244. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3245. linesize, uvlinesize);
  3246. } else {
  3247. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3248. dest_cr, linesize, uvlinesize);
  3249. }
  3250. }
  3251. }
  3252. h->slice_type = old_slice_type;
  3253. h->mb_x = end_x;
  3254. h->mb_y = end_mb_y - FRAME_MBAFF(h);
  3255. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3256. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3257. }
  3258. static void predict_field_decoding_flag(H264Context *h)
  3259. {
  3260. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3261. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3262. h->cur_pic.mb_type[mb_xy - 1] :
  3263. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3264. h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
  3265. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3266. }
  3267. /**
  3268. * Draw edges and report progress for the last MB row.
  3269. */
  3270. static void decode_finish_row(H264Context *h)
  3271. {
  3272. int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
  3273. int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
  3274. int height = 16 << FRAME_MBAFF(h);
  3275. int deblock_border = (16 + 4) << FRAME_MBAFF(h);
  3276. if (h->deblocking_filter) {
  3277. if ((top + height) >= pic_height)
  3278. height += deblock_border;
  3279. top -= deblock_border;
  3280. }
  3281. if (top >= pic_height || (top + height) < 0)
  3282. return;
  3283. height = FFMIN(height, pic_height - top);
  3284. if (top < 0) {
  3285. height = top + height;
  3286. top = 0;
  3287. }
  3288. ff_h264_draw_horiz_band(h, top, height);
  3289. if (h->droppable || h->er.error_occurred)
  3290. return;
  3291. ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
  3292. h->picture_structure == PICT_BOTTOM_FIELD);
  3293. }
  3294. static void er_add_slice(H264Context *h, int startx, int starty,
  3295. int endx, int endy, int status)
  3296. {
  3297. if (CONFIG_ERROR_RESILIENCE) {
  3298. ERContext *er = &h->er;
  3299. ff_er_add_slice(er, startx, starty, endx, endy, status);
  3300. }
  3301. }
  3302. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3303. {
  3304. H264Context *h = *(void **)arg;
  3305. int lf_x_start = h->mb_x;
  3306. h->mb_skip_run = -1;
  3307. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
  3308. h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
  3309. avctx->codec_id != AV_CODEC_ID_H264 ||
  3310. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  3311. if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
  3312. const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
  3313. if (start_i) {
  3314. int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
  3315. prev_status &= ~ VP_START;
  3316. if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
  3317. h->er.error_occurred = 1;
  3318. }
  3319. }
  3320. if (h->pps.cabac) {
  3321. /* realign */
  3322. align_get_bits(&h->gb);
  3323. /* init cabac */
  3324. ff_init_cabac_decoder(&h->cabac,
  3325. h->gb.buffer + get_bits_count(&h->gb) / 8,
  3326. (get_bits_left(&h->gb) + 7) / 8);
  3327. ff_h264_init_cabac_states(h);
  3328. for (;;) {
  3329. // START_TIMER
  3330. int ret = ff_h264_decode_mb_cabac(h);
  3331. int eos;
  3332. // STOP_TIMER("decode_mb_cabac")
  3333. if (ret >= 0)
  3334. ff_h264_hl_decode_mb(h);
  3335. // FIXME optimal? or let mb_decode decode 16x32 ?
  3336. if (ret >= 0 && FRAME_MBAFF(h)) {
  3337. h->mb_y++;
  3338. ret = ff_h264_decode_mb_cabac(h);
  3339. if (ret >= 0)
  3340. ff_h264_hl_decode_mb(h);
  3341. h->mb_y--;
  3342. }
  3343. eos = get_cabac_terminate(&h->cabac);
  3344. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  3345. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3346. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3347. h->mb_y, ER_MB_END);
  3348. if (h->mb_x >= lf_x_start)
  3349. loop_filter(h, lf_x_start, h->mb_x + 1);
  3350. return 0;
  3351. }
  3352. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3353. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3354. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3355. av_log(h->avctx, AV_LOG_ERROR,
  3356. "error while decoding MB %d %d, bytestream %td\n",
  3357. h->mb_x, h->mb_y,
  3358. h->cabac.bytestream_end - h->cabac.bytestream);
  3359. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3360. h->mb_y, ER_MB_ERROR);
  3361. return AVERROR_INVALIDDATA;
  3362. }
  3363. if (++h->mb_x >= h->mb_width) {
  3364. loop_filter(h, lf_x_start, h->mb_x);
  3365. h->mb_x = lf_x_start = 0;
  3366. decode_finish_row(h);
  3367. ++h->mb_y;
  3368. if (FIELD_OR_MBAFF_PICTURE(h)) {
  3369. ++h->mb_y;
  3370. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  3371. predict_field_decoding_flag(h);
  3372. }
  3373. }
  3374. if (eos || h->mb_y >= h->mb_height) {
  3375. tprintf(h->avctx, "slice end %d %d\n",
  3376. get_bits_count(&h->gb), h->gb.size_in_bits);
  3377. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3378. h->mb_y, ER_MB_END);
  3379. if (h->mb_x > lf_x_start)
  3380. loop_filter(h, lf_x_start, h->mb_x);
  3381. return 0;
  3382. }
  3383. }
  3384. } else {
  3385. for (;;) {
  3386. int ret = ff_h264_decode_mb_cavlc(h);
  3387. if (ret >= 0)
  3388. ff_h264_hl_decode_mb(h);
  3389. // FIXME optimal? or let mb_decode decode 16x32 ?
  3390. if (ret >= 0 && FRAME_MBAFF(h)) {
  3391. h->mb_y++;
  3392. ret = ff_h264_decode_mb_cavlc(h);
  3393. if (ret >= 0)
  3394. ff_h264_hl_decode_mb(h);
  3395. h->mb_y--;
  3396. }
  3397. if (ret < 0) {
  3398. av_log(h->avctx, AV_LOG_ERROR,
  3399. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  3400. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3401. h->mb_y, ER_MB_ERROR);
  3402. return ret;
  3403. }
  3404. if (++h->mb_x >= h->mb_width) {
  3405. loop_filter(h, lf_x_start, h->mb_x);
  3406. h->mb_x = lf_x_start = 0;
  3407. decode_finish_row(h);
  3408. ++h->mb_y;
  3409. if (FIELD_OR_MBAFF_PICTURE(h)) {
  3410. ++h->mb_y;
  3411. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  3412. predict_field_decoding_flag(h);
  3413. }
  3414. if (h->mb_y >= h->mb_height) {
  3415. tprintf(h->avctx, "slice end %d %d\n",
  3416. get_bits_count(&h->gb), h->gb.size_in_bits);
  3417. if ( get_bits_left(&h->gb) == 0
  3418. || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3419. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3420. h->mb_x - 1, h->mb_y,
  3421. ER_MB_END);
  3422. return 0;
  3423. } else {
  3424. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3425. h->mb_x, h->mb_y,
  3426. ER_MB_END);
  3427. return AVERROR_INVALIDDATA;
  3428. }
  3429. }
  3430. }
  3431. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  3432. tprintf(h->avctx, "slice end %d %d\n",
  3433. get_bits_count(&h->gb), h->gb.size_in_bits);
  3434. if (get_bits_left(&h->gb) == 0) {
  3435. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3436. h->mb_x - 1, h->mb_y,
  3437. ER_MB_END);
  3438. if (h->mb_x > lf_x_start)
  3439. loop_filter(h, lf_x_start, h->mb_x);
  3440. return 0;
  3441. } else {
  3442. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3443. h->mb_y, ER_MB_ERROR);
  3444. return AVERROR_INVALIDDATA;
  3445. }
  3446. }
  3447. }
  3448. }
  3449. }
  3450. /**
  3451. * Call decode_slice() for each context.
  3452. *
  3453. * @param h h264 master context
  3454. * @param context_count number of contexts to execute
  3455. */
  3456. static int execute_decode_slices(H264Context *h, unsigned context_count)
  3457. {
  3458. AVCodecContext *const avctx = h->avctx;
  3459. H264Context *hx;
  3460. int i;
  3461. av_assert0(h->mb_y < h->mb_height);
  3462. if (h->avctx->hwaccel ||
  3463. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3464. return 0;
  3465. if (context_count == 1) {
  3466. return decode_slice(avctx, &h);
  3467. } else {
  3468. av_assert0(context_count > 0);
  3469. for (i = 1; i < context_count; i++) {
  3470. hx = h->thread_context[i];
  3471. if (CONFIG_ERROR_RESILIENCE) {
  3472. hx->er.error_count = 0;
  3473. }
  3474. hx->x264_build = h->x264_build;
  3475. }
  3476. avctx->execute(avctx, decode_slice, h->thread_context,
  3477. NULL, context_count, sizeof(void *));
  3478. /* pull back stuff from slices to master context */
  3479. hx = h->thread_context[context_count - 1];
  3480. h->mb_x = hx->mb_x;
  3481. h->mb_y = hx->mb_y;
  3482. h->droppable = hx->droppable;
  3483. h->picture_structure = hx->picture_structure;
  3484. if (CONFIG_ERROR_RESILIENCE) {
  3485. for (i = 1; i < context_count; i++)
  3486. h->er.error_count += h->thread_context[i]->er.error_count;
  3487. }
  3488. }
  3489. return 0;
  3490. }
  3491. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  3492. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3493. int parse_extradata)
  3494. {
  3495. AVCodecContext *const avctx = h->avctx;
  3496. H264Context *hx; ///< thread context
  3497. int buf_index;
  3498. unsigned context_count;
  3499. int next_avc;
  3500. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3501. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3502. int nal_index;
  3503. int idr_cleared=0;
  3504. int first_slice = 0;
  3505. int ret = 0;
  3506. h->nal_unit_type= 0;
  3507. if(!h->slice_context_count)
  3508. h->slice_context_count= 1;
  3509. h->max_contexts = h->slice_context_count;
  3510. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  3511. h->current_slice = 0;
  3512. if (!h->first_field)
  3513. h->cur_pic_ptr = NULL;
  3514. ff_h264_reset_sei(h);
  3515. }
  3516. if (h->nal_length_size == 4) {
  3517. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3518. h->is_avc = 0;
  3519. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3520. h->is_avc = 1;
  3521. }
  3522. for (; pass <= 1; pass++) {
  3523. buf_index = 0;
  3524. context_count = 0;
  3525. next_avc = h->is_avc ? 0 : buf_size;
  3526. nal_index = 0;
  3527. for (;;) {
  3528. int consumed;
  3529. int dst_length;
  3530. int bit_length;
  3531. const uint8_t *ptr;
  3532. int i, nalsize = 0;
  3533. int err;
  3534. if (buf_index >= next_avc) {
  3535. if (buf_index >= buf_size - h->nal_length_size)
  3536. break;
  3537. nalsize = 0;
  3538. for (i = 0; i < h->nal_length_size; i++)
  3539. nalsize = (nalsize << 8) | buf[buf_index++];
  3540. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3541. av_log(h->avctx, AV_LOG_ERROR,
  3542. "AVC: nal size %d\n", nalsize);
  3543. break;
  3544. }
  3545. next_avc = buf_index + nalsize;
  3546. } else {
  3547. // start code prefix search
  3548. for (; buf_index + 3 < next_avc; buf_index++)
  3549. // This should always succeed in the first iteration.
  3550. if (buf[buf_index] == 0 &&
  3551. buf[buf_index + 1] == 0 &&
  3552. buf[buf_index + 2] == 1)
  3553. break;
  3554. if (buf_index + 3 >= buf_size) {
  3555. buf_index = buf_size;
  3556. break;
  3557. }
  3558. buf_index += 3;
  3559. if (buf_index >= next_avc)
  3560. continue;
  3561. }
  3562. hx = h->thread_context[context_count];
  3563. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3564. &consumed, next_avc - buf_index);
  3565. if (ptr == NULL || dst_length < 0) {
  3566. ret = -1;
  3567. goto end;
  3568. }
  3569. i = buf_index + consumed;
  3570. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3571. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3572. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3573. h->workaround_bugs |= FF_BUG_TRUNCATED;
  3574. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  3575. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  3576. dst_length--;
  3577. bit_length = !dst_length ? 0
  3578. : (8 * dst_length -
  3579. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3580. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  3581. av_log(h->avctx, AV_LOG_DEBUG,
  3582. "NAL %d/%d at %d/%d length %d pass %d\n",
  3583. hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
  3584. if (h->is_avc && (nalsize != consumed) && nalsize)
  3585. av_log(h->avctx, AV_LOG_DEBUG,
  3586. "AVC: Consumed only %d bytes instead of %d\n",
  3587. consumed, nalsize);
  3588. buf_index += consumed;
  3589. nal_index++;
  3590. if (pass == 0) {
  3591. /* packets can sometimes contain multiple PPS/SPS,
  3592. * e.g. two PAFF field pictures in one packet, or a demuxer
  3593. * which splits NALs strangely if so, when frame threading we
  3594. * can't start the next thread until we've read all of them */
  3595. switch (hx->nal_unit_type) {
  3596. case NAL_SPS:
  3597. case NAL_PPS:
  3598. nals_needed = nal_index;
  3599. break;
  3600. case NAL_DPA:
  3601. case NAL_IDR_SLICE:
  3602. case NAL_SLICE:
  3603. init_get_bits(&hx->gb, ptr, bit_length);
  3604. if (!get_ue_golomb(&hx->gb) ||
  3605. !first_slice ||
  3606. first_slice != hx->nal_unit_type)
  3607. nals_needed = nal_index;
  3608. if (!first_slice)
  3609. first_slice = hx->nal_unit_type;
  3610. }
  3611. continue;
  3612. }
  3613. if (!first_slice)
  3614. switch (hx->nal_unit_type) {
  3615. case NAL_DPA:
  3616. case NAL_IDR_SLICE:
  3617. case NAL_SLICE:
  3618. first_slice = hx->nal_unit_type;
  3619. }
  3620. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  3621. h->nal_ref_idc == 0 &&
  3622. h->nal_unit_type != NAL_SEI)
  3623. continue;
  3624. again:
  3625. if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
  3626. || nals_needed >= nal_index)
  3627. h->au_pps_id = -1;
  3628. /* Ignore per frame NAL unit type during extradata
  3629. * parsing. Decoding slices is not possible in codec init
  3630. * with frame-mt */
  3631. if (parse_extradata) {
  3632. switch (hx->nal_unit_type) {
  3633. case NAL_IDR_SLICE:
  3634. case NAL_SLICE:
  3635. case NAL_DPA:
  3636. case NAL_DPB:
  3637. case NAL_DPC:
  3638. av_log(h->avctx, AV_LOG_WARNING,
  3639. "Ignoring NAL %d in global header/extradata\n",
  3640. hx->nal_unit_type);
  3641. // fall through to next case
  3642. case NAL_AUXILIARY_SLICE:
  3643. hx->nal_unit_type = NAL_FF_IGNORE;
  3644. }
  3645. }
  3646. err = 0;
  3647. switch (hx->nal_unit_type) {
  3648. case NAL_IDR_SLICE:
  3649. if (h->nal_unit_type != NAL_IDR_SLICE) {
  3650. av_log(h->avctx, AV_LOG_ERROR,
  3651. "Invalid mix of idr and non-idr slices\n");
  3652. ret = -1;
  3653. goto end;
  3654. }
  3655. if(!idr_cleared)
  3656. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3657. idr_cleared = 1;
  3658. case NAL_SLICE:
  3659. init_get_bits(&hx->gb, ptr, bit_length);
  3660. hx->intra_gb_ptr =
  3661. hx->inter_gb_ptr = &hx->gb;
  3662. hx->data_partitioning = 0;
  3663. if ((err = decode_slice_header(hx, h)))
  3664. break;
  3665. if (h->sei_recovery_frame_cnt >= 0) {
  3666. if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
  3667. h->valid_recovery_point = 1;
  3668. if ( h->recovery_frame < 0
  3669. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
  3670. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  3671. ((1 << h->sps.log2_max_frame_num) - 1);
  3672. if (!h->valid_recovery_point)
  3673. h->recovery_frame = h->frame_num;
  3674. }
  3675. }
  3676. h->cur_pic_ptr->f.key_frame |=
  3677. (hx->nal_unit_type == NAL_IDR_SLICE);
  3678. if (hx->nal_unit_type == NAL_IDR_SLICE ||
  3679. h->recovery_frame == h->frame_num) {
  3680. h->recovery_frame = -1;
  3681. h->cur_pic_ptr->recovered = 1;
  3682. }
  3683. // If we have an IDR, all frames after it in decoded order are
  3684. // "recovered".
  3685. if (hx->nal_unit_type == NAL_IDR_SLICE)
  3686. h->frame_recovered |= FRAME_RECOVERED_IDR;
  3687. h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  3688. h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
  3689. #if 1
  3690. h->cur_pic_ptr->recovered |= h->frame_recovered;
  3691. #else
  3692. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  3693. #endif
  3694. if (h->current_slice == 1) {
  3695. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  3696. decode_postinit(h, nal_index >= nals_needed);
  3697. if (h->avctx->hwaccel &&
  3698. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  3699. return ret;
  3700. if (CONFIG_H264_VDPAU_DECODER &&
  3701. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3702. ff_vdpau_h264_picture_start(h);
  3703. }
  3704. if (hx->redundant_pic_count == 0 &&
  3705. (avctx->skip_frame < AVDISCARD_NONREF ||
  3706. hx->nal_ref_idc) &&
  3707. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3708. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3709. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3710. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3711. avctx->skip_frame < AVDISCARD_ALL) {
  3712. if (avctx->hwaccel) {
  3713. ret = avctx->hwaccel->decode_slice(avctx,
  3714. &buf[buf_index - consumed],
  3715. consumed);
  3716. if (ret < 0)
  3717. return ret;
  3718. } else if (CONFIG_H264_VDPAU_DECODER &&
  3719. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  3720. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  3721. start_code,
  3722. sizeof(start_code));
  3723. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  3724. &buf[buf_index - consumed],
  3725. consumed);
  3726. } else
  3727. context_count++;
  3728. }
  3729. break;
  3730. case NAL_DPA:
  3731. if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
  3732. av_log(h->avctx, AV_LOG_ERROR,
  3733. "Decoding in chunks is not supported for "
  3734. "partitioned slices.\n");
  3735. return AVERROR(ENOSYS);
  3736. }
  3737. init_get_bits(&hx->gb, ptr, bit_length);
  3738. hx->intra_gb_ptr =
  3739. hx->inter_gb_ptr = NULL;
  3740. if ((err = decode_slice_header(hx, h)) < 0) {
  3741. /* make sure data_partitioning is cleared if it was set
  3742. * before, so we don't try decoding a slice without a valid
  3743. * slice header later */
  3744. h->data_partitioning = 0;
  3745. break;
  3746. }
  3747. hx->data_partitioning = 1;
  3748. break;
  3749. case NAL_DPB:
  3750. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3751. hx->intra_gb_ptr = &hx->intra_gb;
  3752. break;
  3753. case NAL_DPC:
  3754. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3755. hx->inter_gb_ptr = &hx->inter_gb;
  3756. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  3757. break;
  3758. if (hx->redundant_pic_count == 0 &&
  3759. hx->intra_gb_ptr &&
  3760. hx->data_partitioning &&
  3761. h->cur_pic_ptr && h->context_initialized &&
  3762. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  3763. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3764. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3765. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3766. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3767. avctx->skip_frame < AVDISCARD_ALL)
  3768. context_count++;
  3769. break;
  3770. case NAL_SEI:
  3771. init_get_bits(&h->gb, ptr, bit_length);
  3772. ff_h264_decode_sei(h);
  3773. break;
  3774. case NAL_SPS:
  3775. init_get_bits(&h->gb, ptr, bit_length);
  3776. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
  3777. av_log(h->avctx, AV_LOG_DEBUG,
  3778. "SPS decoding failure, trying again with the complete NAL\n");
  3779. if (h->is_avc)
  3780. av_assert0(next_avc - buf_index + consumed == nalsize);
  3781. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  3782. break;
  3783. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  3784. 8*(next_avc - buf_index + consumed - 1));
  3785. ff_h264_decode_seq_parameter_set(h);
  3786. }
  3787. break;
  3788. case NAL_PPS:
  3789. init_get_bits(&h->gb, ptr, bit_length);
  3790. ff_h264_decode_picture_parameter_set(h, bit_length);
  3791. break;
  3792. case NAL_AUD:
  3793. case NAL_END_SEQUENCE:
  3794. case NAL_END_STREAM:
  3795. case NAL_FILLER_DATA:
  3796. case NAL_SPS_EXT:
  3797. case NAL_AUXILIARY_SLICE:
  3798. break;
  3799. case NAL_FF_IGNORE:
  3800. break;
  3801. default:
  3802. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  3803. hx->nal_unit_type, bit_length);
  3804. }
  3805. if (context_count == h->max_contexts) {
  3806. execute_decode_slices(h, context_count);
  3807. context_count = 0;
  3808. }
  3809. if (err < 0) {
  3810. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3811. h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
  3812. } else if (err == 1) {
  3813. /* Slice could not be decoded in parallel mode, copy down
  3814. * NAL unit stuff to context 0 and restart. Note that
  3815. * rbsp_buffer is not transferred, but since we no longer
  3816. * run in parallel mode this should not be an issue. */
  3817. h->nal_unit_type = hx->nal_unit_type;
  3818. h->nal_ref_idc = hx->nal_ref_idc;
  3819. hx = h;
  3820. goto again;
  3821. }
  3822. }
  3823. }
  3824. if (context_count)
  3825. execute_decode_slices(h, context_count);
  3826. end:
  3827. /* clean up */
  3828. if (h->cur_pic_ptr && !h->droppable) {
  3829. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  3830. h->picture_structure == PICT_BOTTOM_FIELD);
  3831. }
  3832. return (ret < 0) ? ret : buf_index;
  3833. }
  3834. /**
  3835. * Return the number of bytes consumed for building the current frame.
  3836. */
  3837. static int get_consumed_bytes(int pos, int buf_size)
  3838. {
  3839. if (pos == 0)
  3840. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  3841. if (pos + 10 > buf_size)
  3842. pos = buf_size; // oops ;)
  3843. return pos;
  3844. }
  3845. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  3846. {
  3847. AVFrame *src = &srcp->f;
  3848. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  3849. int i;
  3850. int ret = av_frame_ref(dst, src);
  3851. if (ret < 0)
  3852. return ret;
  3853. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  3854. if (!srcp->crop)
  3855. return 0;
  3856. for (i = 0; i < desc->nb_components; i++) {
  3857. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  3858. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  3859. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  3860. (srcp->crop_top >> vshift) * dst->linesize[i];
  3861. dst->data[i] += off;
  3862. }
  3863. return 0;
  3864. }
  3865. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  3866. int *got_frame, AVPacket *avpkt)
  3867. {
  3868. const uint8_t *buf = avpkt->data;
  3869. int buf_size = avpkt->size;
  3870. H264Context *h = avctx->priv_data;
  3871. AVFrame *pict = data;
  3872. int buf_index = 0;
  3873. H264Picture *out;
  3874. int i, out_idx;
  3875. int ret;
  3876. h->flags = avctx->flags;
  3877. /* reset data partitioning here, to ensure GetBitContexts from previous
  3878. * packets do not get used. */
  3879. h->data_partitioning = 0;
  3880. /* end of stream, output what is still in the buffers */
  3881. if (buf_size == 0) {
  3882. out:
  3883. h->cur_pic_ptr = NULL;
  3884. h->first_field = 0;
  3885. // FIXME factorize this with the output code below
  3886. out = h->delayed_pic[0];
  3887. out_idx = 0;
  3888. for (i = 1;
  3889. h->delayed_pic[i] &&
  3890. !h->delayed_pic[i]->f.key_frame &&
  3891. !h->delayed_pic[i]->mmco_reset;
  3892. i++)
  3893. if (h->delayed_pic[i]->poc < out->poc) {
  3894. out = h->delayed_pic[i];
  3895. out_idx = i;
  3896. }
  3897. for (i = out_idx; h->delayed_pic[i]; i++)
  3898. h->delayed_pic[i] = h->delayed_pic[i + 1];
  3899. if (out) {
  3900. out->reference &= ~DELAYED_PIC_REF;
  3901. ret = output_frame(h, pict, out);
  3902. if (ret < 0)
  3903. return ret;
  3904. *got_frame = 1;
  3905. }
  3906. return buf_index;
  3907. }
  3908. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  3909. int cnt= buf[5]&0x1f;
  3910. const uint8_t *p= buf+6;
  3911. while(cnt--){
  3912. int nalsize= AV_RB16(p) + 2;
  3913. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  3914. goto not_extra;
  3915. p += nalsize;
  3916. }
  3917. cnt = *(p++);
  3918. if(!cnt)
  3919. goto not_extra;
  3920. while(cnt--){
  3921. int nalsize= AV_RB16(p) + 2;
  3922. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  3923. goto not_extra;
  3924. p += nalsize;
  3925. }
  3926. return ff_h264_decode_extradata(h, buf, buf_size);
  3927. }
  3928. not_extra:
  3929. buf_index = decode_nal_units(h, buf, buf_size, 0);
  3930. if (buf_index < 0)
  3931. return AVERROR_INVALIDDATA;
  3932. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3933. av_assert0(buf_index <= buf_size);
  3934. goto out;
  3935. }
  3936. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  3937. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  3938. buf_size >= 4 && !memcmp("Q264", buf, 4))
  3939. return buf_size;
  3940. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3941. return AVERROR_INVALIDDATA;
  3942. }
  3943. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  3944. (h->mb_y >= h->mb_height && h->mb_height)) {
  3945. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  3946. decode_postinit(h, 1);
  3947. field_end(h, 0);
  3948. /* Wait for second field. */
  3949. *got_frame = 0;
  3950. if (h->next_output_pic && (
  3951. h->next_output_pic->recovered)) {
  3952. if (!h->next_output_pic->recovered)
  3953. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  3954. ret = output_frame(h, pict, h->next_output_pic);
  3955. if (ret < 0)
  3956. return ret;
  3957. *got_frame = 1;
  3958. if (CONFIG_MPEGVIDEO) {
  3959. ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
  3960. &h->low_delay,
  3961. h->mb_width, h->mb_height, h->mb_stride, 1);
  3962. }
  3963. }
  3964. }
  3965. assert(pict->buf[0] || !*got_frame);
  3966. return get_consumed_bytes(buf_index, buf_size);
  3967. }
  3968. av_cold void ff_h264_free_context(H264Context *h)
  3969. {
  3970. int i;
  3971. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  3972. for (i = 0; i < MAX_SPS_COUNT; i++)
  3973. av_freep(h->sps_buffers + i);
  3974. for (i = 0; i < MAX_PPS_COUNT; i++)
  3975. av_freep(h->pps_buffers + i);
  3976. }
  3977. static av_cold int h264_decode_end(AVCodecContext *avctx)
  3978. {
  3979. H264Context *h = avctx->priv_data;
  3980. ff_h264_remove_all_refs(h);
  3981. ff_h264_free_context(h);
  3982. unref_picture(h, &h->cur_pic);
  3983. return 0;
  3984. }
  3985. static const AVProfile profiles[] = {
  3986. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3987. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3988. { FF_PROFILE_H264_MAIN, "Main" },
  3989. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3990. { FF_PROFILE_H264_HIGH, "High" },
  3991. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3992. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3993. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3994. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3995. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3996. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3997. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3998. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3999. { FF_PROFILE_UNKNOWN },
  4000. };
  4001. static const AVOption h264_options[] = {
  4002. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  4003. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  4004. {NULL}
  4005. };
  4006. static const AVClass h264_class = {
  4007. .class_name = "H264 Decoder",
  4008. .item_name = av_default_item_name,
  4009. .option = h264_options,
  4010. .version = LIBAVUTIL_VERSION_INT,
  4011. };
  4012. static const AVClass h264_vdpau_class = {
  4013. .class_name = "H264 VDPAU Decoder",
  4014. .item_name = av_default_item_name,
  4015. .option = h264_options,
  4016. .version = LIBAVUTIL_VERSION_INT,
  4017. };
  4018. AVCodec ff_h264_decoder = {
  4019. .name = "h264",
  4020. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4021. .type = AVMEDIA_TYPE_VIDEO,
  4022. .id = AV_CODEC_ID_H264,
  4023. .priv_data_size = sizeof(H264Context),
  4024. .init = ff_h264_decode_init,
  4025. .close = h264_decode_end,
  4026. .decode = h264_decode_frame,
  4027. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4028. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4029. CODEC_CAP_FRAME_THREADS,
  4030. .flush = flush_dpb,
  4031. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4032. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4033. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4034. .priv_class = &h264_class,
  4035. };
  4036. #if CONFIG_H264_VDPAU_DECODER
  4037. AVCodec ff_h264_vdpau_decoder = {
  4038. .name = "h264_vdpau",
  4039. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4040. .type = AVMEDIA_TYPE_VIDEO,
  4041. .id = AV_CODEC_ID_H264,
  4042. .priv_data_size = sizeof(H264Context),
  4043. .init = ff_h264_decode_init,
  4044. .close = h264_decode_end,
  4045. .decode = h264_decode_frame,
  4046. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4047. .flush = flush_dpb,
  4048. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4049. AV_PIX_FMT_NONE},
  4050. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4051. .priv_class = &h264_vdpau_class,
  4052. };
  4053. #endif