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.

378 lines
13KB

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