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.

355 lines
13KB

  1. /*
  2. * Copyright (C) 2009 Justin Ruggles
  3. * Copyright (c) 2009 Xuggle Incorporated
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * libspeex Speex audio encoder
  24. *
  25. * Usage Guide
  26. * This explains the values that need to be set prior to initialization in
  27. * order to control various encoding parameters.
  28. *
  29. * Channels
  30. * Speex only supports mono or stereo, so avctx->channels must be set to
  31. * 1 or 2.
  32. *
  33. * Sample Rate / Encoding Mode
  34. * Speex has 3 modes, each of which uses a specific sample rate.
  35. * narrowband : 8 kHz
  36. * wideband : 16 kHz
  37. * ultra-wideband : 32 kHz
  38. * avctx->sample_rate must be set to one of these 3 values. This will be
  39. * used to set the encoding mode.
  40. *
  41. * Rate Control
  42. * VBR mode is turned on by setting CODEC_FLAG_QSCALE in avctx->flags.
  43. * avctx->global_quality is used to set the encoding quality.
  44. * For CBR mode, avctx->bit_rate can be used to set the constant bitrate.
  45. * Alternatively, the 'cbr_quality' option can be set from 0 to 10 to set
  46. * a constant bitrate based on quality.
  47. * For ABR mode, set avctx->bit_rate and set the 'abr' option to 1.
  48. * Approx. Bitrate Range:
  49. * narrowband : 2400 - 25600 bps
  50. * wideband : 4000 - 43200 bps
  51. * ultra-wideband : 4400 - 45200 bps
  52. *
  53. * Complexity
  54. * Encoding complexity is controlled by setting avctx->compression_level.
  55. * The valid range is 0 to 10. A higher setting gives generally better
  56. * quality at the expense of encoding speed. This does not affect the
  57. * bit rate.
  58. *
  59. * Frames-per-Packet
  60. * The encoder defaults to using 1 frame-per-packet. However, it is
  61. * sometimes desirable to use multiple frames-per-packet to reduce the
  62. * amount of container overhead. This can be done by setting the
  63. * 'frames_per_packet' option to a value 1 to 8.
  64. */
  65. #include <speex/speex.h>
  66. #include <speex/speex_header.h>
  67. #include <speex/speex_stereo.h>
  68. #include "libavutil/audioconvert.h"
  69. #include "libavutil/common.h"
  70. #include "libavutil/opt.h"
  71. #include "avcodec.h"
  72. #include "internal.h"
  73. #include "audio_frame_queue.h"
  74. /* TODO: Think about converting abr, vad, dtx (still to come) and such flags to a bit field */
  75. typedef struct {
  76. AVClass *class; ///< AVClass for private options
  77. SpeexBits bits; ///< libspeex bitwriter context
  78. SpeexHeader header; ///< libspeex header struct
  79. void *enc_state; ///< libspeex encoder state
  80. int frames_per_packet; ///< number of frames to encode in each packet
  81. float vbr_quality; ///< VBR quality 0.0 to 10.0
  82. int cbr_quality; ///< CBR quality 0 to 10
  83. int abr; ///< flag to enable ABR
  84. int vad; ///< flag to enable VAD
  85. int pkt_frame_count; ///< frame count for the current packet
  86. AudioFrameQueue afq; ///< frame queue
  87. } LibSpeexEncContext;
  88. static av_cold void print_enc_params(AVCodecContext *avctx,
  89. LibSpeexEncContext *s)
  90. {
  91. const char *mode_str = "unknown";
  92. av_log(avctx, AV_LOG_DEBUG, "channels: %d\n", avctx->channels);
  93. switch (s->header.mode) {
  94. case SPEEX_MODEID_NB: mode_str = "narrowband"; break;
  95. case SPEEX_MODEID_WB: mode_str = "wideband"; break;
  96. case SPEEX_MODEID_UWB: mode_str = "ultra-wideband"; break;
  97. }
  98. av_log(avctx, AV_LOG_DEBUG, "mode: %s\n", mode_str);
  99. if (s->header.vbr) {
  100. av_log(avctx, AV_LOG_DEBUG, "rate control: VBR\n");
  101. av_log(avctx, AV_LOG_DEBUG, " quality: %f\n", s->vbr_quality);
  102. } else if (s->abr) {
  103. av_log(avctx, AV_LOG_DEBUG, "rate control: ABR\n");
  104. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  105. } else {
  106. av_log(avctx, AV_LOG_DEBUG, "rate control: CBR\n");
  107. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  108. }
  109. av_log(avctx, AV_LOG_DEBUG, "complexity: %d\n",
  110. avctx->compression_level);
  111. av_log(avctx, AV_LOG_DEBUG, "frame size: %d samples\n",
  112. avctx->frame_size);
  113. av_log(avctx, AV_LOG_DEBUG, "frames per packet: %d\n",
  114. s->frames_per_packet);
  115. av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
  116. avctx->frame_size * s->frames_per_packet);
  117. av_log(avctx, AV_LOG_DEBUG, "voice activity detection: %d\n", s->vad);
  118. }
  119. static av_cold int encode_init(AVCodecContext *avctx)
  120. {
  121. LibSpeexEncContext *s = avctx->priv_data;
  122. const SpeexMode *mode;
  123. uint8_t *header_data;
  124. int header_size;
  125. int32_t complexity;
  126. /* channels */
  127. if (avctx->channels < 1 || avctx->channels > 2) {
  128. av_log(avctx, AV_LOG_ERROR, "Invalid channels (%d). Only stereo and "
  129. "mono are supported\n", avctx->channels);
  130. return AVERROR(EINVAL);
  131. }
  132. /* sample rate and encoding mode */
  133. switch (avctx->sample_rate) {
  134. case 8000: mode = &speex_nb_mode; break;
  135. case 16000: mode = &speex_wb_mode; break;
  136. case 32000: mode = &speex_uwb_mode; break;
  137. default:
  138. av_log(avctx, AV_LOG_ERROR, "Sample rate of %d Hz is not supported. "
  139. "Resample to 8, 16, or 32 kHz.\n", avctx->sample_rate);
  140. return AVERROR(EINVAL);
  141. }
  142. /* initialize libspeex */
  143. s->enc_state = speex_encoder_init(mode);
  144. if (!s->enc_state) {
  145. av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex\n");
  146. return -1;
  147. }
  148. speex_init_header(&s->header, avctx->sample_rate, avctx->channels, mode);
  149. /* rate control method and parameters */
  150. if (avctx->flags & CODEC_FLAG_QSCALE) {
  151. /* VBR */
  152. s->header.vbr = 1;
  153. s->vad = 1; /* VAD is always implicitly activated for VBR */
  154. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
  155. s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
  156. 0.0f, 10.0f);
  157. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR_QUALITY, &s->vbr_quality);
  158. } else {
  159. s->header.bitrate = avctx->bit_rate;
  160. if (avctx->bit_rate > 0) {
  161. /* CBR or ABR by bitrate */
  162. if (s->abr) {
  163. speex_encoder_ctl(s->enc_state, SPEEX_SET_ABR,
  164. &s->header.bitrate);
  165. speex_encoder_ctl(s->enc_state, SPEEX_GET_ABR,
  166. &s->header.bitrate);
  167. } else {
  168. speex_encoder_ctl(s->enc_state, SPEEX_SET_BITRATE,
  169. &s->header.bitrate);
  170. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  171. &s->header.bitrate);
  172. }
  173. } else {
  174. /* CBR by quality */
  175. speex_encoder_ctl(s->enc_state, SPEEX_SET_QUALITY,
  176. &s->cbr_quality);
  177. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  178. &s->header.bitrate);
  179. }
  180. /* stereo side information adds about 800 bps to the base bitrate */
  181. /* TODO: this should be calculated exactly */
  182. avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
  183. }
  184. /* VAD is activated with VBR or can be turned on by itself */
  185. if (s->vad)
  186. speex_encoder_ctl(s->enc_state, SPEEX_SET_VAD, &s->vad);
  187. /* set encoding complexity */
  188. if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
  189. complexity = av_clip(avctx->compression_level, 0, 10);
  190. speex_encoder_ctl(s->enc_state, SPEEX_SET_COMPLEXITY, &complexity);
  191. }
  192. speex_encoder_ctl(s->enc_state, SPEEX_GET_COMPLEXITY, &complexity);
  193. avctx->compression_level = complexity;
  194. /* set packet size */
  195. avctx->frame_size = s->header.frame_size;
  196. s->header.frames_per_packet = s->frames_per_packet;
  197. /* set encoding delay */
  198. speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &avctx->delay);
  199. ff_af_queue_init(avctx, &s->afq);
  200. /* create header packet bytes from header struct */
  201. /* note: libspeex allocates the memory for header_data, which is freed
  202. below with speex_header_free() */
  203. header_data = speex_header_to_packet(&s->header, &header_size);
  204. /* allocate extradata and coded_frame */
  205. avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
  206. if (!avctx->extradata) {
  207. speex_header_free(header_data);
  208. speex_encoder_destroy(s->enc_state);
  209. av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
  210. return AVERROR(ENOMEM);
  211. }
  212. #if FF_API_OLD_ENCODE_AUDIO
  213. avctx->coded_frame = avcodec_alloc_frame();
  214. if (!avctx->coded_frame) {
  215. av_freep(&avctx->extradata);
  216. speex_header_free(header_data);
  217. speex_encoder_destroy(s->enc_state);
  218. av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
  219. return AVERROR(ENOMEM);
  220. }
  221. #endif
  222. /* copy header packet to extradata */
  223. memcpy(avctx->extradata, header_data, header_size);
  224. avctx->extradata_size = header_size;
  225. speex_header_free(header_data);
  226. /* init libspeex bitwriter */
  227. speex_bits_init(&s->bits);
  228. print_enc_params(avctx, s);
  229. return 0;
  230. }
  231. static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  232. const AVFrame *frame, int *got_packet_ptr)
  233. {
  234. LibSpeexEncContext *s = avctx->priv_data;
  235. int16_t *samples = frame ? (int16_t *)frame->data[0] : NULL;
  236. int ret;
  237. if (samples) {
  238. /* encode Speex frame */
  239. if (avctx->channels == 2)
  240. speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
  241. speex_encode_int(s->enc_state, samples, &s->bits);
  242. s->pkt_frame_count++;
  243. if ((ret = ff_af_queue_add(&s->afq, frame) < 0))
  244. return ret;
  245. } else {
  246. /* handle end-of-stream */
  247. if (!s->pkt_frame_count)
  248. return 0;
  249. /* add extra terminator codes for unused frames in last packet */
  250. while (s->pkt_frame_count < s->frames_per_packet) {
  251. speex_bits_pack(&s->bits, 15, 5);
  252. s->pkt_frame_count++;
  253. }
  254. }
  255. /* write output if all frames for the packet have been encoded */
  256. if (s->pkt_frame_count == s->frames_per_packet) {
  257. s->pkt_frame_count = 0;
  258. if ((ret = ff_alloc_packet2(avctx, avpkt, speex_bits_nbytes(&s->bits))))
  259. return ret;
  260. ret = speex_bits_write(&s->bits, avpkt->data, avpkt->size);
  261. speex_bits_reset(&s->bits);
  262. /* Get the next frame pts/duration */
  263. ff_af_queue_remove(&s->afq, s->frames_per_packet * avctx->frame_size,
  264. &avpkt->pts, &avpkt->duration);
  265. avpkt->size = ret;
  266. *got_packet_ptr = 1;
  267. return 0;
  268. }
  269. return 0;
  270. }
  271. static av_cold int encode_close(AVCodecContext *avctx)
  272. {
  273. LibSpeexEncContext *s = avctx->priv_data;
  274. speex_bits_destroy(&s->bits);
  275. speex_encoder_destroy(s->enc_state);
  276. ff_af_queue_close(&s->afq);
  277. #if FF_API_OLD_ENCODE_AUDIO
  278. av_freep(&avctx->coded_frame);
  279. #endif
  280. av_freep(&avctx->extradata);
  281. return 0;
  282. }
  283. #define OFFSET(x) offsetof(LibSpeexEncContext, x)
  284. #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  285. static const AVOption options[] = {
  286. { "abr", "Use average bit rate", OFFSET(abr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AE },
  287. { "cbr_quality", "Set quality value (0 to 10) for CBR", OFFSET(cbr_quality), AV_OPT_TYPE_INT, { .i64 = 8 }, 0, 10, AE },
  288. { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, 8, AE },
  289. { "vad", "Voice Activity Detection", OFFSET(vad), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AE },
  290. { NULL },
  291. };
  292. static const AVClass class = {
  293. .class_name = "libspeex",
  294. .item_name = av_default_item_name,
  295. .option = options,
  296. .version = LIBAVUTIL_VERSION_INT,
  297. };
  298. static const AVCodecDefault defaults[] = {
  299. { "b", "0" },
  300. { "compression_level", "3" },
  301. { NULL },
  302. };
  303. AVCodec ff_libspeex_encoder = {
  304. .name = "libspeex",
  305. .type = AVMEDIA_TYPE_AUDIO,
  306. .id = AV_CODEC_ID_SPEEX,
  307. .priv_data_size = sizeof(LibSpeexEncContext),
  308. .init = encode_init,
  309. .encode2 = encode_frame,
  310. .close = encode_close,
  311. .capabilities = CODEC_CAP_DELAY,
  312. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  313. AV_SAMPLE_FMT_NONE },
  314. .channel_layouts = (const uint64_t[]){ AV_CH_LAYOUT_MONO,
  315. AV_CH_LAYOUT_STEREO,
  316. 0 },
  317. .supported_samplerates = (const int[]){ 8000, 16000, 32000, 0 },
  318. .long_name = NULL_IF_CONFIG_SMALL("libspeex Speex"),
  319. .priv_class = &class,
  320. .defaults = defaults,
  321. };