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.

387 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/fifo.h"
  22. #include "libavutil/opt.h"
  23. #include "avcodec.h"
  24. #include "audio_frame_queue.h"
  25. #include "internal.h"
  26. #include "vorbis.h"
  27. #include "vorbis_parser.h"
  28. #undef NDEBUG
  29. #include <assert.h>
  30. /* Number of samples the user should send in each call.
  31. * This value is used because it is the LCD of all possible frame sizes, so
  32. * an output packet will always start at the same point as one of the input
  33. * packets.
  34. */
  35. #define OGGVORBIS_FRAME_SIZE 64
  36. #define BUFFER_SIZE (1024 * 64)
  37. typedef struct OggVorbisEncContext {
  38. AVClass *av_class; /**< class for AVOptions */
  39. AVFrame frame;
  40. vorbis_info vi; /**< vorbis_info used during init */
  41. vorbis_dsp_state vd; /**< DSP state used for analysis */
  42. vorbis_block vb; /**< vorbis_block used for analysis */
  43. AVFifoBuffer *pkt_fifo; /**< output packet buffer */
  44. int eof; /**< end-of-file flag */
  45. int dsp_initialized; /**< vd has been initialized */
  46. vorbis_comment vc; /**< VorbisComment info */
  47. double iblock; /**< impulse block bias option */
  48. VorbisParseContext vp; /**< parse context to get durations */
  49. AudioFrameQueue afq; /**< frame queue for timestamps */
  50. } OggVorbisEncContext;
  51. static const AVOption options[] = {
  52. { "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 },
  53. { NULL }
  54. };
  55. static const AVCodecDefault defaults[] = {
  56. { "b", "0" },
  57. { NULL },
  58. };
  59. static const AVClass class = { "libvorbis", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
  60. static int vorbis_error_to_averror(int ov_err)
  61. {
  62. switch (ov_err) {
  63. case OV_EFAULT: return AVERROR_BUG;
  64. case OV_EINVAL: return AVERROR(EINVAL);
  65. case OV_EIMPL: return AVERROR(EINVAL);
  66. default: return AVERROR_UNKNOWN;
  67. }
  68. }
  69. static av_cold int oggvorbis_init_encoder(vorbis_info *vi,
  70. AVCodecContext *avctx)
  71. {
  72. OggVorbisEncContext *s = avctx->priv_data;
  73. double cfreq;
  74. int ret;
  75. if (avctx->flags & CODEC_FLAG_QSCALE || !avctx->bit_rate) {
  76. /* variable bitrate
  77. * NOTE: we use the oggenc range of -1 to 10 for global_quality for
  78. * user convenience, but libvorbis uses -0.1 to 1.0.
  79. */
  80. float q = avctx->global_quality / (float)FF_QP2LAMBDA;
  81. /* default to 3 if the user did not set quality or bitrate */
  82. if (!(avctx->flags & CODEC_FLAG_QSCALE))
  83. q = 3.0;
  84. if ((ret = vorbis_encode_setup_vbr(vi, avctx->channels,
  85. avctx->sample_rate,
  86. q / 10.0)))
  87. goto error;
  88. } else {
  89. int minrate = avctx->rc_min_rate > 0 ? avctx->rc_min_rate : -1;
  90. int maxrate = avctx->rc_max_rate > 0 ? avctx->rc_max_rate : -1;
  91. /* average bitrate */
  92. if ((ret = vorbis_encode_setup_managed(vi, avctx->channels,
  93. avctx->sample_rate, maxrate,
  94. avctx->bit_rate, minrate)))
  95. goto error;
  96. /* variable bitrate by estimate, disable slow rate management */
  97. if (minrate == -1 && maxrate == -1)
  98. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL)))
  99. goto error; /* should not happen */
  100. }
  101. /* cutoff frequency */
  102. if (avctx->cutoff > 0) {
  103. cfreq = avctx->cutoff / 1000.0;
  104. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq)))
  105. goto error; /* should not happen */
  106. }
  107. /* impulse block bias */
  108. if (s->iblock) {
  109. if ((ret = vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &s->iblock)))
  110. goto error;
  111. }
  112. if (avctx->channels == 3 &&
  113. avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
  114. avctx->channels == 4 &&
  115. avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
  116. avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
  117. avctx->channels == 5 &&
  118. avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
  119. avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
  120. avctx->channels == 6 &&
  121. avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
  122. avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK ||
  123. avctx->channels == 7 &&
  124. avctx->channel_layout != (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) ||
  125. avctx->channels == 8 &&
  126. avctx->channel_layout != AV_CH_LAYOUT_7POINT1) {
  127. if (avctx->channel_layout) {
  128. char name[32];
  129. av_get_channel_layout_string(name, sizeof(name), avctx->channels,
  130. avctx->channel_layout);
  131. av_log(avctx, AV_LOG_ERROR, "%s not supported by Vorbis: "
  132. "output stream will have incorrect "
  133. "channel layout.\n", name);
  134. } else {
  135. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
  136. "will use Vorbis channel layout for "
  137. "%d channels.\n", avctx->channels);
  138. }
  139. }
  140. if ((ret = vorbis_encode_setup_init(vi)))
  141. goto error;
  142. return 0;
  143. error:
  144. return vorbis_error_to_averror(ret);
  145. }
  146. /* How many bytes are needed for a buffer of length 'l' */
  147. static int xiph_len(int l)
  148. {
  149. return 1 + l / 255 + l;
  150. }
  151. static av_cold int oggvorbis_encode_close(AVCodecContext *avctx)
  152. {
  153. OggVorbisEncContext *s = avctx->priv_data;
  154. /* notify vorbisenc this is EOF */
  155. if (s->dsp_initialized)
  156. vorbis_analysis_wrote(&s->vd, 0);
  157. vorbis_block_clear(&s->vb);
  158. vorbis_dsp_clear(&s->vd);
  159. vorbis_info_clear(&s->vi);
  160. av_fifo_free(s->pkt_fifo);
  161. ff_af_queue_close(&s->afq);
  162. #if FF_API_OLD_ENCODE_AUDIO
  163. av_freep(&avctx->coded_frame);
  164. #endif
  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. assert(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. #if FF_API_OLD_ENCODE_AUDIO
  232. avctx->coded_frame = avcodec_alloc_frame();
  233. if (!avctx->coded_frame) {
  234. ret = AVERROR(ENOMEM);
  235. goto error;
  236. }
  237. #endif
  238. return 0;
  239. error:
  240. oggvorbis_encode_close(avctx);
  241. return ret;
  242. }
  243. static int oggvorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  244. const AVFrame *frame, int *got_packet_ptr)
  245. {
  246. OggVorbisEncContext *s = avctx->priv_data;
  247. ogg_packet op;
  248. int ret, duration;
  249. /* send samples to libvorbis */
  250. if (frame) {
  251. const float *audio = (const float *)frame->data[0];
  252. const int samples = frame->nb_samples;
  253. float **buffer;
  254. int c, channels = s->vi.channels;
  255. buffer = vorbis_analysis_buffer(&s->vd, samples);
  256. for (c = 0; c < channels; c++) {
  257. int i;
  258. int co = (channels > 8) ? c :
  259. ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
  260. for (i = 0; i < samples; i++)
  261. buffer[c][i] = audio[i * channels + co];
  262. }
  263. if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {
  264. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  265. return vorbis_error_to_averror(ret);
  266. }
  267. if ((ret = ff_af_queue_add(&s->afq, frame) < 0))
  268. return ret;
  269. } else {
  270. if (!s->eof)
  271. if ((ret = vorbis_analysis_wrote(&s->vd, 0)) < 0) {
  272. av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
  273. return vorbis_error_to_averror(ret);
  274. }
  275. s->eof = 1;
  276. }
  277. /* retrieve available packets from libvorbis */
  278. while ((ret = vorbis_analysis_blockout(&s->vd, &s->vb)) == 1) {
  279. if ((ret = vorbis_analysis(&s->vb, NULL)) < 0)
  280. break;
  281. if ((ret = vorbis_bitrate_addblock(&s->vb)) < 0)
  282. break;
  283. /* add any available packets to the output packet buffer */
  284. while ((ret = vorbis_bitrate_flushpacket(&s->vd, &op)) == 1) {
  285. if (av_fifo_space(s->pkt_fifo) < sizeof(ogg_packet) + op.bytes) {
  286. av_log(avctx, AV_LOG_ERROR, "packet buffer is too small\n");
  287. return AVERROR_BUG;
  288. }
  289. av_fifo_generic_write(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  290. av_fifo_generic_write(s->pkt_fifo, op.packet, op.bytes, NULL);
  291. }
  292. if (ret < 0) {
  293. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  294. break;
  295. }
  296. }
  297. if (ret < 0) {
  298. av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");
  299. return vorbis_error_to_averror(ret);
  300. }
  301. /* check for available packets */
  302. if (av_fifo_size(s->pkt_fifo) < sizeof(ogg_packet))
  303. return 0;
  304. av_fifo_generic_read(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);
  305. if ((ret = ff_alloc_packet2(avctx, avpkt, op.bytes)))
  306. return ret;
  307. av_fifo_generic_read(s->pkt_fifo, avpkt->data, op.bytes, NULL);
  308. avpkt->pts = ff_samples_to_time_base(avctx, op.granulepos);
  309. duration = avpriv_vorbis_parse_frame(&s->vp, avpkt->data, avpkt->size);
  310. if (duration > 0) {
  311. /* we do not know encoder delay until we get the first packet from
  312. * libvorbis, so we have to update the AudioFrameQueue counts */
  313. if (!avctx->delay) {
  314. avctx->delay = duration;
  315. s->afq.remaining_delay += duration;
  316. s->afq.remaining_samples += duration;
  317. }
  318. ff_af_queue_remove(&s->afq, duration, &avpkt->pts, &avpkt->duration);
  319. }
  320. *got_packet_ptr = 1;
  321. return 0;
  322. }
  323. AVCodec ff_libvorbis_encoder = {
  324. .name = "libvorbis",
  325. .type = AVMEDIA_TYPE_AUDIO,
  326. .id = CODEC_ID_VORBIS,
  327. .priv_data_size = sizeof(OggVorbisEncContext),
  328. .init = oggvorbis_encode_init,
  329. .encode2 = oggvorbis_encode_frame,
  330. .close = oggvorbis_encode_close,
  331. .capabilities = CODEC_CAP_DELAY,
  332. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLT,
  333. AV_SAMPLE_FMT_NONE },
  334. .long_name = NULL_IF_CONFIG_SMALL("libvorbis"),
  335. .priv_class = &class,
  336. .defaults = defaults,
  337. };