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.

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