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.

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