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.

4955 lines
183KB

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