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.

4505 lines
172KB

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