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.

451 lines
15KB

  1. /*
  2. * Copyright (c) 2018 Ronald S. Bultje <rsbultje gmail com>
  3. * Copyright (c) 2018 James Almer <jamrial gmail com>
  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. #include <dav1d/dav1d.h>
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/mastering_display_metadata.h"
  24. #include "libavutil/imgutils.h"
  25. #include "libavutil/opt.h"
  26. #include "atsc_a53.h"
  27. #include "avcodec.h"
  28. #include "bytestream.h"
  29. #include "decode.h"
  30. #include "internal.h"
  31. typedef struct Libdav1dContext {
  32. AVClass *class;
  33. Dav1dContext *c;
  34. AVBufferPool *pool;
  35. int pool_size;
  36. Dav1dData data;
  37. int tile_threads;
  38. int frame_threads;
  39. int apply_grain;
  40. int operating_point;
  41. int all_layers;
  42. } Libdav1dContext;
  43. static const enum AVPixelFormat pix_fmt[][3] = {
  44. [DAV1D_PIXEL_LAYOUT_I400] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12 },
  45. [DAV1D_PIXEL_LAYOUT_I420] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12 },
  46. [DAV1D_PIXEL_LAYOUT_I422] = { AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12 },
  47. [DAV1D_PIXEL_LAYOUT_I444] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12 },
  48. };
  49. static const enum AVPixelFormat pix_fmt_rgb[3] = {
  50. AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12,
  51. };
  52. static void libdav1d_log_callback(void *opaque, const char *fmt, va_list vl)
  53. {
  54. AVCodecContext *c = opaque;
  55. av_vlog(c, AV_LOG_ERROR, fmt, vl);
  56. }
  57. static int libdav1d_picture_allocator(Dav1dPicture *p, void *cookie)
  58. {
  59. Libdav1dContext *dav1d = cookie;
  60. enum AVPixelFormat format = pix_fmt[p->p.layout][p->seq_hdr->hbd];
  61. int ret, linesize[4], h = FFALIGN(p->p.h, 128), w = FFALIGN(p->p.w, 128);
  62. uint8_t *aligned_ptr, *data[4];
  63. AVBufferRef *buf;
  64. ret = av_image_get_buffer_size(format, w, h, DAV1D_PICTURE_ALIGNMENT);
  65. if (ret < 0)
  66. return ret;
  67. if (ret != dav1d->pool_size) {
  68. av_buffer_pool_uninit(&dav1d->pool);
  69. // Use twice the amount of required padding bytes for aligned_ptr below.
  70. dav1d->pool = av_buffer_pool_init(ret + DAV1D_PICTURE_ALIGNMENT * 2, NULL);
  71. if (!dav1d->pool) {
  72. dav1d->pool_size = 0;
  73. return AVERROR(ENOMEM);
  74. }
  75. dav1d->pool_size = ret;
  76. }
  77. buf = av_buffer_pool_get(dav1d->pool);
  78. if (!buf)
  79. return AVERROR(ENOMEM);
  80. // libdav1d requires DAV1D_PICTURE_ALIGNMENT aligned buffers, which av_malloc()
  81. // doesn't guarantee for example when AVX is disabled at configure time.
  82. // Use the extra DAV1D_PICTURE_ALIGNMENT padding bytes in the buffer to align it
  83. // if required.
  84. aligned_ptr = (uint8_t *)FFALIGN((uintptr_t)buf->data, DAV1D_PICTURE_ALIGNMENT);
  85. ret = av_image_fill_arrays(data, linesize, aligned_ptr, format, w, h,
  86. DAV1D_PICTURE_ALIGNMENT);
  87. if (ret < 0) {
  88. av_buffer_unref(&buf);
  89. return ret;
  90. }
  91. p->data[0] = data[0];
  92. p->data[1] = data[1];
  93. p->data[2] = data[2];
  94. p->stride[0] = linesize[0];
  95. p->stride[1] = linesize[1];
  96. p->allocator_data = buf;
  97. return 0;
  98. }
  99. static void libdav1d_picture_release(Dav1dPicture *p, void *cookie)
  100. {
  101. AVBufferRef *buf = p->allocator_data;
  102. av_buffer_unref(&buf);
  103. }
  104. static av_cold int libdav1d_init(AVCodecContext *c)
  105. {
  106. Libdav1dContext *dav1d = c->priv_data;
  107. Dav1dSettings s;
  108. int threads = (c->thread_count ? c->thread_count : av_cpu_count()) * 3 / 2;
  109. int res;
  110. av_log(c, AV_LOG_INFO, "libdav1d %s\n", dav1d_version());
  111. dav1d_default_settings(&s);
  112. s.logger.cookie = c;
  113. s.logger.callback = libdav1d_log_callback;
  114. s.allocator.cookie = dav1d;
  115. s.allocator.alloc_picture_callback = libdav1d_picture_allocator;
  116. s.allocator.release_picture_callback = libdav1d_picture_release;
  117. s.frame_size_limit = c->max_pixels;
  118. if (dav1d->apply_grain >= 0)
  119. s.apply_grain = dav1d->apply_grain;
  120. s.all_layers = dav1d->all_layers;
  121. if (dav1d->operating_point >= 0)
  122. s.operating_point = dav1d->operating_point;
  123. s.n_tile_threads = dav1d->tile_threads
  124. ? dav1d->tile_threads
  125. : FFMIN(floor(sqrt(threads)), DAV1D_MAX_TILE_THREADS);
  126. s.n_frame_threads = dav1d->frame_threads
  127. ? dav1d->frame_threads
  128. : FFMIN(ceil(threads / s.n_tile_threads), DAV1D_MAX_FRAME_THREADS);
  129. av_log(c, AV_LOG_DEBUG, "Using %d frame threads, %d tile threads\n",
  130. s.n_frame_threads, s.n_tile_threads);
  131. res = dav1d_open(&dav1d->c, &s);
  132. if (res < 0)
  133. return AVERROR(ENOMEM);
  134. return 0;
  135. }
  136. static void libdav1d_flush(AVCodecContext *c)
  137. {
  138. Libdav1dContext *dav1d = c->priv_data;
  139. dav1d_data_unref(&dav1d->data);
  140. dav1d_flush(dav1d->c);
  141. }
  142. static void libdav1d_data_free(const uint8_t *data, void *opaque) {
  143. AVBufferRef *buf = opaque;
  144. av_buffer_unref(&buf);
  145. }
  146. static void libdav1d_user_data_free(const uint8_t *data, void *opaque) {
  147. av_assert0(data == opaque);
  148. av_free(opaque);
  149. }
  150. static int libdav1d_receive_frame(AVCodecContext *c, AVFrame *frame)
  151. {
  152. Libdav1dContext *dav1d = c->priv_data;
  153. Dav1dData *data = &dav1d->data;
  154. Dav1dPicture pic = { 0 }, *p = &pic;
  155. int res;
  156. if (!data->sz) {
  157. AVPacket pkt = { 0 };
  158. res = ff_decode_get_packet(c, &pkt);
  159. if (res < 0 && res != AVERROR_EOF)
  160. return res;
  161. if (pkt.size) {
  162. res = dav1d_data_wrap(data, pkt.data, pkt.size, libdav1d_data_free, pkt.buf);
  163. if (res < 0) {
  164. av_packet_unref(&pkt);
  165. return res;
  166. }
  167. data->m.timestamp = pkt.pts;
  168. data->m.offset = pkt.pos;
  169. data->m.duration = pkt.duration;
  170. pkt.buf = NULL;
  171. av_packet_unref(&pkt);
  172. if (c->reordered_opaque != AV_NOPTS_VALUE) {
  173. uint8_t *reordered_opaque = av_malloc(sizeof(c->reordered_opaque));
  174. if (!reordered_opaque) {
  175. dav1d_data_unref(data);
  176. return AVERROR(ENOMEM);
  177. }
  178. memcpy(reordered_opaque, &c->reordered_opaque, sizeof(c->reordered_opaque));
  179. res = dav1d_data_wrap_user_data(data, reordered_opaque,
  180. libdav1d_user_data_free, reordered_opaque);
  181. if (res < 0) {
  182. av_free(reordered_opaque);
  183. dav1d_data_unref(data);
  184. return res;
  185. }
  186. }
  187. }
  188. }
  189. res = dav1d_send_data(dav1d->c, data);
  190. if (res < 0) {
  191. if (res == AVERROR(EINVAL))
  192. res = AVERROR_INVALIDDATA;
  193. if (res != AVERROR(EAGAIN))
  194. return res;
  195. }
  196. res = dav1d_get_picture(dav1d->c, p);
  197. if (res < 0) {
  198. if (res == AVERROR(EINVAL))
  199. res = AVERROR_INVALIDDATA;
  200. else if (res == AVERROR(EAGAIN) && c->internal->draining)
  201. res = AVERROR_EOF;
  202. return res;
  203. }
  204. av_assert0(p->data[0] && p->allocator_data);
  205. // This requires the custom allocator above
  206. frame->buf[0] = av_buffer_ref(p->allocator_data);
  207. if (!frame->buf[0]) {
  208. dav1d_picture_unref(p);
  209. return AVERROR(ENOMEM);
  210. }
  211. frame->data[0] = p->data[0];
  212. frame->data[1] = p->data[1];
  213. frame->data[2] = p->data[2];
  214. frame->linesize[0] = p->stride[0];
  215. frame->linesize[1] = p->stride[1];
  216. frame->linesize[2] = p->stride[1];
  217. c->profile = p->seq_hdr->profile;
  218. c->level = ((p->seq_hdr->operating_points[0].major_level - 2) << 2)
  219. | p->seq_hdr->operating_points[0].minor_level;
  220. frame->width = p->p.w;
  221. frame->height = p->p.h;
  222. if (c->width != p->p.w || c->height != p->p.h) {
  223. res = ff_set_dimensions(c, p->p.w, p->p.h);
  224. if (res < 0)
  225. goto fail;
  226. }
  227. av_reduce(&frame->sample_aspect_ratio.num,
  228. &frame->sample_aspect_ratio.den,
  229. frame->height * (int64_t)p->frame_hdr->render_width,
  230. frame->width * (int64_t)p->frame_hdr->render_height,
  231. INT_MAX);
  232. ff_set_sar(c, frame->sample_aspect_ratio);
  233. switch (p->seq_hdr->chr) {
  234. case DAV1D_CHR_VERTICAL:
  235. frame->chroma_location = c->chroma_sample_location = AVCHROMA_LOC_LEFT;
  236. break;
  237. case DAV1D_CHR_COLOCATED:
  238. frame->chroma_location = c->chroma_sample_location = AVCHROMA_LOC_TOPLEFT;
  239. break;
  240. }
  241. frame->colorspace = c->colorspace = (enum AVColorSpace) p->seq_hdr->mtrx;
  242. frame->color_primaries = c->color_primaries = (enum AVColorPrimaries) p->seq_hdr->pri;
  243. frame->color_trc = c->color_trc = (enum AVColorTransferCharacteristic) p->seq_hdr->trc;
  244. frame->color_range = c->color_range = p->seq_hdr->color_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  245. if (p->p.layout == DAV1D_PIXEL_LAYOUT_I444 &&
  246. p->seq_hdr->mtrx == DAV1D_MC_IDENTITY &&
  247. p->seq_hdr->pri == DAV1D_COLOR_PRI_BT709 &&
  248. p->seq_hdr->trc == DAV1D_TRC_SRGB)
  249. frame->format = c->pix_fmt = pix_fmt_rgb[p->seq_hdr->hbd];
  250. else
  251. frame->format = c->pix_fmt = pix_fmt[p->p.layout][p->seq_hdr->hbd];
  252. if (p->m.user_data.data)
  253. memcpy(&frame->reordered_opaque, p->m.user_data.data, sizeof(frame->reordered_opaque));
  254. else
  255. frame->reordered_opaque = AV_NOPTS_VALUE;
  256. if (p->seq_hdr->num_units_in_tick && p->seq_hdr->time_scale) {
  257. av_reduce(&c->framerate.den, &c->framerate.num,
  258. p->seq_hdr->num_units_in_tick, p->seq_hdr->time_scale, INT_MAX);
  259. if (p->seq_hdr->equal_picture_interval)
  260. c->ticks_per_frame = p->seq_hdr->num_ticks_per_picture;
  261. }
  262. // match timestamps and packet size
  263. frame->pts = frame->best_effort_timestamp = p->m.timestamp;
  264. #if FF_API_PKT_PTS
  265. FF_DISABLE_DEPRECATION_WARNINGS
  266. frame->pkt_pts = p->m.timestamp;
  267. FF_ENABLE_DEPRECATION_WARNINGS
  268. #endif
  269. frame->pkt_dts = p->m.timestamp;
  270. frame->pkt_pos = p->m.offset;
  271. frame->pkt_size = p->m.size;
  272. frame->pkt_duration = p->m.duration;
  273. frame->key_frame = p->frame_hdr->frame_type == DAV1D_FRAME_TYPE_KEY;
  274. switch (p->frame_hdr->frame_type) {
  275. case DAV1D_FRAME_TYPE_KEY:
  276. case DAV1D_FRAME_TYPE_INTRA:
  277. frame->pict_type = AV_PICTURE_TYPE_I;
  278. break;
  279. case DAV1D_FRAME_TYPE_INTER:
  280. frame->pict_type = AV_PICTURE_TYPE_P;
  281. break;
  282. case DAV1D_FRAME_TYPE_SWITCH:
  283. frame->pict_type = AV_PICTURE_TYPE_SP;
  284. break;
  285. default:
  286. res = AVERROR_INVALIDDATA;
  287. goto fail;
  288. }
  289. if (p->mastering_display) {
  290. AVMasteringDisplayMetadata *mastering = av_mastering_display_metadata_create_side_data(frame);
  291. if (!mastering) {
  292. res = AVERROR(ENOMEM);
  293. goto fail;
  294. }
  295. for (int i = 0; i < 3; i++) {
  296. mastering->display_primaries[i][0] = av_make_q(p->mastering_display->primaries[i][0], 1 << 16);
  297. mastering->display_primaries[i][1] = av_make_q(p->mastering_display->primaries[i][1], 1 << 16);
  298. }
  299. mastering->white_point[0] = av_make_q(p->mastering_display->white_point[0], 1 << 16);
  300. mastering->white_point[1] = av_make_q(p->mastering_display->white_point[1], 1 << 16);
  301. mastering->max_luminance = av_make_q(p->mastering_display->max_luminance, 1 << 8);
  302. mastering->min_luminance = av_make_q(p->mastering_display->min_luminance, 1 << 14);
  303. mastering->has_primaries = 1;
  304. mastering->has_luminance = 1;
  305. }
  306. if (p->content_light) {
  307. AVContentLightMetadata *light = av_content_light_metadata_create_side_data(frame);
  308. if (!light) {
  309. res = AVERROR(ENOMEM);
  310. goto fail;
  311. }
  312. light->MaxCLL = p->content_light->max_content_light_level;
  313. light->MaxFALL = p->content_light->max_frame_average_light_level;
  314. }
  315. if (p->itut_t35) {
  316. GetByteContext gb;
  317. unsigned int user_identifier;
  318. bytestream2_init(&gb, p->itut_t35->payload, p->itut_t35->payload_size);
  319. bytestream2_skip(&gb, 1); // terminal provider code
  320. bytestream2_skip(&gb, 1); // terminal provider oriented code
  321. user_identifier = bytestream2_get_be32(&gb);
  322. switch (user_identifier) {
  323. case MKBETAG('G', 'A', '9', '4'): { // closed captions
  324. AVBufferRef *buf = NULL;
  325. res = ff_parse_a53_cc(&buf, gb.buffer, bytestream2_get_bytes_left(&gb));
  326. if (res < 0)
  327. goto fail;
  328. if (!res)
  329. break;
  330. if (!av_frame_new_side_data_from_buf(frame, AV_FRAME_DATA_A53_CC, buf))
  331. av_buffer_unref(&buf);
  332. c->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  333. break;
  334. }
  335. default: // ignore unsupported identifiers
  336. break;
  337. }
  338. }
  339. res = 0;
  340. fail:
  341. dav1d_picture_unref(p);
  342. if (res < 0)
  343. av_frame_unref(frame);
  344. return res;
  345. }
  346. static av_cold int libdav1d_close(AVCodecContext *c)
  347. {
  348. Libdav1dContext *dav1d = c->priv_data;
  349. av_buffer_pool_uninit(&dav1d->pool);
  350. dav1d_data_unref(&dav1d->data);
  351. dav1d_close(&dav1d->c);
  352. return 0;
  353. }
  354. #define OFFSET(x) offsetof(Libdav1dContext, x)
  355. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  356. static const AVOption libdav1d_options[] = {
  357. { "tilethreads", "Tile threads", OFFSET(tile_threads), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, DAV1D_MAX_TILE_THREADS, VD },
  358. { "framethreads", "Frame threads", OFFSET(frame_threads), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, DAV1D_MAX_FRAME_THREADS, VD },
  359. { "filmgrain", "Apply Film Grain", OFFSET(apply_grain), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  360. { "oppoint", "Select an operating point of the scalable bitstream", OFFSET(operating_point), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 31, VD },
  361. { "alllayers", "Output all spatial layers", OFFSET(all_layers), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  362. { NULL }
  363. };
  364. static const AVClass libdav1d_class = {
  365. .class_name = "libdav1d decoder",
  366. .item_name = av_default_item_name,
  367. .option = libdav1d_options,
  368. .version = LIBAVUTIL_VERSION_INT,
  369. };
  370. AVCodec ff_libdav1d_decoder = {
  371. .name = "libdav1d",
  372. .long_name = NULL_IF_CONFIG_SMALL("dav1d AV1 decoder by VideoLAN"),
  373. .type = AVMEDIA_TYPE_VIDEO,
  374. .id = AV_CODEC_ID_AV1,
  375. .priv_data_size = sizeof(Libdav1dContext),
  376. .init = libdav1d_init,
  377. .close = libdav1d_close,
  378. .flush = libdav1d_flush,
  379. .receive_frame = libdav1d_receive_frame,
  380. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  381. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_SETS_PKT_DTS,
  382. .priv_class = &libdav1d_class,
  383. .wrapper_name = "libdav1d",
  384. };