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.

381 lines
14KB

  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. AVVorbisParseContext *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. av_vorbis_parse_free(&s->vp);
  166. return 0;
  167. }
  168. static av_cold int libvorbis_encode_init(AVCodecContext *avctx)
  169. {
  170. LibvorbisEncContext *s = avctx->priv_data;
  171. ogg_packet header, header_comm, header_code;
  172. uint8_t *p;
  173. unsigned int offset;
  174. int ret;
  175. vorbis_info_init(&s->vi);
  176. if ((ret = libvorbis_setup(&s->vi, avctx))) {
  177. av_log(avctx, AV_LOG_ERROR, "encoder setup failed\n");
  178. goto error;
  179. }
  180. if ((ret = vorbis_analysis_init(&s->vd, &s->vi))) {
  181. av_log(avctx, AV_LOG_ERROR, "analysis init failed\n");
  182. ret = vorbis_error_to_averror(ret);
  183. goto error;
  184. }
  185. s->dsp_initialized = 1;
  186. if ((ret = vorbis_block_init(&s->vd, &s->vb))) {
  187. av_log(avctx, AV_LOG_ERROR, "dsp init failed\n");
  188. ret = vorbis_error_to_averror(ret);
  189. goto error;
  190. }
  191. vorbis_comment_init(&s->vc);
  192. if (!(avctx->flags & CODEC_FLAG_BITEXACT))
  193. vorbis_comment_add_tag(&s->vc, "encoder", LIBAVCODEC_IDENT);
  194. if ((ret = vorbis_analysis_headerout(&s->vd, &s->vc, &header, &header_comm,
  195. &header_code))) {
  196. ret = vorbis_error_to_averror(ret);
  197. goto error;
  198. }
  199. avctx->extradata_size = 1 + xiph_len(header.bytes) +
  200. xiph_len(header_comm.bytes) +
  201. header_code.bytes;
  202. p = avctx->extradata = av_malloc(avctx->extradata_size +
  203. FF_INPUT_BUFFER_PADDING_SIZE);
  204. if (!p) {
  205. ret = AVERROR(ENOMEM);
  206. goto error;
  207. }
  208. p[0] = 2;
  209. offset = 1;
  210. offset += av_xiphlacing(&p[offset], header.bytes);
  211. offset += av_xiphlacing(&p[offset], header_comm.bytes);
  212. memcpy(&p[offset], header.packet, header.bytes);
  213. offset += header.bytes;
  214. memcpy(&p[offset], header_comm.packet, header_comm.bytes);
  215. offset += header_comm.bytes;
  216. memcpy(&p[offset], header_code.packet, header_code.bytes);
  217. offset += header_code.bytes;
  218. av_assert0(offset == avctx->extradata_size);
  219. s->vp = av_vorbis_parse_init(avctx->extradata, avctx->extradata_size);
  220. if (!s->vp) {
  221. av_log(avctx, AV_LOG_ERROR, "invalid extradata\n");
  222. return ret;
  223. }
  224. vorbis_comment_clear(&s->vc);
  225. avctx->frame_size = LIBVORBIS_FRAME_SIZE;
  226. ff_af_queue_init(avctx, &s->afq);
  227. s->pkt_fifo = av_fifo_alloc(BUFFER_SIZE);
  228. if (!s->pkt_fifo) {
  229. ret = AVERROR(ENOMEM);
  230. goto error;
  231. }
  232. return 0;
  233. error:
  234. libvorbis_encode_close(avctx);
  235. return ret;
  236. }
  237. static int libvorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  238. const AVFrame *frame, int *got_packet_ptr)
  239. {
  240. LibvorbisEncContext *s = avctx->priv_data;
  241. ogg_packet op;
  242. int ret, duration;
  243. /* send samples to libvorbis */
  244. if (frame) {
  245. const int samples = frame->nb_samples;
  246. float **buffer;
  247. int c, channels = s->vi.channels;
  248. buffer = vorbis_analysis_buffer(&s->vd, samples);
  249. for (c = 0; c < channels; c++) {
  250. int co = (channels > 8) ? c :
  251. ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
  252. memcpy(buffer[c], frame->extended_data[co],
  253. samples * sizeof(*buffer[c]));
  254. }
  255. if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {
  256. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  257. return vorbis_error_to_averror(ret);
  258. }
  259. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  260. return ret;
  261. } else {
  262. if (!s->eof && s->afq.frame_alloc)
  263. if ((ret = vorbis_analysis_wrote(&s->vd, 0)) < 0) {
  264. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  265. return vorbis_error_to_averror(ret);
  266. }
  267. s->eof = 1;
  268. }
  269. /* retrieve available packets from libvorbis */
  270. while ((ret = vorbis_analysis_blockout(&s->vd, &s->vb)) == 1) {
  271. if ((ret = vorbis_analysis(&s->vb, NULL)) < 0)
  272. break;
  273. if ((ret = vorbis_bitrate_addblock(&s->vb)) < 0)
  274. break;
  275. /* add any available packets to the output packet buffer */
  276. while ((ret = vorbis_bitrate_flushpacket(&s->vd, &op)) == 1) {
  277. if (av_fifo_space(s->pkt_fifo) < sizeof(ogg_packet) + op.bytes) {
  278. av_log(avctx, AV_LOG_ERROR, "packet buffer is too small\n");
  279. return AVERROR_BUG;
  280. }
  281. av_fifo_generic_write(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  282. av_fifo_generic_write(s->pkt_fifo, op.packet, op.bytes, NULL);
  283. }
  284. if (ret < 0) {
  285. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  286. break;
  287. }
  288. }
  289. if (ret < 0) {
  290. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  291. return vorbis_error_to_averror(ret);
  292. }
  293. /* check for available packets */
  294. if (av_fifo_size(s->pkt_fifo) < sizeof(ogg_packet))
  295. return 0;
  296. av_fifo_generic_read(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  297. if ((ret = ff_alloc_packet2(avctx, avpkt, op.bytes, 0)) < 0)
  298. return ret;
  299. av_fifo_generic_read(s->pkt_fifo, avpkt->data, op.bytes, NULL);
  300. avpkt->pts = ff_samples_to_time_base(avctx, op.granulepos);
  301. duration = av_vorbis_parse_frame(s->vp, avpkt->data, avpkt->size);
  302. if (duration > 0) {
  303. /* we do not know encoder delay until we get the first packet from
  304. * libvorbis, so we have to update the AudioFrameQueue counts */
  305. if (!avctx->initial_padding && s->afq.frames) {
  306. avctx->initial_padding = duration;
  307. av_assert0(!s->afq.remaining_delay);
  308. s->afq.frames->duration += duration;
  309. if (s->afq.frames->pts != AV_NOPTS_VALUE)
  310. s->afq.frames->pts -= duration;
  311. s->afq.remaining_samples += duration;
  312. }
  313. ff_af_queue_remove(&s->afq, duration, &avpkt->pts, &avpkt->duration);
  314. }
  315. *got_packet_ptr = 1;
  316. return 0;
  317. }
  318. AVCodec ff_libvorbis_encoder = {
  319. .name = "libvorbis",
  320. .long_name = NULL_IF_CONFIG_SMALL("libvorbis"),
  321. .type = AVMEDIA_TYPE_AUDIO,
  322. .id = AV_CODEC_ID_VORBIS,
  323. .priv_data_size = sizeof(LibvorbisEncContext),
  324. .init = libvorbis_encode_init,
  325. .encode2 = libvorbis_encode_frame,
  326. .close = libvorbis_encode_close,
  327. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_SMALL_LAST_FRAME,
  328. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  329. AV_SAMPLE_FMT_NONE },
  330. .priv_class = &vorbis_class,
  331. .defaults = defaults,
  332. };