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.

349 lines
11KB

  1. /*
  2. * libkvazaar encoder
  3. *
  4. * Copyright (c) 2015 Tampere University of Technology
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <kvazaar.h>
  23. #include <stdint.h>
  24. #include <string.h>
  25. #include "libavutil/attributes.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/error.h"
  29. #include "libavutil/imgutils.h"
  30. #include "libavutil/internal.h"
  31. #include "libavutil/log.h"
  32. #include "libavutil/mem.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/opt.h"
  35. #include "avcodec.h"
  36. #include "internal.h"
  37. #include "packet_internal.h"
  38. typedef struct LibkvazaarContext {
  39. const AVClass *class;
  40. const kvz_api *api;
  41. kvz_encoder *encoder;
  42. kvz_config *config;
  43. char *kvz_params;
  44. } LibkvazaarContext;
  45. static av_cold int libkvazaar_init(AVCodecContext *avctx)
  46. {
  47. LibkvazaarContext *const ctx = avctx->priv_data;
  48. const kvz_api *const api = ctx->api = kvz_api_get(8);
  49. kvz_config *cfg = NULL;
  50. kvz_encoder *enc = NULL;
  51. /* Kvazaar requires width and height to be multiples of eight. */
  52. if (avctx->width % 8 || avctx->height % 8) {
  53. av_log(avctx, AV_LOG_ERROR,
  54. "Video dimensions are not a multiple of 8 (%dx%d).\n",
  55. avctx->width, avctx->height);
  56. return AVERROR(ENOSYS);
  57. }
  58. ctx->config = cfg = api->config_alloc();
  59. if (!cfg) {
  60. av_log(avctx, AV_LOG_ERROR,
  61. "Could not allocate kvazaar config structure.\n");
  62. return AVERROR(ENOMEM);
  63. }
  64. if (!api->config_init(cfg)) {
  65. av_log(avctx, AV_LOG_ERROR,
  66. "Could not initialize kvazaar config structure.\n");
  67. return AVERROR_BUG;
  68. }
  69. cfg->width = avctx->width;
  70. cfg->height = avctx->height;
  71. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  72. cfg->framerate_num = avctx->framerate.num;
  73. cfg->framerate_denom = avctx->framerate.den;
  74. } else {
  75. if (avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
  76. av_log(avctx, AV_LOG_ERROR,
  77. "Could not set framerate for kvazaar: integer overflow\n");
  78. return AVERROR(EINVAL);
  79. }
  80. cfg->framerate_num = avctx->time_base.den;
  81. cfg->framerate_denom = avctx->time_base.num * avctx->ticks_per_frame;
  82. }
  83. cfg->target_bitrate = avctx->bit_rate;
  84. cfg->vui.sar_width = avctx->sample_aspect_ratio.num;
  85. cfg->vui.sar_height = avctx->sample_aspect_ratio.den;
  86. if (avctx->bit_rate) {
  87. cfg->rc_algorithm = KVZ_LAMBDA;
  88. }
  89. if (ctx->kvz_params) {
  90. AVDictionary *dict = NULL;
  91. if (!av_dict_parse_string(&dict, ctx->kvz_params, "=", ",", 0)) {
  92. AVDictionaryEntry *entry = NULL;
  93. while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) {
  94. if (!api->config_parse(cfg, entry->key, entry->value)) {
  95. av_log(avctx, AV_LOG_WARNING, "Invalid option: %s=%s.\n",
  96. entry->key, entry->value);
  97. }
  98. }
  99. }
  100. av_dict_free(&dict);
  101. }
  102. ctx->encoder = enc = api->encoder_open(cfg);
  103. if (!enc) {
  104. av_log(avctx, AV_LOG_ERROR, "Could not open kvazaar encoder.\n");
  105. return AVERROR_BUG;
  106. }
  107. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  108. kvz_data_chunk *data_out = NULL;
  109. kvz_data_chunk *chunk = NULL;
  110. uint32_t len_out;
  111. uint8_t *p;
  112. if (!api->encoder_headers(enc, &data_out, &len_out))
  113. return AVERROR(ENOMEM);
  114. avctx->extradata = p = av_mallocz(len_out + AV_INPUT_BUFFER_PADDING_SIZE);
  115. if (!p) {
  116. ctx->api->chunk_free(data_out);
  117. return AVERROR(ENOMEM);
  118. }
  119. avctx->extradata_size = len_out;
  120. for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
  121. memcpy(p, chunk->data, chunk->len);
  122. p += chunk->len;
  123. }
  124. ctx->api->chunk_free(data_out);
  125. }
  126. return 0;
  127. }
  128. static av_cold int libkvazaar_close(AVCodecContext *avctx)
  129. {
  130. LibkvazaarContext *ctx = avctx->priv_data;
  131. if (ctx->api) {
  132. ctx->api->encoder_close(ctx->encoder);
  133. ctx->api->config_destroy(ctx->config);
  134. }
  135. if (avctx->extradata)
  136. av_freep(&avctx->extradata);
  137. return 0;
  138. }
  139. static int libkvazaar_encode(AVCodecContext *avctx,
  140. AVPacket *avpkt,
  141. const AVFrame *frame,
  142. int *got_packet_ptr)
  143. {
  144. LibkvazaarContext *ctx = avctx->priv_data;
  145. kvz_picture *input_pic = NULL;
  146. kvz_picture *recon_pic = NULL;
  147. kvz_frame_info frame_info;
  148. kvz_data_chunk *data_out = NULL;
  149. uint32_t len_out = 0;
  150. int retval = 0;
  151. int pict_type;
  152. *got_packet_ptr = 0;
  153. if (frame) {
  154. if (frame->width != ctx->config->width ||
  155. frame->height != ctx->config->height) {
  156. av_log(avctx, AV_LOG_ERROR,
  157. "Changing video dimensions during encoding is not supported. "
  158. "(changed from %dx%d to %dx%d)\n",
  159. ctx->config->width, ctx->config->height,
  160. frame->width, frame->height);
  161. retval = AVERROR_INVALIDDATA;
  162. goto done;
  163. }
  164. if (frame->format != avctx->pix_fmt) {
  165. av_log(avctx, AV_LOG_ERROR,
  166. "Changing pixel format during encoding is not supported. "
  167. "(changed from %s to %s)\n",
  168. av_get_pix_fmt_name(avctx->pix_fmt),
  169. av_get_pix_fmt_name(frame->format));
  170. retval = AVERROR_INVALIDDATA;
  171. goto done;
  172. }
  173. // Allocate input picture for kvazaar.
  174. input_pic = ctx->api->picture_alloc(frame->width, frame->height);
  175. if (!input_pic) {
  176. av_log(avctx, AV_LOG_ERROR, "Failed to allocate picture.\n");
  177. retval = AVERROR(ENOMEM);
  178. goto done;
  179. }
  180. // Copy pixels from frame to input_pic.
  181. {
  182. int dst_linesizes[4] = {
  183. frame->width,
  184. frame->width / 2,
  185. frame->width / 2,
  186. 0
  187. };
  188. av_image_copy(input_pic->data, dst_linesizes,
  189. (const uint8_t **)frame->data, frame->linesize,
  190. frame->format, frame->width, frame->height);
  191. }
  192. input_pic->pts = frame->pts;
  193. }
  194. retval = ctx->api->encoder_encode(ctx->encoder,
  195. input_pic,
  196. &data_out, &len_out,
  197. &recon_pic, NULL,
  198. &frame_info);
  199. if (!retval) {
  200. av_log(avctx, AV_LOG_ERROR, "Failed to encode frame.\n");
  201. retval = AVERROR_INVALIDDATA;
  202. goto done;
  203. } else
  204. retval = 0; /* kvazaar returns 1 on success */
  205. if (data_out) {
  206. kvz_data_chunk *chunk = NULL;
  207. uint64_t written = 0;
  208. retval = ff_alloc_packet2(avctx, avpkt, len_out, len_out);
  209. if (retval < 0) {
  210. av_log(avctx, AV_LOG_ERROR, "Failed to allocate output packet.\n");
  211. goto done;
  212. }
  213. for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
  214. av_assert0(written + chunk->len <= len_out);
  215. memcpy(avpkt->data + written, chunk->data, chunk->len);
  216. written += chunk->len;
  217. }
  218. avpkt->pts = recon_pic->pts;
  219. avpkt->dts = recon_pic->dts;
  220. avpkt->flags = 0;
  221. // IRAP VCL NAL unit types span the range
  222. // [BLA_W_LP (16), RSV_IRAP_VCL23 (23)].
  223. if (frame_info.nal_unit_type >= KVZ_NAL_BLA_W_LP &&
  224. frame_info.nal_unit_type <= KVZ_NAL_RSV_IRAP_VCL23) {
  225. avpkt->flags |= AV_PKT_FLAG_KEY;
  226. }
  227. switch (frame_info.slice_type) {
  228. case KVZ_SLICE_I:
  229. pict_type = AV_PICTURE_TYPE_I;
  230. break;
  231. case KVZ_SLICE_P:
  232. pict_type = AV_PICTURE_TYPE_P;
  233. break;
  234. case KVZ_SLICE_B:
  235. pict_type = AV_PICTURE_TYPE_B;
  236. break;
  237. default:
  238. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered.\n");
  239. return AVERROR_EXTERNAL;
  240. }
  241. #if FF_API_CODED_FRAME
  242. FF_DISABLE_DEPRECATION_WARNINGS
  243. avctx->coded_frame->pict_type = pict_type;
  244. FF_ENABLE_DEPRECATION_WARNINGS
  245. #endif
  246. ff_side_data_set_encoder_stats(avpkt, frame_info.qp * FF_QP2LAMBDA, NULL, 0, pict_type);
  247. #if FF_API_CODED_FRAME
  248. FF_DISABLE_DEPRECATION_WARNINGS
  249. avctx->coded_frame->quality = frame_info.qp * FF_QP2LAMBDA;
  250. FF_ENABLE_DEPRECATION_WARNINGS
  251. #endif
  252. *got_packet_ptr = 1;
  253. }
  254. done:
  255. ctx->api->picture_free(input_pic);
  256. ctx->api->picture_free(recon_pic);
  257. ctx->api->chunk_free(data_out);
  258. return retval;
  259. }
  260. static const enum AVPixelFormat pix_fmts[] = {
  261. AV_PIX_FMT_YUV420P,
  262. AV_PIX_FMT_NONE
  263. };
  264. #define OFFSET(x) offsetof(LibkvazaarContext, x)
  265. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  266. static const AVOption options[] = {
  267. { "kvazaar-params", "Set kvazaar parameters as a comma-separated list of key=value pairs.",
  268. OFFSET(kvz_params), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
  269. { NULL },
  270. };
  271. static const AVClass class = {
  272. .class_name = "libkvazaar",
  273. .item_name = av_default_item_name,
  274. .option = options,
  275. .version = LIBAVUTIL_VERSION_INT,
  276. };
  277. static const AVCodecDefault defaults[] = {
  278. { "b", "0" },
  279. { NULL },
  280. };
  281. AVCodec ff_libkvazaar_encoder = {
  282. .name = "libkvazaar",
  283. .long_name = NULL_IF_CONFIG_SMALL("libkvazaar H.265 / HEVC"),
  284. .type = AVMEDIA_TYPE_VIDEO,
  285. .id = AV_CODEC_ID_HEVC,
  286. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_OTHER_THREADS,
  287. .pix_fmts = pix_fmts,
  288. .priv_class = &class,
  289. .priv_data_size = sizeof(LibkvazaarContext),
  290. .defaults = defaults,
  291. .init = libkvazaar_init,
  292. .encode2 = libkvazaar_encode,
  293. .close = libkvazaar_close,
  294. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP |
  295. FF_CODEC_CAP_AUTO_THREADS,
  296. .wrapper_name = "libkvazaar",
  297. };