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.

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