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.

2376 lines
87KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/timer.h"
  29. #include "internal.h"
  30. #include "cabac.h"
  31. #include "cabac_functions.h"
  32. #include "error_resilience.h"
  33. #include "avcodec.h"
  34. #include "h264.h"
  35. #include "h264data.h"
  36. #include "h264chroma.h"
  37. #include "h264_mvpred.h"
  38. #include "golomb.h"
  39. #include "mathops.h"
  40. #include "mpegutils.h"
  41. #include "rectangle.h"
  42. #include "thread.h"
  43. static const uint8_t rem6[QP_MAX_NUM + 1] = {
  44. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  45. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  46. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
  47. };
  48. static const uint8_t div6[QP_MAX_NUM + 1] = {
  49. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
  50. 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
  51. 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
  52. };
  53. static const uint8_t field_scan[16] = {
  54. 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
  55. 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
  56. 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
  57. 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
  58. };
  59. static const uint8_t field_scan8x8[64] = {
  60. 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
  61. 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
  62. 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
  63. 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
  64. 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
  65. 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
  66. 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
  67. 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
  68. 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
  69. 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
  70. 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
  71. 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
  72. 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
  73. 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
  74. 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
  75. 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
  76. };
  77. static const uint8_t field_scan8x8_cavlc[64] = {
  78. 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
  79. 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
  80. 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
  81. 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
  82. 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
  83. 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
  84. 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
  85. 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
  86. 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
  87. 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
  88. 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
  89. 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
  90. 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
  91. 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
  92. 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
  93. 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
  94. };
  95. // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
  96. static const uint8_t zigzag_scan8x8_cavlc[64] = {
  97. 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
  98. 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
  99. 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
  100. 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
  101. 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
  102. 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
  103. 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
  104. 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
  105. 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
  106. 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
  107. 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
  108. 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
  109. 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
  110. 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
  111. 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
  112. 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
  113. };
  114. static const uint8_t dequant4_coeff_init[6][3] = {
  115. { 10, 13, 16 },
  116. { 11, 14, 18 },
  117. { 13, 16, 20 },
  118. { 14, 18, 23 },
  119. { 16, 20, 25 },
  120. { 18, 23, 29 },
  121. };
  122. static const uint8_t dequant8_coeff_init_scan[16] = {
  123. 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
  124. };
  125. static const uint8_t dequant8_coeff_init[6][6] = {
  126. { 20, 18, 32, 19, 25, 24 },
  127. { 22, 19, 35, 21, 28, 26 },
  128. { 26, 23, 42, 24, 33, 31 },
  129. { 28, 25, 45, 26, 35, 33 },
  130. { 32, 28, 51, 30, 40, 38 },
  131. { 36, 32, 58, 34, 46, 43 },
  132. };
  133. static void release_unused_pictures(H264Context *h, int remove_current)
  134. {
  135. int i;
  136. /* release non reference frames */
  137. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  138. if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
  139. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  140. ff_h264_unref_picture(h, &h->DPB[i]);
  141. }
  142. }
  143. }
  144. static int alloc_scratch_buffers(H264Context *h, int linesize)
  145. {
  146. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  147. if (h->bipred_scratchpad)
  148. return 0;
  149. h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
  150. // edge emu needs blocksize + filter length - 1
  151. // (= 21x21 for h264)
  152. h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
  153. if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
  154. av_freep(&h->bipred_scratchpad);
  155. av_freep(&h->edge_emu_buffer);
  156. return AVERROR(ENOMEM);
  157. }
  158. return 0;
  159. }
  160. static int init_table_pools(H264Context *h)
  161. {
  162. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  163. const int mb_array_size = h->mb_stride * h->mb_height;
  164. const int b4_stride = h->mb_width * 4 + 1;
  165. const int b4_array_size = b4_stride * h->mb_height * 4;
  166. h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
  167. av_buffer_allocz);
  168. h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
  169. sizeof(uint32_t), av_buffer_allocz);
  170. h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
  171. sizeof(int16_t), av_buffer_allocz);
  172. h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
  173. if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
  174. !h->ref_index_pool) {
  175. av_buffer_pool_uninit(&h->qscale_table_pool);
  176. av_buffer_pool_uninit(&h->mb_type_pool);
  177. av_buffer_pool_uninit(&h->motion_val_pool);
  178. av_buffer_pool_uninit(&h->ref_index_pool);
  179. return AVERROR(ENOMEM);
  180. }
  181. return 0;
  182. }
  183. static int alloc_picture(H264Context *h, H264Picture *pic)
  184. {
  185. int i, ret = 0;
  186. av_assert0(!pic->f.data[0]);
  187. pic->tf.f = &pic->f;
  188. ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
  189. AV_GET_BUFFER_FLAG_REF : 0);
  190. if (ret < 0)
  191. goto fail;
  192. h->linesize = pic->f.linesize[0];
  193. h->uvlinesize = pic->f.linesize[1];
  194. if (h->avctx->hwaccel) {
  195. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  196. av_assert0(!pic->hwaccel_picture_private);
  197. if (hwaccel->frame_priv_data_size) {
  198. pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
  199. if (!pic->hwaccel_priv_buf)
  200. return AVERROR(ENOMEM);
  201. pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
  202. }
  203. }
  204. if (!h->qscale_table_pool) {
  205. ret = init_table_pools(h);
  206. if (ret < 0)
  207. goto fail;
  208. }
  209. pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
  210. pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
  211. if (!pic->qscale_table_buf || !pic->mb_type_buf)
  212. goto fail;
  213. pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
  214. pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
  215. for (i = 0; i < 2; i++) {
  216. pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
  217. pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
  218. if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
  219. goto fail;
  220. pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
  221. pic->ref_index[i] = pic->ref_index_buf[i]->data;
  222. }
  223. return 0;
  224. fail:
  225. ff_h264_unref_picture(h, pic);
  226. return (ret < 0) ? ret : AVERROR(ENOMEM);
  227. }
  228. static inline int pic_is_unused(H264Context *h, H264Picture *pic)
  229. {
  230. if (!pic->f.buf[0])
  231. return 1;
  232. if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
  233. return 1;
  234. return 0;
  235. }
  236. static int find_unused_picture(H264Context *h)
  237. {
  238. int i;
  239. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  240. if (pic_is_unused(h, &h->DPB[i]))
  241. break;
  242. }
  243. if (i == H264_MAX_PICTURE_COUNT)
  244. return AVERROR_INVALIDDATA;
  245. if (h->DPB[i].needs_realloc) {
  246. h->DPB[i].needs_realloc = 0;
  247. ff_h264_unref_picture(h, &h->DPB[i]);
  248. }
  249. return i;
  250. }
  251. static void init_dequant8_coeff_table(H264Context *h)
  252. {
  253. int i, j, q, x;
  254. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  255. for (i = 0; i < 6; i++) {
  256. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  257. for (j = 0; j < i; j++)
  258. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  259. 64 * sizeof(uint8_t))) {
  260. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  261. break;
  262. }
  263. if (j < i)
  264. continue;
  265. for (q = 0; q < max_qp + 1; q++) {
  266. int shift = div6[q];
  267. int idx = rem6[q];
  268. for (x = 0; x < 64; x++)
  269. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  270. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  271. h->pps.scaling_matrix8[i][x]) << shift;
  272. }
  273. }
  274. }
  275. static void init_dequant4_coeff_table(H264Context *h)
  276. {
  277. int i, j, q, x;
  278. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  279. for (i = 0; i < 6; i++) {
  280. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  281. for (j = 0; j < i; j++)
  282. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  283. 16 * sizeof(uint8_t))) {
  284. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  285. break;
  286. }
  287. if (j < i)
  288. continue;
  289. for (q = 0; q < max_qp + 1; q++) {
  290. int shift = div6[q] + 2;
  291. int idx = rem6[q];
  292. for (x = 0; x < 16; x++)
  293. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  294. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  295. h->pps.scaling_matrix4[i][x]) << shift;
  296. }
  297. }
  298. }
  299. void h264_init_dequant_tables(H264Context *h)
  300. {
  301. int i, x;
  302. init_dequant4_coeff_table(h);
  303. if (h->pps.transform_8x8_mode)
  304. init_dequant8_coeff_table(h);
  305. if (h->sps.transform_bypass) {
  306. for (i = 0; i < 6; i++)
  307. for (x = 0; x < 16; x++)
  308. h->dequant4_coeff[i][0][x] = 1 << 6;
  309. if (h->pps.transform_8x8_mode)
  310. for (i = 0; i < 6; i++)
  311. for (x = 0; x < 64; x++)
  312. h->dequant8_coeff[i][0][x] = 1 << 6;
  313. }
  314. }
  315. /**
  316. * Mimic alloc_tables(), but for every context thread.
  317. */
  318. static void clone_tables(H264Context *dst, H264SliceContext *sl,
  319. H264Context *src, int i)
  320. {
  321. sl->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
  322. sl->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
  323. sl->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
  324. dst->non_zero_count = src->non_zero_count;
  325. dst->slice_table = src->slice_table;
  326. dst->cbp_table = src->cbp_table;
  327. dst->mb2b_xy = src->mb2b_xy;
  328. dst->mb2br_xy = src->mb2br_xy;
  329. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  330. dst->direct_table = src->direct_table;
  331. dst->list_counts = src->list_counts;
  332. dst->DPB = src->DPB;
  333. dst->cur_pic_ptr = src->cur_pic_ptr;
  334. dst->cur_pic = src->cur_pic;
  335. dst->bipred_scratchpad = NULL;
  336. dst->edge_emu_buffer = NULL;
  337. ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
  338. src->sps.chroma_format_idc);
  339. }
  340. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  341. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  342. ((pic && pic >= old_ctx->DPB && \
  343. pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
  344. &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
  345. static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
  346. H264Context *new_base,
  347. H264Context *old_base)
  348. {
  349. int i;
  350. for (i = 0; i < count; i++) {
  351. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  352. IN_RANGE(from[i], old_base->DPB,
  353. sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
  354. !from[i]));
  355. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  356. }
  357. }
  358. static int copy_parameter_set(void **to, void **from, int count, int size)
  359. {
  360. int i;
  361. for (i = 0; i < count; i++) {
  362. if (to[i] && !from[i]) {
  363. av_freep(&to[i]);
  364. } else if (from[i] && !to[i]) {
  365. to[i] = av_malloc(size);
  366. if (!to[i])
  367. return AVERROR(ENOMEM);
  368. }
  369. if (from[i])
  370. memcpy(to[i], from[i], size);
  371. }
  372. return 0;
  373. }
  374. #define copy_fields(to, from, start_field, end_field) \
  375. memcpy(&to->start_field, &from->start_field, \
  376. (char *)&to->end_field - (char *)&to->start_field)
  377. static int h264_slice_header_init(H264Context *h, int reinit);
  378. int ff_h264_update_thread_context(AVCodecContext *dst,
  379. const AVCodecContext *src)
  380. {
  381. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  382. int inited = h->context_initialized, err = 0;
  383. int context_reinitialized = 0;
  384. int i, ret;
  385. if (dst == src || !h1->context_initialized)
  386. return 0;
  387. if (inited &&
  388. (h->width != h1->width ||
  389. h->height != h1->height ||
  390. h->mb_width != h1->mb_width ||
  391. h->mb_height != h1->mb_height ||
  392. h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
  393. h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
  394. h->sps.colorspace != h1->sps.colorspace)) {
  395. /* set bits_per_raw_sample to the previous value. the check for changed
  396. * bit depth in h264_set_parameter_from_sps() uses it and sets it to
  397. * the current value */
  398. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  399. av_freep(&h->bipred_scratchpad);
  400. h->width = h1->width;
  401. h->height = h1->height;
  402. h->mb_height = h1->mb_height;
  403. h->mb_width = h1->mb_width;
  404. h->mb_num = h1->mb_num;
  405. h->mb_stride = h1->mb_stride;
  406. h->b_stride = h1->b_stride;
  407. if ((err = h264_slice_header_init(h, 1)) < 0) {
  408. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  409. return err;
  410. }
  411. context_reinitialized = 1;
  412. /* update linesize on resize. The decoder doesn't
  413. * necessarily call h264_frame_start in the new thread */
  414. h->linesize = h1->linesize;
  415. h->uvlinesize = h1->uvlinesize;
  416. /* copy block_offset since frame_start may not be called */
  417. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  418. }
  419. if (!inited) {
  420. H264SliceContext *orig_slice_ctx = h->slice_ctx;
  421. for (i = 0; i < MAX_SPS_COUNT; i++)
  422. av_freep(h->sps_buffers + i);
  423. for (i = 0; i < MAX_PPS_COUNT; i++)
  424. av_freep(h->pps_buffers + i);
  425. memcpy(h, h1, sizeof(*h1));
  426. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  427. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  428. memset(&h->er, 0, sizeof(h->er));
  429. h->context_initialized = 0;
  430. memset(&h->cur_pic, 0, sizeof(h->cur_pic));
  431. av_frame_unref(&h->cur_pic.f);
  432. h->cur_pic.tf.f = &h->cur_pic.f;
  433. h->slice_ctx = orig_slice_ctx;
  434. memset(&h->slice_ctx[0].mb, 0, sizeof(h->slice_ctx[0].mb));
  435. memset(&h->slice_ctx[0].mb_luma_dc, 0, sizeof(h->slice_ctx[0].mb_luma_dc));
  436. memset(&h->slice_ctx[0].mb_padding, 0, sizeof(h->slice_ctx[0].mb_padding));
  437. h->avctx = dst;
  438. h->DPB = NULL;
  439. h->qscale_table_pool = NULL;
  440. h->mb_type_pool = NULL;
  441. h->ref_index_pool = NULL;
  442. h->motion_val_pool = NULL;
  443. ret = ff_h264_alloc_tables(h);
  444. if (ret < 0) {
  445. av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
  446. return ret;
  447. }
  448. ret = ff_h264_context_init(h);
  449. if (ret < 0) {
  450. av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
  451. return ret;
  452. }
  453. for (i = 0; i < 2; i++) {
  454. h->rbsp_buffer[i] = NULL;
  455. h->rbsp_buffer_size[i] = 0;
  456. }
  457. h->bipred_scratchpad = NULL;
  458. h->edge_emu_buffer = NULL;
  459. h->thread_context[0] = h;
  460. h->context_initialized = 1;
  461. }
  462. h->avctx->coded_height = h1->avctx->coded_height;
  463. h->avctx->coded_width = h1->avctx->coded_width;
  464. h->avctx->width = h1->avctx->width;
  465. h->avctx->height = h1->avctx->height;
  466. h->coded_picture_number = h1->coded_picture_number;
  467. h->first_field = h1->first_field;
  468. h->picture_structure = h1->picture_structure;
  469. h->droppable = h1->droppable;
  470. h->low_delay = h1->low_delay;
  471. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  472. ff_h264_unref_picture(h, &h->DPB[i]);
  473. if (h1->DPB[i].f.buf[0] &&
  474. (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
  475. return ret;
  476. }
  477. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  478. ff_h264_unref_picture(h, &h->cur_pic);
  479. if (h1->cur_pic.f.buf[0]) {
  480. ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
  481. if (ret < 0)
  482. return ret;
  483. }
  484. h->workaround_bugs = h1->workaround_bugs;
  485. h->low_delay = h1->low_delay;
  486. h->droppable = h1->droppable;
  487. /* frame_start may not be called for the next thread (if it's decoding
  488. * a bottom field) so this has to be allocated here */
  489. err = alloc_scratch_buffers(h, h1->linesize);
  490. if (err < 0)
  491. return err;
  492. // extradata/NAL handling
  493. h->is_avc = h1->is_avc;
  494. // SPS/PPS
  495. if ((ret = copy_parameter_set((void **)h->sps_buffers,
  496. (void **)h1->sps_buffers,
  497. MAX_SPS_COUNT, sizeof(SPS))) < 0)
  498. return ret;
  499. h->sps = h1->sps;
  500. if ((ret = copy_parameter_set((void **)h->pps_buffers,
  501. (void **)h1->pps_buffers,
  502. MAX_PPS_COUNT, sizeof(PPS))) < 0)
  503. return ret;
  504. h->pps = h1->pps;
  505. // Dequantization matrices
  506. // FIXME these are big - can they be only copied when PPS changes?
  507. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  508. for (i = 0; i < 6; i++)
  509. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  510. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  511. for (i = 0; i < 6; i++)
  512. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  513. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  514. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  515. // POC timing
  516. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  517. // reference lists
  518. copy_fields(h, h1, short_ref, thread_context);
  519. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  520. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  521. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  522. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  523. h->last_slice_type = h1->last_slice_type;
  524. if (context_reinitialized)
  525. ff_h264_set_parameter_from_sps(h);
  526. if (!h->cur_pic_ptr)
  527. return 0;
  528. if (!h->droppable) {
  529. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  530. h->prev_poc_msb = h->poc_msb;
  531. h->prev_poc_lsb = h->poc_lsb;
  532. }
  533. h->prev_frame_num_offset = h->frame_num_offset;
  534. h->prev_frame_num = h->frame_num;
  535. h->outputed_poc = h->next_outputed_poc;
  536. h->recovery_frame = h1->recovery_frame;
  537. h->frame_recovered = h1->frame_recovered;
  538. return err;
  539. }
  540. static int h264_frame_start(H264Context *h)
  541. {
  542. H264Picture *pic;
  543. int i, ret;
  544. const int pixel_shift = h->pixel_shift;
  545. release_unused_pictures(h, 1);
  546. h->cur_pic_ptr = NULL;
  547. i = find_unused_picture(h);
  548. if (i < 0) {
  549. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  550. return i;
  551. }
  552. pic = &h->DPB[i];
  553. pic->reference = h->droppable ? 0 : h->picture_structure;
  554. pic->f.coded_picture_number = h->coded_picture_number++;
  555. pic->field_picture = h->picture_structure != PICT_FRAME;
  556. /*
  557. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  558. * in later.
  559. * See decode_nal_units().
  560. */
  561. pic->f.key_frame = 0;
  562. pic->mmco_reset = 0;
  563. pic->recovered = 0;
  564. if ((ret = alloc_picture(h, pic)) < 0)
  565. return ret;
  566. h->cur_pic_ptr = pic;
  567. ff_h264_unref_picture(h, &h->cur_pic);
  568. if ((ret = ff_h264_ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
  569. return ret;
  570. if (CONFIG_ERROR_RESILIENCE)
  571. ff_er_frame_start(&h->er);
  572. assert(h->linesize && h->uvlinesize);
  573. for (i = 0; i < 16; i++) {
  574. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  575. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  576. }
  577. for (i = 0; i < 16; i++) {
  578. h->block_offset[16 + i] =
  579. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  580. h->block_offset[48 + 16 + i] =
  581. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  582. }
  583. /* can't be in alloc_tables because linesize isn't known there.
  584. * FIXME: redo bipred weight to not require extra buffer? */
  585. for (i = 0; i < h->slice_context_count; i++)
  586. if (h->thread_context[i]) {
  587. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  588. if (ret < 0)
  589. return ret;
  590. }
  591. /* Some macroblocks can be accessed before they're available in case
  592. * of lost slices, MBAFF or threading. */
  593. memset(h->slice_table, -1,
  594. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  595. /* We mark the current picture as non-reference after allocating it, so
  596. * that if we break out due to an error it can be released automatically
  597. * in the next ff_mpv_frame_start().
  598. */
  599. h->cur_pic_ptr->reference = 0;
  600. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  601. h->next_output_pic = NULL;
  602. assert(h->cur_pic_ptr->long_ref == 0);
  603. return 0;
  604. }
  605. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  606. uint8_t *src_cb, uint8_t *src_cr,
  607. int linesize, int uvlinesize,
  608. int simple)
  609. {
  610. uint8_t *top_border;
  611. int top_idx = 1;
  612. const int pixel_shift = h->pixel_shift;
  613. int chroma444 = CHROMA444(h);
  614. int chroma422 = CHROMA422(h);
  615. src_y -= linesize;
  616. src_cb -= uvlinesize;
  617. src_cr -= uvlinesize;
  618. if (!simple && FRAME_MBAFF(h)) {
  619. if (h->mb_y & 1) {
  620. if (!MB_MBAFF(h)) {
  621. top_border = h->top_borders[0][h->mb_x];
  622. AV_COPY128(top_border, src_y + 15 * linesize);
  623. if (pixel_shift)
  624. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  625. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  626. if (chroma444) {
  627. if (pixel_shift) {
  628. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  629. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  630. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  631. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  632. } else {
  633. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  634. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  635. }
  636. } else if (chroma422) {
  637. if (pixel_shift) {
  638. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  639. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  640. } else {
  641. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  642. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  643. }
  644. } else {
  645. if (pixel_shift) {
  646. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  647. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  648. } else {
  649. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  650. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  651. }
  652. }
  653. }
  654. }
  655. } else if (MB_MBAFF(h)) {
  656. top_idx = 0;
  657. } else
  658. return;
  659. }
  660. top_border = h->top_borders[top_idx][h->mb_x];
  661. /* There are two lines saved, the line above the top macroblock
  662. * of a pair, and the line above the bottom macroblock. */
  663. AV_COPY128(top_border, src_y + 16 * linesize);
  664. if (pixel_shift)
  665. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  666. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  667. if (chroma444) {
  668. if (pixel_shift) {
  669. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  670. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  671. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  672. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  673. } else {
  674. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  675. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  676. }
  677. } else if (chroma422) {
  678. if (pixel_shift) {
  679. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  680. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  681. } else {
  682. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  683. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  684. }
  685. } else {
  686. if (pixel_shift) {
  687. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  688. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  689. } else {
  690. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  691. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  692. }
  693. }
  694. }
  695. }
  696. /**
  697. * Initialize implicit_weight table.
  698. * @param field 0/1 initialize the weight for interlaced MBAFF
  699. * -1 initializes the rest
  700. */
  701. static void implicit_weight_table(H264Context *h, H264SliceContext *sl, int field)
  702. {
  703. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  704. for (i = 0; i < 2; i++) {
  705. sl->luma_weight_flag[i] = 0;
  706. sl->chroma_weight_flag[i] = 0;
  707. }
  708. if (field < 0) {
  709. if (h->picture_structure == PICT_FRAME) {
  710. cur_poc = h->cur_pic_ptr->poc;
  711. } else {
  712. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  713. }
  714. if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
  715. sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
  716. sl->use_weight = 0;
  717. sl->use_weight_chroma = 0;
  718. return;
  719. }
  720. ref_start = 0;
  721. ref_count0 = sl->ref_count[0];
  722. ref_count1 = sl->ref_count[1];
  723. } else {
  724. cur_poc = h->cur_pic_ptr->field_poc[field];
  725. ref_start = 16;
  726. ref_count0 = 16 + 2 * sl->ref_count[0];
  727. ref_count1 = 16 + 2 * sl->ref_count[1];
  728. }
  729. sl->use_weight = 2;
  730. sl->use_weight_chroma = 2;
  731. sl->luma_log2_weight_denom = 5;
  732. sl->chroma_log2_weight_denom = 5;
  733. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  734. int poc0 = sl->ref_list[0][ref0].poc;
  735. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  736. int w = 32;
  737. if (!sl->ref_list[0][ref0].long_ref && !sl->ref_list[1][ref1].long_ref) {
  738. int poc1 = sl->ref_list[1][ref1].poc;
  739. int td = av_clip_int8(poc1 - poc0);
  740. if (td) {
  741. int tb = av_clip_int8(cur_poc - poc0);
  742. int tx = (16384 + (FFABS(td) >> 1)) / td;
  743. int dist_scale_factor = (tb * tx + 32) >> 8;
  744. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  745. w = 64 - dist_scale_factor;
  746. }
  747. }
  748. if (field < 0) {
  749. sl->implicit_weight[ref0][ref1][0] =
  750. sl->implicit_weight[ref0][ref1][1] = w;
  751. } else {
  752. sl->implicit_weight[ref0][ref1][field] = w;
  753. }
  754. }
  755. }
  756. }
  757. /**
  758. * initialize scan tables
  759. */
  760. static void init_scan_tables(H264Context *h)
  761. {
  762. int i;
  763. for (i = 0; i < 16; i++) {
  764. #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
  765. h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
  766. h->field_scan[i] = TRANSPOSE(field_scan[i]);
  767. #undef TRANSPOSE
  768. }
  769. for (i = 0; i < 64; i++) {
  770. #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
  771. h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
  772. h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
  773. h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
  774. h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
  775. #undef TRANSPOSE
  776. }
  777. if (h->sps.transform_bypass) { // FIXME same ugly
  778. h->zigzag_scan_q0 = zigzag_scan;
  779. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  780. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  781. h->field_scan_q0 = field_scan;
  782. h->field_scan8x8_q0 = field_scan8x8;
  783. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  784. } else {
  785. h->zigzag_scan_q0 = h->zigzag_scan;
  786. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  787. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  788. h->field_scan_q0 = h->field_scan;
  789. h->field_scan8x8_q0 = h->field_scan8x8;
  790. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  791. }
  792. }
  793. /**
  794. * Replicate H264 "master" context to thread contexts.
  795. */
  796. static int clone_slice(H264Context *dst, H264Context *src)
  797. {
  798. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  799. dst->cur_pic_ptr = src->cur_pic_ptr;
  800. dst->cur_pic = src->cur_pic;
  801. dst->linesize = src->linesize;
  802. dst->uvlinesize = src->uvlinesize;
  803. dst->first_field = src->first_field;
  804. dst->prev_poc_msb = src->prev_poc_msb;
  805. dst->prev_poc_lsb = src->prev_poc_lsb;
  806. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  807. dst->prev_frame_num = src->prev_frame_num;
  808. dst->short_ref_count = src->short_ref_count;
  809. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  810. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  811. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  812. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  813. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  814. return 0;
  815. }
  816. static enum AVPixelFormat get_pixel_format(H264Context *h)
  817. {
  818. #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
  819. CONFIG_H264_VAAPI_HWACCEL + \
  820. (CONFIG_H264_VDA_HWACCEL * 2) + \
  821. CONFIG_H264_VDPAU_HWACCEL)
  822. enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
  823. const enum AVPixelFormat *choices = pix_fmts;
  824. switch (h->sps.bit_depth_luma) {
  825. case 9:
  826. if (CHROMA444(h)) {
  827. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  828. *fmt++ = AV_PIX_FMT_GBRP9;
  829. } else
  830. *fmt++ = AV_PIX_FMT_YUV444P9;
  831. } else if (CHROMA422(h))
  832. *fmt++ = AV_PIX_FMT_YUV422P9;
  833. else
  834. *fmt++ = AV_PIX_FMT_YUV420P9;
  835. break;
  836. case 10:
  837. if (CHROMA444(h)) {
  838. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  839. *fmt++ = AV_PIX_FMT_GBRP10;
  840. } else
  841. *fmt++ = AV_PIX_FMT_YUV444P10;
  842. } else if (CHROMA422(h))
  843. *fmt++ = AV_PIX_FMT_YUV422P10;
  844. else
  845. *fmt++ = AV_PIX_FMT_YUV420P10;
  846. break;
  847. case 8:
  848. #if CONFIG_H264_VDPAU_HWACCEL
  849. *fmt++ = AV_PIX_FMT_VDPAU;
  850. #endif
  851. if (CHROMA444(h)) {
  852. if (h->avctx->colorspace == AVCOL_SPC_RGB)
  853. *fmt++ = AV_PIX_FMT_GBRP;
  854. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  855. *fmt++ = AV_PIX_FMT_YUVJ444P;
  856. else
  857. *fmt++ = AV_PIX_FMT_YUV444P;
  858. } else if (CHROMA422(h)) {
  859. if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  860. *fmt++ = AV_PIX_FMT_YUVJ422P;
  861. else
  862. *fmt++ = AV_PIX_FMT_YUV422P;
  863. } else {
  864. #if CONFIG_H264_DXVA2_HWACCEL
  865. *fmt++ = AV_PIX_FMT_DXVA2_VLD;
  866. #endif
  867. #if CONFIG_H264_VAAPI_HWACCEL
  868. *fmt++ = AV_PIX_FMT_VAAPI_VLD;
  869. #endif
  870. #if CONFIG_H264_VDA_HWACCEL
  871. *fmt++ = AV_PIX_FMT_VDA_VLD;
  872. *fmt++ = AV_PIX_FMT_VDA;
  873. #endif
  874. if (h->avctx->codec->pix_fmts)
  875. choices = h->avctx->codec->pix_fmts;
  876. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  877. *fmt++ = AV_PIX_FMT_YUVJ420P;
  878. else
  879. *fmt++ = AV_PIX_FMT_YUV420P;
  880. }
  881. break;
  882. default:
  883. av_log(h->avctx, AV_LOG_ERROR,
  884. "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
  885. return AVERROR_INVALIDDATA;
  886. }
  887. *fmt = AV_PIX_FMT_NONE;
  888. return ff_get_format(h->avctx, choices);
  889. }
  890. /* export coded and cropped frame dimensions to AVCodecContext */
  891. static int init_dimensions(H264Context *h)
  892. {
  893. int width = h->width - (h->sps.crop_right + h->sps.crop_left);
  894. int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
  895. int crop_present = h->sps.crop_left || h->sps.crop_top ||
  896. h->sps.crop_right || h->sps.crop_bottom;
  897. /* handle container cropping */
  898. if (!crop_present &&
  899. FFALIGN(h->avctx->width, 16) == h->width &&
  900. FFALIGN(h->avctx->height, 16) == h->height) {
  901. width = h->avctx->width;
  902. height = h->avctx->height;
  903. }
  904. if (width <= 0 || height <= 0) {
  905. av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
  906. width, height);
  907. if (h->avctx->err_recognition & AV_EF_EXPLODE)
  908. return AVERROR_INVALIDDATA;
  909. av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
  910. h->sps.crop_bottom =
  911. h->sps.crop_top =
  912. h->sps.crop_right =
  913. h->sps.crop_left =
  914. h->sps.crop = 0;
  915. width = h->width;
  916. height = h->height;
  917. }
  918. h->avctx->coded_width = h->width;
  919. h->avctx->coded_height = h->height;
  920. h->avctx->width = width;
  921. h->avctx->height = height;
  922. return 0;
  923. }
  924. static int h264_slice_header_init(H264Context *h, int reinit)
  925. {
  926. int nb_slices = (HAVE_THREADS &&
  927. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  928. h->avctx->thread_count : 1;
  929. int i, ret;
  930. ff_set_sar(h->avctx, h->sps.sar);
  931. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  932. &h->chroma_x_shift, &h->chroma_y_shift);
  933. if (h->sps.timing_info_present_flag) {
  934. int64_t den = h->sps.time_scale;
  935. if (h->x264_build < 44U)
  936. den *= 2;
  937. av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
  938. h->sps.num_units_in_tick, den, 1 << 30);
  939. }
  940. if (reinit)
  941. ff_h264_free_tables(h, 0);
  942. h->first_field = 0;
  943. h->prev_interlaced_frame = 1;
  944. init_scan_tables(h);
  945. ret = ff_h264_alloc_tables(h);
  946. if (ret < 0) {
  947. av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
  948. return ret;
  949. }
  950. if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  951. int max_slices;
  952. if (h->mb_height)
  953. max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
  954. else
  955. max_slices = H264_MAX_THREADS;
  956. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
  957. " reducing to %d\n", nb_slices, max_slices);
  958. nb_slices = max_slices;
  959. }
  960. h->slice_context_count = nb_slices;
  961. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  962. ret = ff_h264_context_init(h);
  963. if (ret < 0) {
  964. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  965. return ret;
  966. }
  967. } else {
  968. for (i = 1; i < h->slice_context_count; i++) {
  969. H264Context *c;
  970. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  971. if (!c)
  972. return AVERROR(ENOMEM);
  973. c->avctx = h->avctx;
  974. c->vdsp = h->vdsp;
  975. c->h264dsp = h->h264dsp;
  976. c->h264qpel = h->h264qpel;
  977. c->h264chroma = h->h264chroma;
  978. c->sps = h->sps;
  979. c->pps = h->pps;
  980. c->pixel_shift = h->pixel_shift;
  981. c->width = h->width;
  982. c->height = h->height;
  983. c->linesize = h->linesize;
  984. c->uvlinesize = h->uvlinesize;
  985. c->chroma_x_shift = h->chroma_x_shift;
  986. c->chroma_y_shift = h->chroma_y_shift;
  987. c->droppable = h->droppable;
  988. c->low_delay = h->low_delay;
  989. c->mb_width = h->mb_width;
  990. c->mb_height = h->mb_height;
  991. c->mb_stride = h->mb_stride;
  992. c->mb_num = h->mb_num;
  993. c->flags = h->flags;
  994. c->workaround_bugs = h->workaround_bugs;
  995. c->pict_type = h->pict_type;
  996. h->slice_ctx[i].h264 = c;
  997. init_scan_tables(c);
  998. clone_tables(c, &h->slice_ctx[i], h, i);
  999. c->context_initialized = 1;
  1000. }
  1001. for (i = 0; i < h->slice_context_count; i++)
  1002. if ((ret = ff_h264_context_init(h->thread_context[i])) < 0) {
  1003. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  1004. return ret;
  1005. }
  1006. }
  1007. h->context_initialized = 1;
  1008. return 0;
  1009. }
  1010. /**
  1011. * Decode a slice header.
  1012. * This will (re)intialize the decoder and call h264_frame_start() as needed.
  1013. *
  1014. * @param h h264context
  1015. * @param h0 h264 master context (differs from 'h' when doing sliced based
  1016. * parallel decoding)
  1017. *
  1018. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  1019. */
  1020. int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl, H264Context *h0)
  1021. {
  1022. unsigned int first_mb_in_slice;
  1023. unsigned int pps_id;
  1024. int ret;
  1025. unsigned int slice_type, tmp, i, j;
  1026. int default_ref_list_done = 0;
  1027. int last_pic_structure, last_pic_droppable;
  1028. int needs_reinit = 0;
  1029. int field_pic_flag, bottom_field_flag;
  1030. h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  1031. h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  1032. first_mb_in_slice = get_ue_golomb(&h->gb);
  1033. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  1034. if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
  1035. ff_h264_field_end(h, sl, 1);
  1036. }
  1037. h0->current_slice = 0;
  1038. if (!h0->first_field) {
  1039. if (h->cur_pic_ptr && !h->droppable) {
  1040. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1041. h->picture_structure == PICT_BOTTOM_FIELD);
  1042. }
  1043. h->cur_pic_ptr = NULL;
  1044. }
  1045. }
  1046. slice_type = get_ue_golomb_31(&h->gb);
  1047. if (slice_type > 9) {
  1048. av_log(h->avctx, AV_LOG_ERROR,
  1049. "slice type %d too large at %d %d\n",
  1050. slice_type, h->mb_x, h->mb_y);
  1051. return AVERROR_INVALIDDATA;
  1052. }
  1053. if (slice_type > 4) {
  1054. slice_type -= 5;
  1055. sl->slice_type_fixed = 1;
  1056. } else
  1057. sl->slice_type_fixed = 0;
  1058. slice_type = golomb_to_pict_type[slice_type];
  1059. if (slice_type == AV_PICTURE_TYPE_I ||
  1060. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  1061. default_ref_list_done = 1;
  1062. }
  1063. sl->slice_type = slice_type;
  1064. sl->slice_type_nos = slice_type & 3;
  1065. if (h->nal_unit_type == NAL_IDR_SLICE &&
  1066. sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1067. av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
  1068. return AVERROR_INVALIDDATA;
  1069. }
  1070. // to make a few old functions happy, it's wrong though
  1071. h->pict_type = sl->slice_type;
  1072. pps_id = get_ue_golomb(&h->gb);
  1073. if (pps_id >= MAX_PPS_COUNT) {
  1074. av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
  1075. return AVERROR_INVALIDDATA;
  1076. }
  1077. if (!h0->pps_buffers[pps_id]) {
  1078. av_log(h->avctx, AV_LOG_ERROR,
  1079. "non-existing PPS %u referenced\n",
  1080. pps_id);
  1081. return AVERROR_INVALIDDATA;
  1082. }
  1083. h->pps = *h0->pps_buffers[pps_id];
  1084. if (!h0->sps_buffers[h->pps.sps_id]) {
  1085. av_log(h->avctx, AV_LOG_ERROR,
  1086. "non-existing SPS %u referenced\n",
  1087. h->pps.sps_id);
  1088. return AVERROR_INVALIDDATA;
  1089. }
  1090. if (h->pps.sps_id != h->sps.sps_id ||
  1091. h0->sps_buffers[h->pps.sps_id]->new) {
  1092. h0->sps_buffers[h->pps.sps_id]->new = 0;
  1093. h->sps = *h0->sps_buffers[h->pps.sps_id];
  1094. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  1095. h->chroma_format_idc != h->sps.chroma_format_idc) {
  1096. h->bit_depth_luma = h->sps.bit_depth_luma;
  1097. h->chroma_format_idc = h->sps.chroma_format_idc;
  1098. needs_reinit = 1;
  1099. }
  1100. if ((ret = ff_h264_set_parameter_from_sps(h)) < 0)
  1101. return ret;
  1102. }
  1103. h->avctx->profile = ff_h264_get_profile(&h->sps);
  1104. h->avctx->level = h->sps.level_idc;
  1105. h->avctx->refs = h->sps.ref_frame_count;
  1106. if (h->mb_width != h->sps.mb_width ||
  1107. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
  1108. needs_reinit = 1;
  1109. h->mb_width = h->sps.mb_width;
  1110. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  1111. h->mb_num = h->mb_width * h->mb_height;
  1112. h->mb_stride = h->mb_width + 1;
  1113. h->b_stride = h->mb_width * 4;
  1114. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  1115. h->width = 16 * h->mb_width;
  1116. h->height = 16 * h->mb_height;
  1117. ret = init_dimensions(h);
  1118. if (ret < 0)
  1119. return ret;
  1120. if (h->sps.video_signal_type_present_flag) {
  1121. h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
  1122. : AVCOL_RANGE_MPEG;
  1123. if (h->sps.colour_description_present_flag) {
  1124. if (h->avctx->colorspace != h->sps.colorspace)
  1125. needs_reinit = 1;
  1126. h->avctx->color_primaries = h->sps.color_primaries;
  1127. h->avctx->color_trc = h->sps.color_trc;
  1128. h->avctx->colorspace = h->sps.colorspace;
  1129. }
  1130. }
  1131. if (h->context_initialized && needs_reinit) {
  1132. if (h != h0) {
  1133. av_log(h->avctx, AV_LOG_ERROR,
  1134. "changing width %d -> %d / height %d -> %d on "
  1135. "slice %d\n",
  1136. h->width, h->avctx->coded_width,
  1137. h->height, h->avctx->coded_height,
  1138. h0->current_slice + 1);
  1139. return AVERROR_INVALIDDATA;
  1140. }
  1141. ff_h264_flush_change(h);
  1142. if ((ret = get_pixel_format(h)) < 0)
  1143. return ret;
  1144. h->avctx->pix_fmt = ret;
  1145. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  1146. "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
  1147. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  1148. av_log(h->avctx, AV_LOG_ERROR,
  1149. "h264_slice_header_init() failed\n");
  1150. return ret;
  1151. }
  1152. }
  1153. if (!h->context_initialized) {
  1154. if (h != h0) {
  1155. av_log(h->avctx, AV_LOG_ERROR,
  1156. "Cannot (re-)initialize context during parallel decoding.\n");
  1157. return AVERROR_PATCHWELCOME;
  1158. }
  1159. if ((ret = get_pixel_format(h)) < 0)
  1160. return ret;
  1161. h->avctx->pix_fmt = ret;
  1162. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  1163. av_log(h->avctx, AV_LOG_ERROR,
  1164. "h264_slice_header_init() failed\n");
  1165. return ret;
  1166. }
  1167. }
  1168. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  1169. h->dequant_coeff_pps = pps_id;
  1170. h264_init_dequant_tables(h);
  1171. }
  1172. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  1173. h->mb_mbaff = 0;
  1174. h->mb_aff_frame = 0;
  1175. last_pic_structure = h0->picture_structure;
  1176. last_pic_droppable = h0->droppable;
  1177. h->droppable = h->nal_ref_idc == 0;
  1178. if (h->sps.frame_mbs_only_flag) {
  1179. h->picture_structure = PICT_FRAME;
  1180. } else {
  1181. field_pic_flag = get_bits1(&h->gb);
  1182. if (field_pic_flag) {
  1183. bottom_field_flag = get_bits1(&h->gb);
  1184. h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
  1185. } else {
  1186. h->picture_structure = PICT_FRAME;
  1187. h->mb_aff_frame = h->sps.mb_aff;
  1188. }
  1189. }
  1190. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  1191. if (h0->current_slice != 0) {
  1192. if (last_pic_structure != h->picture_structure ||
  1193. last_pic_droppable != h->droppable) {
  1194. av_log(h->avctx, AV_LOG_ERROR,
  1195. "Changing field mode (%d -> %d) between slices is not allowed\n",
  1196. last_pic_structure, h->picture_structure);
  1197. h->picture_structure = last_pic_structure;
  1198. h->droppable = last_pic_droppable;
  1199. return AVERROR_INVALIDDATA;
  1200. } else if (!h0->cur_pic_ptr) {
  1201. av_log(h->avctx, AV_LOG_ERROR,
  1202. "unset cur_pic_ptr on slice %d\n",
  1203. h0->current_slice + 1);
  1204. return AVERROR_INVALIDDATA;
  1205. }
  1206. } else {
  1207. /* Shorten frame num gaps so we don't have to allocate reference
  1208. * frames just to throw them away */
  1209. if (h->frame_num != h->prev_frame_num) {
  1210. int unwrap_prev_frame_num = h->prev_frame_num;
  1211. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  1212. if (unwrap_prev_frame_num > h->frame_num)
  1213. unwrap_prev_frame_num -= max_frame_num;
  1214. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  1215. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  1216. if (unwrap_prev_frame_num < 0)
  1217. unwrap_prev_frame_num += max_frame_num;
  1218. h->prev_frame_num = unwrap_prev_frame_num;
  1219. }
  1220. }
  1221. /* See if we have a decoded first field looking for a pair...
  1222. * Here, we're using that to see if we should mark previously
  1223. * decode frames as "finished".
  1224. * We have to do that before the "dummy" in-between frame allocation,
  1225. * since that can modify s->current_picture_ptr. */
  1226. if (h0->first_field) {
  1227. assert(h0->cur_pic_ptr);
  1228. assert(h0->cur_pic_ptr->f.buf[0]);
  1229. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1230. /* figure out if we have a complementary field pair */
  1231. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1232. /* Previous field is unmatched. Don't display it, but let it
  1233. * remain for reference if marked as such. */
  1234. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  1235. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  1236. last_pic_structure == PICT_TOP_FIELD);
  1237. }
  1238. } else {
  1239. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  1240. /* This and previous field were reference, but had
  1241. * different frame_nums. Consider this field first in
  1242. * pair. Throw away previous field except for reference
  1243. * purposes. */
  1244. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  1245. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  1246. last_pic_structure == PICT_TOP_FIELD);
  1247. }
  1248. } else {
  1249. /* Second field in complementary pair */
  1250. if (!((last_pic_structure == PICT_TOP_FIELD &&
  1251. h->picture_structure == PICT_BOTTOM_FIELD) ||
  1252. (last_pic_structure == PICT_BOTTOM_FIELD &&
  1253. h->picture_structure == PICT_TOP_FIELD))) {
  1254. av_log(h->avctx, AV_LOG_ERROR,
  1255. "Invalid field mode combination %d/%d\n",
  1256. last_pic_structure, h->picture_structure);
  1257. h->picture_structure = last_pic_structure;
  1258. h->droppable = last_pic_droppable;
  1259. return AVERROR_INVALIDDATA;
  1260. } else if (last_pic_droppable != h->droppable) {
  1261. avpriv_request_sample(h->avctx,
  1262. "Found reference and non-reference fields in the same frame, which");
  1263. h->picture_structure = last_pic_structure;
  1264. h->droppable = last_pic_droppable;
  1265. return AVERROR_PATCHWELCOME;
  1266. }
  1267. }
  1268. }
  1269. }
  1270. while (h->frame_num != h->prev_frame_num &&
  1271. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  1272. H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  1273. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  1274. h->frame_num, h->prev_frame_num);
  1275. ret = h264_frame_start(h);
  1276. if (ret < 0) {
  1277. h0->first_field = 0;
  1278. return ret;
  1279. }
  1280. h->prev_frame_num++;
  1281. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  1282. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  1283. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  1284. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  1285. ret = ff_generate_sliding_window_mmcos(h, 1);
  1286. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1287. return ret;
  1288. ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1289. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1290. return ret;
  1291. /* Error concealment: If a ref is missing, copy the previous ref
  1292. * in its place.
  1293. * FIXME: Avoiding a memcpy would be nice, but ref handling makes
  1294. * many assumptions about there being no actual duplicates.
  1295. * FIXME: This does not copy padding for out-of-frame motion
  1296. * vectors. Given we are concealing a lost frame, this probably
  1297. * is not noticeable by comparison, but it should be fixed. */
  1298. if (h->short_ref_count) {
  1299. if (prev) {
  1300. av_image_copy(h->short_ref[0]->f.data,
  1301. h->short_ref[0]->f.linesize,
  1302. (const uint8_t **)prev->f.data,
  1303. prev->f.linesize,
  1304. h->avctx->pix_fmt,
  1305. h->mb_width * 16,
  1306. h->mb_height * 16);
  1307. h->short_ref[0]->poc = prev->poc + 2;
  1308. }
  1309. h->short_ref[0]->frame_num = h->prev_frame_num;
  1310. }
  1311. }
  1312. /* See if we have a decoded first field looking for a pair...
  1313. * We're using that to see whether to continue decoding in that
  1314. * frame, or to allocate a new one. */
  1315. if (h0->first_field) {
  1316. assert(h0->cur_pic_ptr);
  1317. assert(h0->cur_pic_ptr->f.buf[0]);
  1318. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1319. /* figure out if we have a complementary field pair */
  1320. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1321. /* Previous field is unmatched. Don't display it, but let it
  1322. * remain for reference if marked as such. */
  1323. h0->cur_pic_ptr = NULL;
  1324. h0->first_field = FIELD_PICTURE(h);
  1325. } else {
  1326. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  1327. /* This and the previous field had different frame_nums.
  1328. * Consider this field first in pair. Throw away previous
  1329. * one except for reference purposes. */
  1330. h0->first_field = 1;
  1331. h0->cur_pic_ptr = NULL;
  1332. } else {
  1333. /* Second field in complementary pair */
  1334. h0->first_field = 0;
  1335. }
  1336. }
  1337. } else {
  1338. /* Frame or first field in a potentially complementary pair */
  1339. h0->first_field = FIELD_PICTURE(h);
  1340. }
  1341. if (!FIELD_PICTURE(h) || h0->first_field) {
  1342. if (h264_frame_start(h) < 0) {
  1343. h0->first_field = 0;
  1344. return AVERROR_INVALIDDATA;
  1345. }
  1346. } else {
  1347. release_unused_pictures(h, 0);
  1348. }
  1349. }
  1350. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  1351. return ret;
  1352. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  1353. assert(h->mb_num == h->mb_width * h->mb_height);
  1354. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
  1355. first_mb_in_slice >= h->mb_num) {
  1356. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  1357. return AVERROR_INVALIDDATA;
  1358. }
  1359. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  1360. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
  1361. FIELD_OR_MBAFF_PICTURE(h);
  1362. if (h->picture_structure == PICT_BOTTOM_FIELD)
  1363. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  1364. assert(h->mb_y < h->mb_height);
  1365. if (h->picture_structure == PICT_FRAME) {
  1366. h->curr_pic_num = h->frame_num;
  1367. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  1368. } else {
  1369. h->curr_pic_num = 2 * h->frame_num + 1;
  1370. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  1371. }
  1372. if (h->nal_unit_type == NAL_IDR_SLICE)
  1373. get_ue_golomb(&h->gb); /* idr_pic_id */
  1374. if (h->sps.poc_type == 0) {
  1375. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  1376. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  1377. h->delta_poc_bottom = get_se_golomb(&h->gb);
  1378. }
  1379. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  1380. h->delta_poc[0] = get_se_golomb(&h->gb);
  1381. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  1382. h->delta_poc[1] = get_se_golomb(&h->gb);
  1383. }
  1384. ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
  1385. if (h->pps.redundant_pic_cnt_present)
  1386. h->redundant_pic_count = get_ue_golomb(&h->gb);
  1387. ret = ff_set_ref_count(h, sl);
  1388. if (ret < 0)
  1389. return ret;
  1390. else if (ret == 1)
  1391. default_ref_list_done = 0;
  1392. if (!default_ref_list_done)
  1393. ff_h264_fill_default_ref_list(h, sl);
  1394. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1395. ret = ff_h264_decode_ref_pic_list_reordering(h, sl);
  1396. if (ret < 0) {
  1397. sl->ref_count[1] = sl->ref_count[0] = 0;
  1398. return ret;
  1399. }
  1400. }
  1401. if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
  1402. (h->pps.weighted_bipred_idc == 1 &&
  1403. sl->slice_type_nos == AV_PICTURE_TYPE_B))
  1404. ff_pred_weight_table(h, sl);
  1405. else if (h->pps.weighted_bipred_idc == 2 &&
  1406. sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1407. implicit_weight_table(h, sl, -1);
  1408. } else {
  1409. sl->use_weight = 0;
  1410. for (i = 0; i < 2; i++) {
  1411. sl->luma_weight_flag[i] = 0;
  1412. sl->chroma_weight_flag[i] = 0;
  1413. }
  1414. }
  1415. // If frame-mt is enabled, only update mmco tables for the first slice
  1416. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  1417. // or h->mmco, which will cause ref list mix-ups and decoding errors
  1418. // further down the line. This may break decoding if the first slice is
  1419. // corrupt, thus we only do this if frame-mt is enabled.
  1420. if (h->nal_ref_idc) {
  1421. ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
  1422. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  1423. h0->current_slice == 0);
  1424. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1425. return AVERROR_INVALIDDATA;
  1426. }
  1427. if (FRAME_MBAFF(h)) {
  1428. ff_h264_fill_mbaff_ref_list(h, sl);
  1429. if (h->pps.weighted_bipred_idc == 2 && sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1430. implicit_weight_table(h, sl, 0);
  1431. implicit_weight_table(h, sl, 1);
  1432. }
  1433. }
  1434. if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
  1435. ff_h264_direct_dist_scale_factor(h, sl);
  1436. ff_h264_direct_ref_list_init(h, sl);
  1437. if (sl->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  1438. tmp = get_ue_golomb_31(&h->gb);
  1439. if (tmp > 2) {
  1440. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
  1441. return AVERROR_INVALIDDATA;
  1442. }
  1443. sl->cabac_init_idc = tmp;
  1444. }
  1445. sl->last_qscale_diff = 0;
  1446. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  1447. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  1448. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  1449. return AVERROR_INVALIDDATA;
  1450. }
  1451. sl->qscale = tmp;
  1452. sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
  1453. sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
  1454. // FIXME qscale / qp ... stuff
  1455. if (sl->slice_type == AV_PICTURE_TYPE_SP)
  1456. get_bits1(&h->gb); /* sp_for_switch_flag */
  1457. if (sl->slice_type == AV_PICTURE_TYPE_SP ||
  1458. sl->slice_type == AV_PICTURE_TYPE_SI)
  1459. get_se_golomb(&h->gb); /* slice_qs_delta */
  1460. sl->deblocking_filter = 1;
  1461. sl->slice_alpha_c0_offset = 0;
  1462. sl->slice_beta_offset = 0;
  1463. if (h->pps.deblocking_filter_parameters_present) {
  1464. tmp = get_ue_golomb_31(&h->gb);
  1465. if (tmp > 2) {
  1466. av_log(h->avctx, AV_LOG_ERROR,
  1467. "deblocking_filter_idc %u out of range\n", tmp);
  1468. return AVERROR_INVALIDDATA;
  1469. }
  1470. sl->deblocking_filter = tmp;
  1471. if (sl->deblocking_filter < 2)
  1472. sl->deblocking_filter ^= 1; // 1<->0
  1473. if (sl->deblocking_filter) {
  1474. sl->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
  1475. sl->slice_beta_offset = get_se_golomb(&h->gb) * 2;
  1476. if (sl->slice_alpha_c0_offset > 12 ||
  1477. sl->slice_alpha_c0_offset < -12 ||
  1478. sl->slice_beta_offset > 12 ||
  1479. sl->slice_beta_offset < -12) {
  1480. av_log(h->avctx, AV_LOG_ERROR,
  1481. "deblocking filter parameters %d %d out of range\n",
  1482. sl->slice_alpha_c0_offset, sl->slice_beta_offset);
  1483. return AVERROR_INVALIDDATA;
  1484. }
  1485. }
  1486. }
  1487. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  1488. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  1489. sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
  1490. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  1491. sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
  1492. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  1493. h->nal_ref_idc == 0))
  1494. sl->deblocking_filter = 0;
  1495. if (sl->deblocking_filter == 1 && h0->max_contexts > 1) {
  1496. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  1497. /* Cheat slightly for speed:
  1498. * Do not bother to deblock across slices. */
  1499. sl->deblocking_filter = 2;
  1500. } else {
  1501. h0->max_contexts = 1;
  1502. if (!h0->single_decode_warning) {
  1503. av_log(h->avctx, AV_LOG_INFO,
  1504. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  1505. h0->single_decode_warning = 1;
  1506. }
  1507. if (h != h0) {
  1508. av_log(h->avctx, AV_LOG_ERROR,
  1509. "Deblocking switched inside frame.\n");
  1510. return 1;
  1511. }
  1512. }
  1513. }
  1514. sl->qp_thresh = 15 -
  1515. FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
  1516. FFMAX3(0,
  1517. h->pps.chroma_qp_index_offset[0],
  1518. h->pps.chroma_qp_index_offset[1]) +
  1519. 6 * (h->sps.bit_depth_luma - 8);
  1520. h0->last_slice_type = slice_type;
  1521. sl->slice_num = ++h0->current_slice;
  1522. if (sl->slice_num >= MAX_SLICES) {
  1523. av_log(h->avctx, AV_LOG_ERROR,
  1524. "Too many slices, increase MAX_SLICES and recompile\n");
  1525. }
  1526. for (j = 0; j < 2; j++) {
  1527. int id_list[16];
  1528. int *ref2frm = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
  1529. for (i = 0; i < 16; i++) {
  1530. id_list[i] = 60;
  1531. if (j < sl->list_count && i < sl->ref_count[j] &&
  1532. sl->ref_list[j][i].f.buf[0]) {
  1533. int k;
  1534. AVBuffer *buf = sl->ref_list[j][i].f.buf[0]->buffer;
  1535. for (k = 0; k < h->short_ref_count; k++)
  1536. if (h->short_ref[k]->f.buf[0]->buffer == buf) {
  1537. id_list[i] = k;
  1538. break;
  1539. }
  1540. for (k = 0; k < h->long_ref_count; k++)
  1541. if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
  1542. id_list[i] = h->short_ref_count + k;
  1543. break;
  1544. }
  1545. }
  1546. }
  1547. ref2frm[0] =
  1548. ref2frm[1] = -1;
  1549. for (i = 0; i < 16; i++)
  1550. ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
  1551. ref2frm[18 + 0] =
  1552. ref2frm[18 + 1] = -1;
  1553. for (i = 16; i < 48; i++)
  1554. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  1555. (sl->ref_list[j][i].reference & 3);
  1556. }
  1557. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  1558. av_log(h->avctx, AV_LOG_DEBUG,
  1559. "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",
  1560. sl->slice_num,
  1561. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  1562. first_mb_in_slice,
  1563. av_get_picture_type_char(sl->slice_type),
  1564. sl->slice_type_fixed ? " fix" : "",
  1565. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  1566. pps_id, h->frame_num,
  1567. h->cur_pic_ptr->field_poc[0],
  1568. h->cur_pic_ptr->field_poc[1],
  1569. sl->ref_count[0], sl->ref_count[1],
  1570. sl->qscale,
  1571. sl->deblocking_filter,
  1572. sl->slice_alpha_c0_offset, sl->slice_beta_offset,
  1573. sl->use_weight,
  1574. sl->use_weight == 1 && sl->use_weight_chroma ? "c" : "",
  1575. sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  1576. }
  1577. return 0;
  1578. }
  1579. int ff_h264_get_slice_type(const H264SliceContext *sl)
  1580. {
  1581. switch (sl->slice_type) {
  1582. case AV_PICTURE_TYPE_P:
  1583. return 0;
  1584. case AV_PICTURE_TYPE_B:
  1585. return 1;
  1586. case AV_PICTURE_TYPE_I:
  1587. return 2;
  1588. case AV_PICTURE_TYPE_SP:
  1589. return 3;
  1590. case AV_PICTURE_TYPE_SI:
  1591. return 4;
  1592. default:
  1593. return AVERROR_INVALIDDATA;
  1594. }
  1595. }
  1596. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  1597. H264SliceContext *sl,
  1598. int mb_type, int top_xy,
  1599. int left_xy[LEFT_MBS],
  1600. int top_type,
  1601. int left_type[LEFT_MBS],
  1602. int mb_xy, int list)
  1603. {
  1604. int b_stride = h->b_stride;
  1605. int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
  1606. int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
  1607. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  1608. if (USES_LIST(top_type, list)) {
  1609. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  1610. const int b8_xy = 4 * top_xy + 2;
  1611. int (*ref2frm)[64] = sl->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
  1612. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
  1613. ref_cache[0 - 1 * 8] =
  1614. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
  1615. ref_cache[2 - 1 * 8] =
  1616. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
  1617. } else {
  1618. AV_ZERO128(mv_dst - 1 * 8);
  1619. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1620. }
  1621. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  1622. if (USES_LIST(left_type[LTOP], list)) {
  1623. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  1624. const int b8_xy = 4 * left_xy[LTOP] + 1;
  1625. int (*ref2frm)[64] = sl->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
  1626. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
  1627. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
  1628. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
  1629. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
  1630. ref_cache[-1 + 0] =
  1631. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
  1632. ref_cache[-1 + 16] =
  1633. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
  1634. } else {
  1635. AV_ZERO32(mv_dst - 1 + 0);
  1636. AV_ZERO32(mv_dst - 1 + 8);
  1637. AV_ZERO32(mv_dst - 1 + 16);
  1638. AV_ZERO32(mv_dst - 1 + 24);
  1639. ref_cache[-1 + 0] =
  1640. ref_cache[-1 + 8] =
  1641. ref_cache[-1 + 16] =
  1642. ref_cache[-1 + 24] = LIST_NOT_USED;
  1643. }
  1644. }
  1645. }
  1646. if (!USES_LIST(mb_type, list)) {
  1647. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  1648. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1649. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1650. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1651. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1652. return;
  1653. }
  1654. {
  1655. int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
  1656. int (*ref2frm)[64] = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
  1657. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  1658. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  1659. AV_WN32A(&ref_cache[0 * 8], ref01);
  1660. AV_WN32A(&ref_cache[1 * 8], ref01);
  1661. AV_WN32A(&ref_cache[2 * 8], ref23);
  1662. AV_WN32A(&ref_cache[3 * 8], ref23);
  1663. }
  1664. {
  1665. int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  1666. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  1667. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  1668. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  1669. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  1670. }
  1671. }
  1672. /**
  1673. *
  1674. * @return non zero if the loop filter can be skipped
  1675. */
  1676. static int fill_filter_caches(H264Context *h, H264SliceContext *sl, int mb_type)
  1677. {
  1678. const int mb_xy = h->mb_xy;
  1679. int top_xy, left_xy[LEFT_MBS];
  1680. int top_type, left_type[LEFT_MBS];
  1681. uint8_t *nnz;
  1682. uint8_t *nnz_cache;
  1683. top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
  1684. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  1685. * stuff, I can't imagine that these complex rules are worth it. */
  1686. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  1687. if (FRAME_MBAFF(h)) {
  1688. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
  1689. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  1690. if (h->mb_y & 1) {
  1691. if (left_mb_field_flag != curr_mb_field_flag)
  1692. left_xy[LTOP] -= h->mb_stride;
  1693. } else {
  1694. if (curr_mb_field_flag)
  1695. top_xy += h->mb_stride &
  1696. (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
  1697. if (left_mb_field_flag != curr_mb_field_flag)
  1698. left_xy[LBOT] += h->mb_stride;
  1699. }
  1700. }
  1701. sl->top_mb_xy = top_xy;
  1702. sl->left_mb_xy[LTOP] = left_xy[LTOP];
  1703. sl->left_mb_xy[LBOT] = left_xy[LBOT];
  1704. {
  1705. /* For sufficiently low qp, filtering wouldn't do anything.
  1706. * This is a conservative estimate: could also check beta_offset
  1707. * and more accurate chroma_qp. */
  1708. int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  1709. int qp = h->cur_pic.qscale_table[mb_xy];
  1710. if (qp <= qp_thresh &&
  1711. (left_xy[LTOP] < 0 ||
  1712. ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  1713. (top_xy < 0 ||
  1714. ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  1715. if (!FRAME_MBAFF(h))
  1716. return 1;
  1717. if ((left_xy[LTOP] < 0 ||
  1718. ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  1719. (top_xy < h->mb_stride ||
  1720. ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  1721. return 1;
  1722. }
  1723. }
  1724. top_type = h->cur_pic.mb_type[top_xy];
  1725. left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
  1726. left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
  1727. if (sl->deblocking_filter == 2) {
  1728. if (h->slice_table[top_xy] != sl->slice_num)
  1729. top_type = 0;
  1730. if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
  1731. left_type[LTOP] = left_type[LBOT] = 0;
  1732. } else {
  1733. if (h->slice_table[top_xy] == 0xFFFF)
  1734. top_type = 0;
  1735. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  1736. left_type[LTOP] = left_type[LBOT] = 0;
  1737. }
  1738. sl->top_type = top_type;
  1739. sl->left_type[LTOP] = left_type[LTOP];
  1740. sl->left_type[LBOT] = left_type[LBOT];
  1741. if (IS_INTRA(mb_type))
  1742. return 0;
  1743. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  1744. top_type, left_type, mb_xy, 0);
  1745. if (sl->list_count == 2)
  1746. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  1747. top_type, left_type, mb_xy, 1);
  1748. nnz = h->non_zero_count[mb_xy];
  1749. nnz_cache = sl->non_zero_count_cache;
  1750. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  1751. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  1752. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  1753. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  1754. sl->cbp = h->cbp_table[mb_xy];
  1755. if (top_type) {
  1756. nnz = h->non_zero_count[top_xy];
  1757. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  1758. }
  1759. if (left_type[LTOP]) {
  1760. nnz = h->non_zero_count[left_xy[LTOP]];
  1761. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  1762. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  1763. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  1764. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  1765. }
  1766. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  1767. * from what the loop filter needs */
  1768. if (!CABAC(h) && h->pps.transform_8x8_mode) {
  1769. if (IS_8x8DCT(top_type)) {
  1770. nnz_cache[4 + 8 * 0] =
  1771. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  1772. nnz_cache[6 + 8 * 0] =
  1773. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  1774. }
  1775. if (IS_8x8DCT(left_type[LTOP])) {
  1776. nnz_cache[3 + 8 * 1] =
  1777. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  1778. }
  1779. if (IS_8x8DCT(left_type[LBOT])) {
  1780. nnz_cache[3 + 8 * 3] =
  1781. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  1782. }
  1783. if (IS_8x8DCT(mb_type)) {
  1784. nnz_cache[scan8[0]] =
  1785. nnz_cache[scan8[1]] =
  1786. nnz_cache[scan8[2]] =
  1787. nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
  1788. nnz_cache[scan8[0 + 4]] =
  1789. nnz_cache[scan8[1 + 4]] =
  1790. nnz_cache[scan8[2 + 4]] =
  1791. nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
  1792. nnz_cache[scan8[0 + 8]] =
  1793. nnz_cache[scan8[1 + 8]] =
  1794. nnz_cache[scan8[2 + 8]] =
  1795. nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
  1796. nnz_cache[scan8[0 + 12]] =
  1797. nnz_cache[scan8[1 + 12]] =
  1798. nnz_cache[scan8[2 + 12]] =
  1799. nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
  1800. }
  1801. }
  1802. return 0;
  1803. }
  1804. static void loop_filter(H264Context *h, H264SliceContext *sl, int start_x, int end_x)
  1805. {
  1806. uint8_t *dest_y, *dest_cb, *dest_cr;
  1807. int linesize, uvlinesize, mb_x, mb_y;
  1808. const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
  1809. const int old_slice_type = sl->slice_type;
  1810. const int pixel_shift = h->pixel_shift;
  1811. const int block_h = 16 >> h->chroma_y_shift;
  1812. if (sl->deblocking_filter) {
  1813. for (mb_x = start_x; mb_x < end_x; mb_x++)
  1814. for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
  1815. int mb_xy, mb_type;
  1816. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  1817. sl->slice_num = h->slice_table[mb_xy];
  1818. mb_type = h->cur_pic.mb_type[mb_xy];
  1819. sl->list_count = h->list_counts[mb_xy];
  1820. if (FRAME_MBAFF(h))
  1821. h->mb_mbaff =
  1822. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  1823. h->mb_x = mb_x;
  1824. h->mb_y = mb_y;
  1825. dest_y = h->cur_pic.f.data[0] +
  1826. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  1827. dest_cb = h->cur_pic.f.data[1] +
  1828. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  1829. mb_y * h->uvlinesize * block_h;
  1830. dest_cr = h->cur_pic.f.data[2] +
  1831. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  1832. mb_y * h->uvlinesize * block_h;
  1833. // FIXME simplify above
  1834. if (MB_FIELD(h)) {
  1835. linesize = sl->mb_linesize = h->linesize * 2;
  1836. uvlinesize = sl->mb_uvlinesize = h->uvlinesize * 2;
  1837. if (mb_y & 1) { // FIXME move out of this function?
  1838. dest_y -= h->linesize * 15;
  1839. dest_cb -= h->uvlinesize * (block_h - 1);
  1840. dest_cr -= h->uvlinesize * (block_h - 1);
  1841. }
  1842. } else {
  1843. linesize = sl->mb_linesize = h->linesize;
  1844. uvlinesize = sl->mb_uvlinesize = h->uvlinesize;
  1845. }
  1846. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  1847. uvlinesize, 0);
  1848. if (fill_filter_caches(h, sl, mb_type))
  1849. continue;
  1850. sl->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
  1851. sl->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
  1852. if (FRAME_MBAFF(h)) {
  1853. ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  1854. linesize, uvlinesize);
  1855. } else {
  1856. ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
  1857. dest_cr, linesize, uvlinesize);
  1858. }
  1859. }
  1860. }
  1861. sl->slice_type = old_slice_type;
  1862. h->mb_x = end_x;
  1863. h->mb_y = end_mb_y - FRAME_MBAFF(h);
  1864. sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
  1865. sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
  1866. }
  1867. static void predict_field_decoding_flag(H264Context *h, H264SliceContext *sl)
  1868. {
  1869. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  1870. int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
  1871. h->cur_pic.mb_type[mb_xy - 1] :
  1872. (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
  1873. h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
  1874. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  1875. }
  1876. /**
  1877. * Draw edges and report progress for the last MB row.
  1878. */
  1879. static void decode_finish_row(H264Context *h, H264SliceContext *sl)
  1880. {
  1881. int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
  1882. int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
  1883. int height = 16 << FRAME_MBAFF(h);
  1884. int deblock_border = (16 + 4) << FRAME_MBAFF(h);
  1885. if (sl->deblocking_filter) {
  1886. if ((top + height) >= pic_height)
  1887. height += deblock_border;
  1888. top -= deblock_border;
  1889. }
  1890. if (top >= pic_height || (top + height) < 0)
  1891. return;
  1892. height = FFMIN(height, pic_height - top);
  1893. if (top < 0) {
  1894. height = top + height;
  1895. top = 0;
  1896. }
  1897. ff_h264_draw_horiz_band(h, sl, top, height);
  1898. if (h->droppable)
  1899. return;
  1900. ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
  1901. h->picture_structure == PICT_BOTTOM_FIELD);
  1902. }
  1903. static void er_add_slice(H264Context *h, H264SliceContext *sl,
  1904. int startx, int starty,
  1905. int endx, int endy, int status)
  1906. {
  1907. #if CONFIG_ERROR_RESILIENCE
  1908. ERContext *er = &h->er;
  1909. er->ref_count = sl->ref_count[0];
  1910. ff_er_add_slice(er, startx, starty, endx, endy, status);
  1911. #endif
  1912. }
  1913. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  1914. {
  1915. H264SliceContext *sl = arg;
  1916. H264Context *h = sl->h264;
  1917. int lf_x_start = h->mb_x;
  1918. h->mb_skip_run = -1;
  1919. h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
  1920. avctx->codec_id != AV_CODEC_ID_H264 ||
  1921. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  1922. if (h->pps.cabac) {
  1923. /* realign */
  1924. align_get_bits(&h->gb);
  1925. /* init cabac */
  1926. ff_init_cabac_decoder(&sl->cabac,
  1927. h->gb.buffer + get_bits_count(&h->gb) / 8,
  1928. (get_bits_left(&h->gb) + 7) / 8);
  1929. ff_h264_init_cabac_states(h, sl);
  1930. for (;;) {
  1931. // START_TIMER
  1932. int ret = ff_h264_decode_mb_cabac(h, sl);
  1933. int eos;
  1934. // STOP_TIMER("decode_mb_cabac")
  1935. if (ret >= 0)
  1936. ff_h264_hl_decode_mb(h, sl);
  1937. // FIXME optimal? or let mb_decode decode 16x32 ?
  1938. if (ret >= 0 && FRAME_MBAFF(h)) {
  1939. h->mb_y++;
  1940. ret = ff_h264_decode_mb_cabac(h, sl);
  1941. if (ret >= 0)
  1942. ff_h264_hl_decode_mb(h, sl);
  1943. h->mb_y--;
  1944. }
  1945. eos = get_cabac_terminate(&sl->cabac);
  1946. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  1947. sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
  1948. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  1949. h->mb_y, ER_MB_END);
  1950. if (h->mb_x >= lf_x_start)
  1951. loop_filter(h, sl, lf_x_start, h->mb_x + 1);
  1952. return 0;
  1953. }
  1954. if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
  1955. av_log(h->avctx, AV_LOG_ERROR,
  1956. "error while decoding MB %d %d, bytestream %td\n",
  1957. h->mb_x, h->mb_y,
  1958. sl->cabac.bytestream_end - sl->cabac.bytestream);
  1959. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  1960. h->mb_y, ER_MB_ERROR);
  1961. return AVERROR_INVALIDDATA;
  1962. }
  1963. if (++h->mb_x >= h->mb_width) {
  1964. loop_filter(h, sl, lf_x_start, h->mb_x);
  1965. h->mb_x = lf_x_start = 0;
  1966. decode_finish_row(h, sl);
  1967. ++h->mb_y;
  1968. if (FIELD_OR_MBAFF_PICTURE(h)) {
  1969. ++h->mb_y;
  1970. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  1971. predict_field_decoding_flag(h, sl);
  1972. }
  1973. }
  1974. if (eos || h->mb_y >= h->mb_height) {
  1975. tprintf(h->avctx, "slice end %d %d\n",
  1976. get_bits_count(&h->gb), h->gb.size_in_bits);
  1977. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  1978. h->mb_y, ER_MB_END);
  1979. if (h->mb_x > lf_x_start)
  1980. loop_filter(h, sl, lf_x_start, h->mb_x);
  1981. return 0;
  1982. }
  1983. }
  1984. } else {
  1985. for (;;) {
  1986. int ret = ff_h264_decode_mb_cavlc(h, sl);
  1987. if (ret >= 0)
  1988. ff_h264_hl_decode_mb(h, sl);
  1989. // FIXME optimal? or let mb_decode decode 16x32 ?
  1990. if (ret >= 0 && FRAME_MBAFF(h)) {
  1991. h->mb_y++;
  1992. ret = ff_h264_decode_mb_cavlc(h, sl);
  1993. if (ret >= 0)
  1994. ff_h264_hl_decode_mb(h, sl);
  1995. h->mb_y--;
  1996. }
  1997. if (ret < 0) {
  1998. av_log(h->avctx, AV_LOG_ERROR,
  1999. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  2000. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  2001. h->mb_y, ER_MB_ERROR);
  2002. return ret;
  2003. }
  2004. if (++h->mb_x >= h->mb_width) {
  2005. loop_filter(h, sl, lf_x_start, h->mb_x);
  2006. h->mb_x = lf_x_start = 0;
  2007. decode_finish_row(h, sl);
  2008. ++h->mb_y;
  2009. if (FIELD_OR_MBAFF_PICTURE(h)) {
  2010. ++h->mb_y;
  2011. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  2012. predict_field_decoding_flag(h, sl);
  2013. }
  2014. if (h->mb_y >= h->mb_height) {
  2015. tprintf(h->avctx, "slice end %d %d\n",
  2016. get_bits_count(&h->gb), h->gb.size_in_bits);
  2017. if (get_bits_left(&h->gb) == 0) {
  2018. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y,
  2019. h->mb_x - 1, h->mb_y, ER_MB_END);
  2020. return 0;
  2021. } else {
  2022. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y,
  2023. h->mb_x - 1, h->mb_y, ER_MB_END);
  2024. return AVERROR_INVALIDDATA;
  2025. }
  2026. }
  2027. }
  2028. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  2029. tprintf(h->avctx, "slice end %d %d\n",
  2030. get_bits_count(&h->gb), h->gb.size_in_bits);
  2031. if (get_bits_left(&h->gb) == 0) {
  2032. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y,
  2033. h->mb_x - 1, h->mb_y, ER_MB_END);
  2034. if (h->mb_x > lf_x_start)
  2035. loop_filter(h, sl, lf_x_start, h->mb_x);
  2036. return 0;
  2037. } else {
  2038. er_add_slice(h, sl, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  2039. h->mb_y, ER_MB_ERROR);
  2040. return AVERROR_INVALIDDATA;
  2041. }
  2042. }
  2043. }
  2044. }
  2045. }
  2046. /**
  2047. * Call decode_slice() for each context.
  2048. *
  2049. * @param h h264 master context
  2050. * @param context_count number of contexts to execute
  2051. */
  2052. int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
  2053. {
  2054. AVCodecContext *const avctx = h->avctx;
  2055. H264Context *hx;
  2056. int i;
  2057. if (h->avctx->hwaccel)
  2058. return 0;
  2059. if (context_count == 1) {
  2060. return decode_slice(avctx, &h->slice_ctx[0]);
  2061. } else {
  2062. for (i = 1; i < context_count; i++) {
  2063. hx = h->thread_context[i];
  2064. hx->er.error_count = 0;
  2065. }
  2066. avctx->execute(avctx, decode_slice, h->slice_ctx,
  2067. NULL, context_count, sizeof(h->slice_ctx[0]));
  2068. /* pull back stuff from slices to master context */
  2069. hx = h->thread_context[context_count - 1];
  2070. h->mb_x = hx->mb_x;
  2071. h->mb_y = hx->mb_y;
  2072. h->droppable = hx->droppable;
  2073. h->picture_structure = hx->picture_structure;
  2074. for (i = 1; i < context_count; i++)
  2075. h->er.error_count += h->thread_context[i]->er.error_count;
  2076. }
  2077. return 0;
  2078. }