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.

4908 lines
181KB

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