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.

376 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
  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/common.h"
  33. #include "libavutil/intreadwrite.h"
  34. #include "libavutil/log.h"
  35. #include "libavutil/base64.h"
  36. #include "avcodec.h"
  37. #include "internal.h"
  38. /* libtheora includes */
  39. #include <theora/theoraenc.h>
  40. typedef struct TheoraContext {
  41. th_enc_ctx *t_state;
  42. uint8_t *stats;
  43. int stats_size;
  44. int stats_offset;
  45. int uv_hshift;
  46. int uv_vshift;
  47. int keyframe_mask;
  48. } TheoraContext;
  49. /** Concatenate an ogg_packet into the extradata. */
  50. static int concatenate_packet(unsigned int* offset,
  51. AVCodecContext* avc_context,
  52. const ogg_packet* packet)
  53. {
  54. const char* message = NULL;
  55. uint8_t* newdata = NULL;
  56. int newsize = avc_context->extradata_size + 2 + packet->bytes;
  57. if (packet->bytes < 0) {
  58. message = "ogg_packet has negative size";
  59. } else if (packet->bytes > 0xffff) {
  60. message = "ogg_packet is larger than 65535 bytes";
  61. } else if (newsize < avc_context->extradata_size) {
  62. message = "extradata_size would overflow";
  63. } else {
  64. newdata = av_realloc(avc_context->extradata, newsize);
  65. if (!newdata)
  66. message = "av_realloc failed";
  67. }
  68. if (message) {
  69. av_log(avc_context, AV_LOG_ERROR, "concatenate_packet failed: %s\n", message);
  70. return -1;
  71. }
  72. avc_context->extradata = newdata;
  73. avc_context->extradata_size = newsize;
  74. AV_WB16(avc_context->extradata + (*offset), packet->bytes);
  75. *offset += 2;
  76. memcpy(avc_context->extradata + (*offset), packet->packet, packet->bytes);
  77. (*offset) += packet->bytes;
  78. return 0;
  79. }
  80. static int get_stats(AVCodecContext *avctx, int eos)
  81. {
  82. #ifdef TH_ENCCTL_2PASS_OUT
  83. TheoraContext *h = avctx->priv_data;
  84. uint8_t *buf;
  85. int bytes;
  86. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
  87. if (bytes < 0) {
  88. av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
  89. return -1;
  90. }
  91. if (!eos) {
  92. h->stats = av_fast_realloc(h->stats, &h->stats_size,
  93. h->stats_offset + bytes);
  94. memcpy(h->stats + h->stats_offset, buf, bytes);
  95. h->stats_offset += bytes;
  96. } else {
  97. int b64_size = AV_BASE64_SIZE(h->stats_offset);
  98. // libtheora generates a summary header at the end
  99. memcpy(h->stats, buf, bytes);
  100. avctx->stats_out = av_malloc(b64_size);
  101. av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);
  102. }
  103. return 0;
  104. #else
  105. av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
  106. return -1;
  107. #endif
  108. }
  109. // libtheora won't read the entire buffer we give it at once, so we have to
  110. // repeatedly submit it...
  111. static int submit_stats(AVCodecContext *avctx)
  112. {
  113. #ifdef TH_ENCCTL_2PASS_IN
  114. TheoraContext *h = avctx->priv_data;
  115. int bytes;
  116. if (!h->stats) {
  117. if (!avctx->stats_in) {
  118. av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
  119. return -1;
  120. }
  121. h->stats_size = strlen(avctx->stats_in) * 3/4;
  122. h->stats = av_malloc(h->stats_size);
  123. h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
  124. }
  125. while (h->stats_size - h->stats_offset > 0) {
  126. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_IN,
  127. h->stats + h->stats_offset,
  128. h->stats_size - h->stats_offset);
  129. if (bytes < 0) {
  130. av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
  131. return -1;
  132. }
  133. if (!bytes)
  134. return 0;
  135. h->stats_offset += bytes;
  136. }
  137. return 0;
  138. #else
  139. av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
  140. return -1;
  141. #endif
  142. }
  143. static av_cold int encode_init(AVCodecContext* avc_context)
  144. {
  145. th_info t_info;
  146. th_comment t_comment;
  147. ogg_packet o_packet;
  148. unsigned int offset;
  149. TheoraContext *h = avc_context->priv_data;
  150. uint32_t gop_size = avc_context->gop_size;
  151. /* Set up the theora_info struct */
  152. th_info_init(&t_info);
  153. t_info.frame_width = FFALIGN(avc_context->width, 16);
  154. t_info.frame_height = FFALIGN(avc_context->height, 16);
  155. t_info.pic_width = avc_context->width;
  156. t_info.pic_height = avc_context->height;
  157. t_info.pic_x = 0;
  158. t_info.pic_y = 0;
  159. /* Swap numerator and denominator as time_base in AVCodecContext gives the
  160. * time period between frames, but theora_info needs the framerate. */
  161. t_info.fps_numerator = avc_context->time_base.den;
  162. t_info.fps_denominator = avc_context->time_base.num;
  163. if (avc_context->sample_aspect_ratio.num) {
  164. t_info.aspect_numerator = avc_context->sample_aspect_ratio.num;
  165. t_info.aspect_denominator = avc_context->sample_aspect_ratio.den;
  166. } else {
  167. t_info.aspect_numerator = 1;
  168. t_info.aspect_denominator = 1;
  169. }
  170. if (avc_context->color_primaries == AVCOL_PRI_BT470M)
  171. t_info.colorspace = TH_CS_ITU_REC_470M;
  172. else if (avc_context->color_primaries == AVCOL_PRI_BT470BG)
  173. t_info.colorspace = TH_CS_ITU_REC_470BG;
  174. else
  175. t_info.colorspace = TH_CS_UNSPECIFIED;
  176. if (avc_context->pix_fmt == PIX_FMT_YUV420P)
  177. t_info.pixel_fmt = TH_PF_420;
  178. else if (avc_context->pix_fmt == PIX_FMT_YUV422P)
  179. t_info.pixel_fmt = TH_PF_422;
  180. else if (avc_context->pix_fmt == PIX_FMT_YUV444P)
  181. t_info.pixel_fmt = TH_PF_444;
  182. else {
  183. av_log(avc_context, AV_LOG_ERROR, "Unsupported pix_fmt\n");
  184. return -1;
  185. }
  186. avcodec_get_chroma_sub_sample(avc_context->pix_fmt, &h->uv_hshift, &h->uv_vshift);
  187. if (avc_context->flags & CODEC_FLAG_QSCALE) {
  188. /* to be constant with the libvorbis implementation, clip global_quality to 0 - 10
  189. Theora accepts a quality parameter p, which is:
  190. * 0 <= p <=63
  191. * an int value
  192. */
  193. t_info.quality = av_clip(avc_context->global_quality / (float)FF_QP2LAMBDA, 0, 10) * 6.3;
  194. t_info.target_bitrate = 0;
  195. } else {
  196. t_info.target_bitrate = avc_context->bit_rate;
  197. t_info.quality = 0;
  198. }
  199. /* Now initialise libtheora */
  200. h->t_state = th_encode_alloc(&t_info);
  201. if (!h->t_state) {
  202. av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");
  203. return -1;
  204. }
  205. h->keyframe_mask = (1 << t_info.keyframe_granule_shift) - 1;
  206. /* Clear up theora_info struct */
  207. th_info_clear(&t_info);
  208. if (th_encode_ctl(h->t_state, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
  209. &gop_size, sizeof(gop_size))) {
  210. av_log(avc_context, AV_LOG_ERROR, "Error setting GOP size\n");
  211. return -1;
  212. }
  213. // need to enable 2 pass (via TH_ENCCTL_2PASS_) before encoding headers
  214. if (avc_context->flags & CODEC_FLAG_PASS1) {
  215. if (get_stats(avc_context, 0))
  216. return -1;
  217. } else if (avc_context->flags & CODEC_FLAG_PASS2) {
  218. if (submit_stats(avc_context))
  219. return -1;
  220. }
  221. /*
  222. Output first header packet consisting of theora
  223. header, comment, and tables.
  224. Each one is prefixed with a 16bit size, then they
  225. are concatenated together into libavcodec's extradata.
  226. */
  227. offset = 0;
  228. /* Headers */
  229. th_comment_init(&t_comment);
  230. while (th_encode_flushheader(h->t_state, &t_comment, &o_packet))
  231. if (concatenate_packet(&offset, avc_context, &o_packet))
  232. return -1;
  233. th_comment_clear(&t_comment);
  234. /* Set up the output AVFrame */
  235. avc_context->coded_frame= avcodec_alloc_frame();
  236. return 0;
  237. }
  238. static int encode_frame(AVCodecContext* avc_context, AVPacket *pkt,
  239. const AVFrame *frame, int *got_packet)
  240. {
  241. th_ycbcr_buffer t_yuv_buffer;
  242. TheoraContext *h = avc_context->priv_data;
  243. ogg_packet o_packet;
  244. int result, i, ret;
  245. // EOS, finish and get 1st pass stats if applicable
  246. if (!frame) {
  247. th_encode_packetout(h->t_state, 1, &o_packet);
  248. if (avc_context->flags & CODEC_FLAG_PASS1)
  249. if (get_stats(avc_context, 1))
  250. return -1;
  251. return 0;
  252. }
  253. /* Copy planes to the theora yuv_buffer */
  254. for (i = 0; i < 3; i++) {
  255. t_yuv_buffer[i].width = FFALIGN(avc_context->width, 16) >> (i && h->uv_hshift);
  256. t_yuv_buffer[i].height = FFALIGN(avc_context->height, 16) >> (i && h->uv_vshift);
  257. t_yuv_buffer[i].stride = frame->linesize[i];
  258. t_yuv_buffer[i].data = frame->data[i];
  259. }
  260. if (avc_context->flags & CODEC_FLAG_PASS2)
  261. if (submit_stats(avc_context))
  262. return -1;
  263. /* Now call into theora_encode_YUVin */
  264. result = th_encode_ycbcr_in(h->t_state, t_yuv_buffer);
  265. if (result) {
  266. const char* message;
  267. switch (result) {
  268. case -1:
  269. message = "differing frame sizes";
  270. break;
  271. case TH_EINVAL:
  272. message = "encoder is not ready or is finished";
  273. break;
  274. default:
  275. message = "unknown reason";
  276. break;
  277. }
  278. av_log(avc_context, AV_LOG_ERROR, "theora_encode_YUVin failed (%s) [%d]\n", message, result);
  279. return -1;
  280. }
  281. if (avc_context->flags & CODEC_FLAG_PASS1)
  282. if (get_stats(avc_context, 0))
  283. return -1;
  284. /* Pick up returned ogg_packet */
  285. result = th_encode_packetout(h->t_state, 0, &o_packet);
  286. switch (result) {
  287. case 0:
  288. /* No packet is ready */
  289. return 0;
  290. case 1:
  291. /* Success, we have a packet */
  292. break;
  293. default:
  294. av_log(avc_context, AV_LOG_ERROR, "theora_encode_packetout failed [%d]\n", result);
  295. return -1;
  296. }
  297. /* Copy ogg_packet content out to buffer */
  298. if ((ret = ff_alloc_packet2(avc_context, pkt, o_packet.bytes)) < 0)
  299. return ret;
  300. memcpy(pkt->data, o_packet.packet, o_packet.bytes);
  301. // HACK: assumes no encoder delay, this is true until libtheora becomes
  302. // multithreaded (which will be disabled unless explictly requested)
  303. pkt->pts = pkt->dts = frame->pts;
  304. avc_context->coded_frame->key_frame = !(o_packet.granulepos & h->keyframe_mask);
  305. if (avc_context->coded_frame->key_frame)
  306. pkt->flags |= AV_PKT_FLAG_KEY;
  307. *got_packet = 1;
  308. return 0;
  309. }
  310. static av_cold int encode_close(AVCodecContext* avc_context)
  311. {
  312. TheoraContext *h = avc_context->priv_data;
  313. th_encode_free(h->t_state);
  314. av_freep(&h->stats);
  315. av_freep(&avc_context->coded_frame);
  316. av_freep(&avc_context->stats_out);
  317. av_freep(&avc_context->extradata);
  318. avc_context->extradata_size = 0;
  319. return 0;
  320. }
  321. /** AVCodec struct exposed to libavcodec */
  322. AVCodec ff_libtheora_encoder = {
  323. .name = "libtheora",
  324. .type = AVMEDIA_TYPE_VIDEO,
  325. .id = AV_CODEC_ID_THEORA,
  326. .priv_data_size = sizeof(TheoraContext),
  327. .init = encode_init,
  328. .close = encode_close,
  329. .encode2 = encode_frame,
  330. .capabilities = CODEC_CAP_DELAY, // needed to get the statsfile summary
  331. .pix_fmts = (const enum PixelFormat[]){
  332. PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE
  333. },
  334. .long_name = NULL_IF_CONFIG_SMALL("libtheora Theora"),
  335. };