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 OGGVORBIS_FRAME_SIZE 64
  35. #define BUFFER_SIZE (1024 * 64)
  36. typedef struct OggVorbisEncContext {
  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. } OggVorbisEncContext;
  49. static const AVOption options[] = {
  50. { "iblock", "Sets the impulse block bias", offsetof(OggVorbisEncContext, 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 oggvorbis_init_encoder(vorbis_info *vi,
  73. AVCodecContext *avctx)
  74. {
  75. OggVorbisEncContext *s = avctx->priv_data;
  76. double cfreq;
  77. int ret;
  78. if (avctx->flags & CODEC_FLAG_QSCALE || !avctx->bit_rate) {
  79. /* variable bitrate
  80. * NOTE: we use the oggenc range of -1 to 10 for global_quality for
  81. * user convenience, but libvorbis uses -0.1 to 1.0.
  82. */
  83. float q = avctx->global_quality / (float)FF_QP2LAMBDA;
  84. /* default to 3 if the user did not set quality or bitrate */
  85. if (!(avctx->flags & CODEC_FLAG_QSCALE))
  86. q = 3.0;
  87. if ((ret = vorbis_encode_setup_vbr(vi, avctx->channels,
  88. avctx->sample_rate,
  89. q / 10.0)))
  90. goto error;
  91. } else {
  92. int minrate = avctx->rc_min_rate > 0 ? avctx->rc_min_rate : -1;
  93. int maxrate = avctx->rc_max_rate > 0 ? avctx->rc_max_rate : -1;
  94. /* average bitrate */
  95. if ((ret = vorbis_encode_setup_managed(vi, avctx->channels,
  96. avctx->sample_rate, maxrate,
  97. avctx->bit_rate, minrate)))
  98. goto error;
  99. /* variable bitrate by estimate, disable slow rate management */
  100. if (minrate == -1 && maxrate == -1)
  101. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL)))
  102. goto error; /* should not happen */
  103. }
  104. /* cutoff frequency */
  105. if (avctx->cutoff > 0) {
  106. cfreq = avctx->cutoff / 1000.0;
  107. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq)))
  108. goto error; /* should not happen */
  109. }
  110. /* impulse block bias */
  111. if (s->iblock) {
  112. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &s->iblock)))
  113. goto error;
  114. }
  115. if (avctx->channels == 3 &&
  116. avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
  117. avctx->channels == 4 &&
  118. avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
  119. avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
  120. avctx->channels == 5 &&
  121. avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
  122. avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
  123. avctx->channels == 6 &&
  124. avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
  125. avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK ||
  126. avctx->channels == 7 &&
  127. avctx->channel_layout != (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) ||
  128. avctx->channels == 8 &&
  129. avctx->channel_layout != AV_CH_LAYOUT_7POINT1) {
  130. if (avctx->channel_layout) {
  131. char name[32];
  132. av_get_channel_layout_string(name, sizeof(name), avctx->channels,
  133. avctx->channel_layout);
  134. av_log(avctx, AV_LOG_ERROR, "%s not supported by Vorbis: "
  135. "output stream will have incorrect "
  136. "channel layout.\n", name);
  137. } else {
  138. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
  139. "will use Vorbis channel layout for "
  140. "%d channels.\n", avctx->channels);
  141. }
  142. }
  143. if ((ret = vorbis_encode_setup_init(vi)))
  144. goto error;
  145. return 0;
  146. error:
  147. return vorbis_error_to_averror(ret);
  148. }
  149. /* How many bytes are needed for a buffer of length 'l' */
  150. static int xiph_len(int l)
  151. {
  152. return 1 + l / 255 + l;
  153. }
  154. static av_cold int oggvorbis_encode_close(AVCodecContext *avctx)
  155. {
  156. OggVorbisEncContext *s = avctx->priv_data;
  157. /* notify vorbisenc this is EOF */
  158. if (s->dsp_initialized)
  159. vorbis_analysis_wrote(&s->vd, 0);
  160. vorbis_block_clear(&s->vb);
  161. vorbis_dsp_clear(&s->vd);
  162. vorbis_info_clear(&s->vi);
  163. av_fifo_free(s->pkt_fifo);
  164. ff_af_queue_close(&s->afq);
  165. av_freep(&avctx->extradata);
  166. return 0;
  167. }
  168. static av_cold int oggvorbis_encode_init(AVCodecContext *avctx)
  169. {
  170. OggVorbisEncContext *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 = oggvorbis_init_encoder(&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. if ((ret = avpriv_vorbis_parse_extradata(avctx, &s->vp)) < 0) {
  220. av_log(avctx, AV_LOG_ERROR, "invalid extradata\n");
  221. return ret;
  222. }
  223. vorbis_comment_clear(&s->vc);
  224. avctx->frame_size = OGGVORBIS_FRAME_SIZE;
  225. ff_af_queue_init(avctx, &s->afq);
  226. s->pkt_fifo = av_fifo_alloc(BUFFER_SIZE);
  227. if (!s->pkt_fifo) {
  228. ret = AVERROR(ENOMEM);
  229. goto error;
  230. }
  231. return 0;
  232. error:
  233. oggvorbis_encode_close(avctx);
  234. return ret;
  235. }
  236. static int oggvorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  237. const AVFrame *frame, int *got_packet_ptr)
  238. {
  239. OggVorbisEncContext *s = avctx->priv_data;
  240. ogg_packet op;
  241. int ret, duration;
  242. /* send samples to libvorbis */
  243. if (frame) {
  244. const int samples = frame->nb_samples;
  245. float **buffer;
  246. int c, channels = s->vi.channels;
  247. buffer = vorbis_analysis_buffer(&s->vd, samples);
  248. for (c = 0; c < channels; c++) {
  249. int co = (channels > 8) ? c :
  250. ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
  251. memcpy(buffer[c], frame->extended_data[co],
  252. samples * sizeof(*buffer[c]));
  253. }
  254. if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {
  255. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  256. return vorbis_error_to_averror(ret);
  257. }
  258. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  259. return ret;
  260. } else {
  261. if (!s->eof)
  262. if ((ret = vorbis_analysis_wrote(&s->vd, 0)) < 0) {
  263. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  264. return vorbis_error_to_averror(ret);
  265. }
  266. s->eof = 1;
  267. }
  268. /* retrieve available packets from libvorbis */
  269. while ((ret = vorbis_analysis_blockout(&s->vd, &s->vb)) == 1) {
  270. if ((ret = vorbis_analysis(&s->vb, NULL)) < 0)
  271. break;
  272. if ((ret = vorbis_bitrate_addblock(&s->vb)) < 0)
  273. break;
  274. /* add any available packets to the output packet buffer */
  275. while ((ret = vorbis_bitrate_flushpacket(&s->vd, &op)) == 1) {
  276. if (av_fifo_space(s->pkt_fifo) < sizeof(ogg_packet) + op.bytes) {
  277. av_log(avctx, AV_LOG_ERROR, "packet buffer is too small\n");
  278. return AVERROR_BUG;
  279. }
  280. av_fifo_generic_write(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  281. av_fifo_generic_write(s->pkt_fifo, op.packet, op.bytes, NULL);
  282. }
  283. if (ret < 0) {
  284. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  285. break;
  286. }
  287. }
  288. if (ret < 0) {
  289. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  290. return vorbis_error_to_averror(ret);
  291. }
  292. /* check for available packets */
  293. if (av_fifo_size(s->pkt_fifo) < sizeof(ogg_packet))
  294. return 0;
  295. av_fifo_generic_read(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  296. if ((ret = ff_alloc_packet2(avctx, avpkt, op.bytes)) < 0)
  297. return ret;
  298. av_fifo_generic_read(s->pkt_fifo, avpkt->data, op.bytes, NULL);
  299. avpkt->pts = ff_samples_to_time_base(avctx, op.granulepos);
  300. duration = avpriv_vorbis_parse_frame(&s->vp, avpkt->data, avpkt->size);
  301. if (duration > 0) {
  302. /* we do not know encoder delay until we get the first packet from
  303. * libvorbis, so we have to update the AudioFrameQueue counts */
  304. if (!avctx->delay && s->afq.frames) {
  305. avctx->delay = duration;
  306. av_assert0(!s->afq.remaining_delay);
  307. s->afq.frames->duration += duration;
  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(OggVorbisEncContext),
  322. .init = oggvorbis_encode_init,
  323. .encode2 = oggvorbis_encode_frame,
  324. .close = oggvorbis_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. };