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.

4514 lines
173KB

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