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.

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