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.

360 lines
12KB

  1. /*
  2. * Copyright (c) 2006 Paul Richards <paul.richards@gmail.com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /*!
  21. * \file libtheoraenc.c
  22. * \brief Theora encoder using libtheora.
  23. * \author Paul Richards <paul.richards@gmail.com>
  24. *
  25. * A lot of this is copy / paste from other output codecs in
  26. * libavcodec or pure guesswork (or both).
  27. *
  28. * I have used t_ prefixes on variables which are libtheora types
  29. * and o_ prefixes on variables which are libogg types.
  30. */
  31. /* FFmpeg includes */
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/log.h"
  34. #include "libavutil/base64.h"
  35. #include "avcodec.h"
  36. /* libtheora includes */
  37. #include <theora/theoraenc.h>
  38. typedef struct TheoraContext {
  39. th_enc_ctx *t_state;
  40. uint8_t *stats;
  41. int stats_size;
  42. int stats_offset;
  43. int uv_hshift;
  44. int uv_vshift;
  45. } TheoraContext;
  46. /*!
  47. Concatenates an ogg_packet into the extradata.
  48. */
  49. static int concatenate_packet(unsigned int* offset,
  50. AVCodecContext* avc_context,
  51. const ogg_packet* packet)
  52. {
  53. const char* message = NULL;
  54. uint8_t* newdata = NULL;
  55. int newsize = avc_context->extradata_size + 2 + packet->bytes;
  56. if (packet->bytes < 0) {
  57. message = "ogg_packet has negative size";
  58. } else if (packet->bytes > 0xffff) {
  59. message = "ogg_packet is larger than 65535 bytes";
  60. } else if (newsize < avc_context->extradata_size) {
  61. message = "extradata_size would overflow";
  62. } else {
  63. newdata = av_realloc(avc_context->extradata, newsize);
  64. if (!newdata)
  65. message = "av_realloc failed";
  66. }
  67. if (message) {
  68. av_log(avc_context, AV_LOG_ERROR, "concatenate_packet failed: %s\n", message);
  69. return -1;
  70. }
  71. avc_context->extradata = newdata;
  72. avc_context->extradata_size = newsize;
  73. AV_WB16(avc_context->extradata + (*offset), packet->bytes);
  74. *offset += 2;
  75. memcpy(avc_context->extradata + (*offset), packet->packet, packet->bytes);
  76. (*offset) += packet->bytes;
  77. return 0;
  78. }
  79. static int get_stats(AVCodecContext *avctx, int eos)
  80. {
  81. TheoraContext *h = avctx->priv_data;
  82. uint8_t *buf;
  83. int bytes;
  84. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
  85. if (bytes < 0) {
  86. av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
  87. return -1;
  88. }
  89. if (!eos) {
  90. h->stats = av_fast_realloc(h->stats, &h->stats_size,
  91. h->stats_offset + bytes);
  92. memcpy(h->stats + h->stats_offset, buf, bytes);
  93. h->stats_offset += bytes;
  94. } else {
  95. int b64_size = ((h->stats_offset + 2) / 3) * 4 + 1;
  96. // libtheora generates a summary header at the end
  97. memcpy(h->stats, buf, bytes);
  98. avctx->stats_out = av_malloc(b64_size);
  99. av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);
  100. }
  101. return 0;
  102. }
  103. // libtheora won't read the entire buffer we give it at once, so we have to
  104. // repeatedly submit it...
  105. static int submit_stats(AVCodecContext *avctx)
  106. {
  107. TheoraContext *h = avctx->priv_data;
  108. int bytes;
  109. if (!h->stats) {
  110. if (!avctx->stats_in) {
  111. av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
  112. return -1;
  113. }
  114. h->stats_size = strlen(avctx->stats_in) * 3/4;
  115. h->stats = av_malloc(h->stats_size);
  116. h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
  117. }
  118. while (h->stats_size - h->stats_offset > 0) {
  119. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_IN,
  120. h->stats + h->stats_offset,
  121. h->stats_size - h->stats_offset);
  122. if (bytes < 0) {
  123. av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
  124. return -1;
  125. }
  126. if (!bytes)
  127. return 0;
  128. h->stats_offset += bytes;
  129. }
  130. return 0;
  131. }
  132. static av_cold int encode_init(AVCodecContext* avc_context)
  133. {
  134. th_info t_info;
  135. th_comment t_comment;
  136. ogg_packet o_packet;
  137. unsigned int offset;
  138. TheoraContext *h = avc_context->priv_data;
  139. uint32_t gop_size = avc_context->gop_size;
  140. /* Set up the theora_info struct */
  141. th_info_init(&t_info);
  142. t_info.frame_width = FFALIGN(avc_context->width, 16);
  143. t_info.frame_height = FFALIGN(avc_context->height, 16);
  144. t_info.pic_width = avc_context->width;
  145. t_info.pic_height = avc_context->height;
  146. t_info.pic_x = 0;
  147. t_info.pic_y = 0;
  148. /* Swap numerator and denominator as time_base in AVCodecContext gives the
  149. * time period between frames, but theora_info needs the framerate. */
  150. t_info.fps_numerator = avc_context->time_base.den;
  151. t_info.fps_denominator = avc_context->time_base.num;
  152. if (avc_context->sample_aspect_ratio.num) {
  153. t_info.aspect_numerator = avc_context->sample_aspect_ratio.num;
  154. t_info.aspect_denominator = avc_context->sample_aspect_ratio.den;
  155. } else {
  156. t_info.aspect_numerator = 1;
  157. t_info.aspect_denominator = 1;
  158. }
  159. if (avc_context->color_primaries == AVCOL_PRI_BT470M)
  160. t_info.colorspace = TH_CS_ITU_REC_470M;
  161. else if (avc_context->color_primaries == AVCOL_PRI_BT470BG)
  162. t_info.colorspace = TH_CS_ITU_REC_470BG;
  163. else
  164. t_info.colorspace = TH_CS_UNSPECIFIED;
  165. if (avc_context->pix_fmt == PIX_FMT_YUV420P)
  166. t_info.pixel_fmt = TH_PF_420;
  167. else if (avc_context->pix_fmt == PIX_FMT_YUV422P)
  168. t_info.pixel_fmt = TH_PF_422;
  169. else if (avc_context->pix_fmt == PIX_FMT_YUV444P)
  170. t_info.pixel_fmt = TH_PF_444;
  171. else {
  172. av_log(avc_context, AV_LOG_ERROR, "Unsupported pix_fmt\n");
  173. return -1;
  174. }
  175. avcodec_get_chroma_sub_sample(avc_context->pix_fmt, &h->uv_hshift, &h->uv_vshift);
  176. if (avc_context->flags & CODEC_FLAG_QSCALE) {
  177. /* to be constant with the libvorbis implementation, clip global_quality to 0 - 10
  178. Theora accepts a quality parameter p, which is:
  179. * 0 <= p <=63
  180. * an int value
  181. */
  182. t_info.quality = av_clip(avc_context->global_quality / (float)FF_QP2LAMBDA, 0, 10) * 6.3;
  183. t_info.target_bitrate = 0;
  184. } else {
  185. t_info.target_bitrate = avc_context->bit_rate;
  186. t_info.quality = 0;
  187. }
  188. /* Now initialise libtheora */
  189. h->t_state = th_encode_alloc(&t_info);
  190. if (!h->t_state) {
  191. av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");
  192. return -1;
  193. }
  194. /* Clear up theora_info struct */
  195. th_info_clear(&t_info);
  196. if (th_encode_ctl(h->t_state, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
  197. &gop_size, sizeof(gop_size))) {
  198. av_log(avc_context, AV_LOG_ERROR, "Error setting GOP size\n");
  199. return -1;
  200. }
  201. // need to enable 2 pass (via TH_ENCCTL_2PASS_) before encoding headers
  202. if (avc_context->flags & CODEC_FLAG_PASS1) {
  203. if (get_stats(avc_context, 0))
  204. return -1;
  205. } else if (avc_context->flags & CODEC_FLAG_PASS2) {
  206. if (submit_stats(avc_context))
  207. return -1;
  208. }
  209. /*
  210. Output first header packet consisting of theora
  211. header, comment, and tables.
  212. Each one is prefixed with a 16bit size, then they
  213. are concatenated together into ffmpeg's extradata.
  214. */
  215. offset = 0;
  216. /* Headers */
  217. th_comment_init(&t_comment);
  218. while (th_encode_flushheader(h->t_state, &t_comment, &o_packet))
  219. if (concatenate_packet(&offset, avc_context, &o_packet))
  220. return -1;
  221. th_comment_clear(&t_comment);
  222. /* Set up the output AVFrame */
  223. avc_context->coded_frame= avcodec_alloc_frame();
  224. return 0;
  225. }
  226. static int encode_frame(AVCodecContext* avc_context, uint8_t *outbuf,
  227. int buf_size, void *data)
  228. {
  229. th_ycbcr_buffer t_yuv_buffer;
  230. TheoraContext *h = avc_context->priv_data;
  231. AVFrame *frame = data;
  232. ogg_packet o_packet;
  233. int result, i;
  234. // EOS, finish and get 1st pass stats if applicable
  235. if (!frame) {
  236. th_encode_packetout(h->t_state, 1, &o_packet);
  237. if (avc_context->flags & CODEC_FLAG_PASS1)
  238. if (get_stats(avc_context, 1))
  239. return -1;
  240. return 0;
  241. }
  242. /* Copy planes to the theora yuv_buffer */
  243. for (i = 0; i < 3; i++) {
  244. t_yuv_buffer[i].width = FFALIGN(avc_context->width, 16) >> (i && h->uv_hshift);
  245. t_yuv_buffer[i].height = FFALIGN(avc_context->height, 16) >> (i && h->uv_vshift);
  246. t_yuv_buffer[i].stride = frame->linesize[i];
  247. t_yuv_buffer[i].data = frame->data[i];
  248. }
  249. if (avc_context->flags & CODEC_FLAG_PASS2)
  250. if (submit_stats(avc_context))
  251. return -1;
  252. /* Now call into theora_encode_YUVin */
  253. result = th_encode_ycbcr_in(h->t_state, t_yuv_buffer);
  254. if (result) {
  255. const char* message;
  256. switch (result) {
  257. case -1:
  258. message = "differing frame sizes";
  259. break;
  260. case TH_EINVAL:
  261. message = "encoder is not ready or is finished";
  262. break;
  263. default:
  264. message = "unknown reason";
  265. break;
  266. }
  267. av_log(avc_context, AV_LOG_ERROR, "theora_encode_YUVin failed (%s) [%d]\n", message, result);
  268. return -1;
  269. }
  270. if (avc_context->flags & CODEC_FLAG_PASS1)
  271. if (get_stats(avc_context, 0))
  272. return -1;
  273. /* Pick up returned ogg_packet */
  274. result = th_encode_packetout(h->t_state, 0, &o_packet);
  275. switch (result) {
  276. case 0:
  277. /* No packet is ready */
  278. return 0;
  279. case 1:
  280. /* Success, we have a packet */
  281. break;
  282. default:
  283. av_log(avc_context, AV_LOG_ERROR, "theora_encode_packetout failed [%d]\n", result);
  284. return -1;
  285. }
  286. /* Copy ogg_packet content out to buffer */
  287. if (buf_size < o_packet.bytes) {
  288. av_log(avc_context, AV_LOG_ERROR, "encoded frame too large\n");
  289. return -1;
  290. }
  291. memcpy(outbuf, o_packet.packet, o_packet.bytes);
  292. // HACK: does not take codec delay into account (neither does the decoder though)
  293. avc_context->coded_frame->pts = frame->pts;
  294. return o_packet.bytes;
  295. }
  296. static av_cold int encode_close(AVCodecContext* avc_context)
  297. {
  298. TheoraContext *h = avc_context->priv_data;
  299. th_encode_free(h->t_state);
  300. av_freep(&h->stats);
  301. av_freep(&avc_context->coded_frame);
  302. av_freep(&avc_context->stats_out);
  303. av_freep(&avc_context->extradata);
  304. avc_context->extradata_size = 0;
  305. return 0;
  306. }
  307. /*! AVCodec struct exposed to libavcodec */
  308. AVCodec libtheora_encoder = {
  309. .name = "libtheora",
  310. .type = CODEC_TYPE_VIDEO,
  311. .id = CODEC_ID_THEORA,
  312. .priv_data_size = sizeof(TheoraContext),
  313. .init = encode_init,
  314. .close = encode_close,
  315. .encode = encode_frame,
  316. .capabilities = CODEC_CAP_DELAY, // needed to get the statsfile summary
  317. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE},
  318. .long_name = NULL_IF_CONFIG_SMALL("libtheora Theora"),
  319. };