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.

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