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.

5061 lines
186KB

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