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) 2002 Mark Hills <mark@pogo.org.uk>
  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. * Vorbis encoding support via libvorbisenc.
  23. * @author Mark Hills <mark@pogo.org.uk>
  24. */
  25. #include <vorbis/vorbisenc.h>
  26. #include "libavutil/fifo.h"
  27. #include "libavutil/opt.h"
  28. #include "avcodec.h"
  29. #include "audio_frame_queue.h"
  30. #include "bytestream.h"
  31. #include "internal.h"
  32. #include "vorbis.h"
  33. #include "vorbis_parser.h"
  34. #undef NDEBUG
  35. #include <assert.h>
  36. /* Number of samples the user should send in each call.
  37. * This value is used because it is the LCD of all possible frame sizes, so
  38. * an output packet will always start at the same point as one of the input
  39. * packets.
  40. */
  41. #define LIBVORBIS_FRAME_SIZE 64
  42. #define BUFFER_SIZE (1024 * 64)
  43. typedef struct LibvorbisContext {
  44. AVClass *av_class; /**< class for AVOptions */
  45. vorbis_info vi; /**< vorbis_info used during init */
  46. vorbis_dsp_state vd; /**< DSP state used for analysis */
  47. vorbis_block vb; /**< vorbis_block used for analysis */
  48. AVFifoBuffer *pkt_fifo; /**< output packet buffer */
  49. int eof; /**< end-of-file flag */
  50. int dsp_initialized; /**< vd has been initialized */
  51. vorbis_comment vc; /**< VorbisComment info */
  52. ogg_packet op; /**< ogg packet */
  53. double iblock; /**< impulse block bias option */
  54. AVVorbisParseContext *vp; /**< parse context to get durations */
  55. AudioFrameQueue afq; /**< frame queue for timestamps */
  56. } LibvorbisContext;
  57. static const AVOption options[] = {
  58. { "iblock", "Sets the impulse block bias", offsetof(LibvorbisContext, iblock), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -15, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
  59. { NULL }
  60. };
  61. static const AVCodecDefault defaults[] = {
  62. { "b", "0" },
  63. { NULL },
  64. };
  65. static const AVClass class = {
  66. .class_name = "libvorbis",
  67. .item_name = av_default_item_name,
  68. .option = options,
  69. .version = LIBAVUTIL_VERSION_INT,
  70. };
  71. static int vorbis_error_to_averror(int ov_err)
  72. {
  73. switch (ov_err) {
  74. case OV_EFAULT: return AVERROR_BUG;
  75. case OV_EINVAL: return AVERROR(EINVAL);
  76. case OV_EIMPL: return AVERROR(EINVAL);
  77. default: return AVERROR_UNKNOWN;
  78. }
  79. }
  80. static av_cold int libvorbis_setup(vorbis_info *vi, AVCodecContext *avctx)
  81. {
  82. LibvorbisContext *s = avctx->priv_data;
  83. double cfreq;
  84. int ret;
  85. if (avctx->flags & AV_CODEC_FLAG_QSCALE || !avctx->bit_rate) {
  86. /* variable bitrate
  87. * NOTE: we use the oggenc range of -1 to 10 for global_quality for
  88. * user convenience, but libvorbis uses -0.1 to 1.0.
  89. */
  90. float q = avctx->global_quality / (float)FF_QP2LAMBDA;
  91. /* default to 3 if the user did not set quality or bitrate */
  92. if (!(avctx->flags & AV_CODEC_FLAG_QSCALE))
  93. q = 3.0;
  94. if ((ret = vorbis_encode_setup_vbr(vi, avctx->channels,
  95. avctx->sample_rate,
  96. q / 10.0)))
  97. goto error;
  98. } else {
  99. int minrate = avctx->rc_min_rate > 0 ? avctx->rc_min_rate : -1;
  100. int maxrate = avctx->rc_max_rate > 0 ? avctx->rc_max_rate : -1;
  101. /* average bitrate */
  102. if ((ret = vorbis_encode_setup_managed(vi, avctx->channels,
  103. avctx->sample_rate, maxrate,
  104. avctx->bit_rate, minrate)))
  105. goto error;
  106. /* variable bitrate by estimate, disable slow rate management */
  107. if (minrate == -1 && maxrate == -1)
  108. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL)))
  109. goto error;
  110. }
  111. /* cutoff frequency */
  112. if (avctx->cutoff > 0) {
  113. cfreq = avctx->cutoff / 1000.0;
  114. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq)))
  115. goto error;
  116. }
  117. /* impulse block bias */
  118. if (s->iblock) {
  119. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &s->iblock)))
  120. goto error;
  121. }
  122. if ((ret = vorbis_encode_setup_init(vi)))
  123. goto error;
  124. return 0;
  125. error:
  126. return vorbis_error_to_averror(ret);
  127. }
  128. /* How many bytes are needed for a buffer of length 'l' */
  129. static int xiph_len(int l)
  130. {
  131. return 1 + l / 255 + l;
  132. }
  133. static av_cold int libvorbis_encode_close(AVCodecContext *avctx)
  134. {
  135. LibvorbisContext *s = avctx->priv_data;
  136. /* notify vorbisenc this is EOF */
  137. if (s->dsp_initialized)
  138. vorbis_analysis_wrote(&s->vd, 0);
  139. vorbis_block_clear(&s->vb);
  140. vorbis_dsp_clear(&s->vd);
  141. vorbis_info_clear(&s->vi);
  142. av_fifo_free(s->pkt_fifo);
  143. ff_af_queue_close(&s->afq);
  144. av_freep(&avctx->extradata);
  145. av_vorbis_parse_free(&s->vp);
  146. return 0;
  147. }
  148. static av_cold int libvorbis_encode_init(AVCodecContext *avctx)
  149. {
  150. LibvorbisContext *s = avctx->priv_data;
  151. ogg_packet header, header_comm, header_code;
  152. uint8_t *p;
  153. unsigned int offset;
  154. int ret;
  155. vorbis_info_init(&s->vi);
  156. if ((ret = libvorbis_setup(&s->vi, avctx))) {
  157. av_log(avctx, AV_LOG_ERROR, "encoder setup failed\n");
  158. goto error;
  159. }
  160. if ((ret = vorbis_analysis_init(&s->vd, &s->vi))) {
  161. av_log(avctx, AV_LOG_ERROR, "analysis init failed\n");
  162. ret = vorbis_error_to_averror(ret);
  163. goto error;
  164. }
  165. s->dsp_initialized = 1;
  166. if ((ret = vorbis_block_init(&s->vd, &s->vb))) {
  167. av_log(avctx, AV_LOG_ERROR, "dsp init failed\n");
  168. ret = vorbis_error_to_averror(ret);
  169. goto error;
  170. }
  171. vorbis_comment_init(&s->vc);
  172. vorbis_comment_add_tag(&s->vc, "encoder", LIBAVCODEC_IDENT);
  173. if ((ret = vorbis_analysis_headerout(&s->vd, &s->vc, &header, &header_comm,
  174. &header_code))) {
  175. ret = vorbis_error_to_averror(ret);
  176. goto error;
  177. }
  178. avctx->extradata_size = 1 + xiph_len(header.bytes) +
  179. xiph_len(header_comm.bytes) +
  180. header_code.bytes;
  181. p = avctx->extradata = av_malloc(avctx->extradata_size +
  182. AV_INPUT_BUFFER_PADDING_SIZE);
  183. if (!p) {
  184. ret = AVERROR(ENOMEM);
  185. goto error;
  186. }
  187. p[0] = 2;
  188. offset = 1;
  189. offset += av_xiphlacing(&p[offset], header.bytes);
  190. offset += av_xiphlacing(&p[offset], header_comm.bytes);
  191. memcpy(&p[offset], header.packet, header.bytes);
  192. offset += header.bytes;
  193. memcpy(&p[offset], header_comm.packet, header_comm.bytes);
  194. offset += header_comm.bytes;
  195. memcpy(&p[offset], header_code.packet, header_code.bytes);
  196. offset += header_code.bytes;
  197. assert(offset == avctx->extradata_size);
  198. s->vp = av_vorbis_parse_init(avctx->extradata, avctx->extradata_size);
  199. if (!s->vp) {
  200. av_log(avctx, AV_LOG_ERROR, "invalid extradata\n");
  201. return ret;
  202. }
  203. vorbis_comment_clear(&s->vc);
  204. avctx->frame_size = LIBVORBIS_FRAME_SIZE;
  205. ff_af_queue_init(avctx, &s->afq);
  206. s->pkt_fifo = av_fifo_alloc(BUFFER_SIZE);
  207. if (!s->pkt_fifo) {
  208. ret = AVERROR(ENOMEM);
  209. goto error;
  210. }
  211. return 0;
  212. error:
  213. libvorbis_encode_close(avctx);
  214. return ret;
  215. }
  216. static int libvorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  217. const AVFrame *frame, int *got_packet_ptr)
  218. {
  219. LibvorbisContext *s = avctx->priv_data;
  220. ogg_packet op;
  221. int ret, duration;
  222. /* send samples to libvorbis */
  223. if (frame) {
  224. const int samples = frame->nb_samples;
  225. float **buffer;
  226. int c, channels = s->vi.channels;
  227. buffer = vorbis_analysis_buffer(&s->vd, samples);
  228. for (c = 0; c < channels; c++) {
  229. int co = (channels > 8) ? c :
  230. ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
  231. memcpy(buffer[c], frame->extended_data[co],
  232. samples * sizeof(*buffer[c]));
  233. }
  234. if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {
  235. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  236. return vorbis_error_to_averror(ret);
  237. }
  238. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  239. return ret;
  240. } else {
  241. if (!s->eof)
  242. if ((ret = vorbis_analysis_wrote(&s->vd, 0)) < 0) {
  243. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  244. return vorbis_error_to_averror(ret);
  245. }
  246. s->eof = 1;
  247. }
  248. /* retrieve available packets from libvorbis */
  249. while ((ret = vorbis_analysis_blockout(&s->vd, &s->vb)) == 1) {
  250. if ((ret = vorbis_analysis(&s->vb, NULL)) < 0)
  251. break;
  252. if ((ret = vorbis_bitrate_addblock(&s->vb)) < 0)
  253. break;
  254. /* add any available packets to the output packet buffer */
  255. while ((ret = vorbis_bitrate_flushpacket(&s->vd, &op)) == 1) {
  256. if (av_fifo_space(s->pkt_fifo) < sizeof(ogg_packet) + op.bytes) {
  257. av_log(avctx, AV_LOG_ERROR, "packet buffer is too small");
  258. return AVERROR_BUG;
  259. }
  260. av_fifo_generic_write(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  261. av_fifo_generic_write(s->pkt_fifo, op.packet, op.bytes, NULL);
  262. }
  263. if (ret < 0) {
  264. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  265. break;
  266. }
  267. }
  268. if (ret < 0) {
  269. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  270. return vorbis_error_to_averror(ret);
  271. }
  272. /* check for available packets */
  273. if (av_fifo_size(s->pkt_fifo) < sizeof(ogg_packet))
  274. return 0;
  275. av_fifo_generic_read(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  276. if ((ret = ff_alloc_packet(avpkt, op.bytes))) {
  277. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  278. return ret;
  279. }
  280. av_fifo_generic_read(s->pkt_fifo, avpkt->data, op.bytes, NULL);
  281. avpkt->pts = ff_samples_to_time_base(avctx, op.granulepos);
  282. duration = av_vorbis_parse_frame(s->vp, avpkt->data, avpkt->size);
  283. if (duration > 0) {
  284. /* we do not know encoder delay until we get the first packet from
  285. * libvorbis, so we have to update the AudioFrameQueue counts */
  286. if (!avctx->initial_padding) {
  287. avctx->initial_padding = duration;
  288. s->afq.remaining_delay += duration;
  289. s->afq.remaining_samples += duration;
  290. }
  291. ff_af_queue_remove(&s->afq, duration, &avpkt->pts, &avpkt->duration);
  292. }
  293. *got_packet_ptr = 1;
  294. return 0;
  295. }
  296. AVCodec ff_libvorbis_encoder = {
  297. .name = "libvorbis",
  298. .long_name = NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
  299. .type = AVMEDIA_TYPE_AUDIO,
  300. .id = AV_CODEC_ID_VORBIS,
  301. .priv_data_size = sizeof(LibvorbisContext),
  302. .init = libvorbis_encode_init,
  303. .encode2 = libvorbis_encode_frame,
  304. .close = libvorbis_encode_close,
  305. .capabilities = AV_CODEC_CAP_DELAY,
  306. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  307. AV_SAMPLE_FMT_NONE },
  308. .priv_class = &class,
  309. .defaults = defaults,
  310. };