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.

377 lines
12KB

  1. /*
  2. * Copyright (c) 2006 Paul Richards <paul.richards@gmail.com>
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav 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. * Libav 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 Libav; 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. /* Libav includes */
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/log.h"
  34. #include "libavutil/base64.h"
  35. #include "avcodec.h"
  36. #include "internal.h"
  37. /* libtheora includes */
  38. #include <theora/theoraenc.h>
  39. typedef struct TheoraContext {
  40. th_enc_ctx *t_state;
  41. uint8_t *stats;
  42. int stats_size;
  43. int stats_offset;
  44. int uv_hshift;
  45. int uv_vshift;
  46. int keyframe_mask;
  47. } TheoraContext;
  48. /** Concatenate an ogg_packet into the extradata. */
  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. #ifdef TH_ENCCTL_2PASS_OUT
  82. TheoraContext *h = avctx->priv_data;
  83. uint8_t *buf;
  84. int bytes;
  85. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
  86. if (bytes < 0) {
  87. av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
  88. return -1;
  89. }
  90. if (!eos) {
  91. h->stats = av_fast_realloc(h->stats, &h->stats_size,
  92. h->stats_offset + bytes);
  93. memcpy(h->stats + h->stats_offset, buf, bytes);
  94. h->stats_offset += bytes;
  95. } else {
  96. int b64_size = AV_BASE64_SIZE(h->stats_offset);
  97. // libtheora generates a summary header at the end
  98. memcpy(h->stats, buf, bytes);
  99. avctx->stats_out = av_malloc(b64_size);
  100. av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);
  101. }
  102. return 0;
  103. #else
  104. av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
  105. return -1;
  106. #endif
  107. }
  108. // libtheora won't read the entire buffer we give it at once, so we have to
  109. // repeatedly submit it...
  110. static int submit_stats(AVCodecContext *avctx)
  111. {
  112. #ifdef TH_ENCCTL_2PASS_IN
  113. TheoraContext *h = avctx->priv_data;
  114. int bytes;
  115. if (!h->stats) {
  116. if (!avctx->stats_in) {
  117. av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
  118. return -1;
  119. }
  120. h->stats_size = strlen(avctx->stats_in) * 3/4;
  121. h->stats = av_malloc(h->stats_size);
  122. h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
  123. }
  124. while (h->stats_size - h->stats_offset > 0) {
  125. bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_IN,
  126. h->stats + h->stats_offset,
  127. h->stats_size - h->stats_offset);
  128. if (bytes < 0) {
  129. av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
  130. return -1;
  131. }
  132. if (!bytes)
  133. return 0;
  134. h->stats_offset += bytes;
  135. }
  136. return 0;
  137. #else
  138. av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
  139. return -1;
  140. #endif
  141. }
  142. static av_cold int encode_init(AVCodecContext* avc_context)
  143. {
  144. th_info t_info;
  145. th_comment t_comment;
  146. ogg_packet o_packet;
  147. unsigned int offset;
  148. TheoraContext *h = avc_context->priv_data;
  149. uint32_t gop_size = avc_context->gop_size;
  150. /* Set up the theora_info struct */
  151. th_info_init(&t_info);
  152. t_info.frame_width = FFALIGN(avc_context->width, 16);
  153. t_info.frame_height = FFALIGN(avc_context->height, 16);
  154. t_info.pic_width = avc_context->width;
  155. t_info.pic_height = avc_context->height;
  156. t_info.pic_x = 0;
  157. t_info.pic_y = 0;
  158. /* Swap numerator and denominator as time_base in AVCodecContext gives the
  159. * time period between frames, but theora_info needs the framerate. */
  160. t_info.fps_numerator = avc_context->time_base.den;
  161. t_info.fps_denominator = avc_context->time_base.num;
  162. if (avc_context->sample_aspect_ratio.num) {
  163. t_info.aspect_numerator = avc_context->sample_aspect_ratio.num;
  164. t_info.aspect_denominator = avc_context->sample_aspect_ratio.den;
  165. } else {
  166. t_info.aspect_numerator = 1;
  167. t_info.aspect_denominator = 1;
  168. }
  169. if (avc_context->color_primaries == AVCOL_PRI_BT470M)
  170. t_info.colorspace = TH_CS_ITU_REC_470M;
  171. else if (avc_context->color_primaries == AVCOL_PRI_BT470BG)
  172. t_info.colorspace = TH_CS_ITU_REC_470BG;
  173. else
  174. t_info.colorspace = TH_CS_UNSPECIFIED;
  175. if (avc_context->pix_fmt == PIX_FMT_YUV420P)
  176. t_info.pixel_fmt = TH_PF_420;
  177. else if (avc_context->pix_fmt == PIX_FMT_YUV422P)
  178. t_info.pixel_fmt = TH_PF_422;
  179. else if (avc_context->pix_fmt == PIX_FMT_YUV444P)
  180. t_info.pixel_fmt = TH_PF_444;
  181. else {
  182. av_log(avc_context, AV_LOG_ERROR, "Unsupported pix_fmt\n");
  183. return -1;
  184. }
  185. avcodec_get_chroma_sub_sample(avc_context->pix_fmt, &h->uv_hshift, &h->uv_vshift);
  186. if (avc_context->flags & CODEC_FLAG_QSCALE) {
  187. /* to be constant with the libvorbis implementation, clip global_quality to 0 - 10
  188. Theora accepts a quality parameter p, which is:
  189. * 0 <= p <=63
  190. * an int value
  191. */
  192. t_info.quality = av_clip(avc_context->global_quality / (float)FF_QP2LAMBDA, 0, 10) * 6.3;
  193. t_info.target_bitrate = 0;
  194. } else {
  195. t_info.target_bitrate = avc_context->bit_rate;
  196. t_info.quality = 0;
  197. }
  198. /* Now initialise libtheora */
  199. h->t_state = th_encode_alloc(&t_info);
  200. if (!h->t_state) {
  201. av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");
  202. return -1;
  203. }
  204. h->keyframe_mask = (1 << t_info.keyframe_granule_shift) - 1;
  205. /* Clear up theora_info struct */
  206. th_info_clear(&t_info);
  207. if (th_encode_ctl(h->t_state, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
  208. &gop_size, sizeof(gop_size))) {
  209. av_log(avc_context, AV_LOG_ERROR, "Error setting GOP size\n");
  210. return -1;
  211. }
  212. // need to enable 2 pass (via TH_ENCCTL_2PASS_) before encoding headers
  213. if (avc_context->flags & CODEC_FLAG_PASS1) {
  214. if (get_stats(avc_context, 0))
  215. return -1;
  216. } else if (avc_context->flags & CODEC_FLAG_PASS2) {
  217. if (submit_stats(avc_context))
  218. return -1;
  219. }
  220. /*
  221. Output first header packet consisting of theora
  222. header, comment, and tables.
  223. Each one is prefixed with a 16bit size, then they
  224. are concatenated together into libavcodec's extradata.
  225. */
  226. offset = 0;
  227. /* Headers */
  228. th_comment_init(&t_comment);
  229. while (th_encode_flushheader(h->t_state, &t_comment, &o_packet))
  230. if (concatenate_packet(&offset, avc_context, &o_packet))
  231. return -1;
  232. th_comment_clear(&t_comment);
  233. /* Set up the output AVFrame */
  234. avc_context->coded_frame= avcodec_alloc_frame();
  235. return 0;
  236. }
  237. static int encode_frame(AVCodecContext* avc_context, AVPacket *pkt,
  238. const AVFrame *frame, int *got_packet)
  239. {
  240. th_ycbcr_buffer t_yuv_buffer;
  241. TheoraContext *h = avc_context->priv_data;
  242. ogg_packet o_packet;
  243. int result, i, ret;
  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 ((ret = ff_alloc_packet(pkt, o_packet.bytes)) < 0) {
  298. av_log(avc_context, AV_LOG_ERROR, "Error getting output packet of size %ld.\n", o_packet.bytes);
  299. return ret;
  300. }
  301. memcpy(pkt->data, 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. pkt->pts = pkt->dts = frame->pts;
  305. avc_context->coded_frame->key_frame = !(o_packet.granulepos & h->keyframe_mask);
  306. if (avc_context->coded_frame->key_frame)
  307. pkt->flags |= AV_PKT_FLAG_KEY;
  308. *got_packet = 1;
  309. return 0;
  310. }
  311. static av_cold int encode_close(AVCodecContext* avc_context)
  312. {
  313. TheoraContext *h = avc_context->priv_data;
  314. th_encode_free(h->t_state);
  315. av_freep(&h->stats);
  316. av_freep(&avc_context->coded_frame);
  317. av_freep(&avc_context->stats_out);
  318. av_freep(&avc_context->extradata);
  319. avc_context->extradata_size = 0;
  320. return 0;
  321. }
  322. /** AVCodec struct exposed to libavcodec */
  323. AVCodec ff_libtheora_encoder = {
  324. .name = "libtheora",
  325. .type = AVMEDIA_TYPE_VIDEO,
  326. .id = CODEC_ID_THEORA,
  327. .priv_data_size = sizeof(TheoraContext),
  328. .init = encode_init,
  329. .close = encode_close,
  330. .encode2 = encode_frame,
  331. .capabilities = CODEC_CAP_DELAY, // needed to get the statsfile summary
  332. .pix_fmts = (const enum PixelFormat[]){
  333. PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE
  334. },
  335. .long_name = NULL_IF_CONFIG_SMALL("libtheora Theora"),
  336. };