libspeexenc.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. *
  66. * Optional features
  67. * Speex encoder supports several optional features, which can be useful
  68. * for some conditions.
  69. *
  70. * Voice Activity Detection
  71. * When enabled, voice activity detection detects whether the audio
  72. * being encoded is speech or silence/background noise. VAD is always
  73. * implicitly activated when encoding in VBR, so the option is only useful
  74. * in non-VBR operation. In this case, Speex detects non-speech periods and
  75. * encodes them with just enough bits to reproduce the background noise.
  76. *
  77. * Discontinuous Transmission (DTX)
  78. * DTX is an addition to VAD/VBR operation, that makes it possible to stop transmitting
  79. * completely when the background noise is stationary.
  80. * In file-based operation only 5 bits are used for such frames.
  81. */
  82. #include <speex/speex.h>
  83. #include <speex/speex_header.h>
  84. #include <speex/speex_stereo.h>
  85. #include "libavutil/channel_layout.h"
  86. #include "libavutil/common.h"
  87. #include "libavutil/opt.h"
  88. #include "avcodec.h"
  89. #include "internal.h"
  90. #include "audio_frame_queue.h"
  91. /* TODO: Think about converting abr, vad, dtx and such flags to a bit field */
  92. typedef struct LibSpeexEncContext {
  93. AVClass *class; ///< AVClass for private options
  94. SpeexBits bits; ///< libspeex bitwriter context
  95. SpeexHeader header; ///< libspeex header struct
  96. void *enc_state; ///< libspeex encoder state
  97. int frames_per_packet; ///< number of frames to encode in each packet
  98. float vbr_quality; ///< VBR quality 0.0 to 10.0
  99. int cbr_quality; ///< CBR quality 0 to 10
  100. int abr; ///< flag to enable ABR
  101. int vad; ///< flag to enable VAD
  102. int dtx; ///< flag to enable DTX
  103. int pkt_frame_count; ///< frame count for the current packet
  104. AudioFrameQueue afq; ///< frame queue
  105. } LibSpeexEncContext;
  106. static av_cold void print_enc_params(AVCodecContext *avctx,
  107. LibSpeexEncContext *s)
  108. {
  109. const char *mode_str = "unknown";
  110. av_log(avctx, AV_LOG_DEBUG, "channels: %d\n", avctx->channels);
  111. switch (s->header.mode) {
  112. case SPEEX_MODEID_NB: mode_str = "narrowband"; break;
  113. case SPEEX_MODEID_WB: mode_str = "wideband"; break;
  114. case SPEEX_MODEID_UWB: mode_str = "ultra-wideband"; break;
  115. }
  116. av_log(avctx, AV_LOG_DEBUG, "mode: %s\n", mode_str);
  117. if (s->header.vbr) {
  118. av_log(avctx, AV_LOG_DEBUG, "rate control: VBR\n");
  119. av_log(avctx, AV_LOG_DEBUG, " quality: %f\n", s->vbr_quality);
  120. } else if (s->abr) {
  121. av_log(avctx, AV_LOG_DEBUG, "rate control: ABR\n");
  122. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  123. } else {
  124. av_log(avctx, AV_LOG_DEBUG, "rate control: CBR\n");
  125. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  126. }
  127. av_log(avctx, AV_LOG_DEBUG, "complexity: %d\n",
  128. avctx->compression_level);
  129. av_log(avctx, AV_LOG_DEBUG, "frame size: %d samples\n",
  130. avctx->frame_size);
  131. av_log(avctx, AV_LOG_DEBUG, "frames per packet: %d\n",
  132. s->frames_per_packet);
  133. av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
  134. avctx->frame_size * s->frames_per_packet);
  135. av_log(avctx, AV_LOG_DEBUG, "voice activity detection: %d\n", s->vad);
  136. av_log(avctx, AV_LOG_DEBUG, "discontinuous transmission: %d\n", s->dtx);
  137. }
  138. static av_cold int encode_init(AVCodecContext *avctx)
  139. {
  140. LibSpeexEncContext *s = avctx->priv_data;
  141. const SpeexMode *mode;
  142. uint8_t *header_data;
  143. int header_size;
  144. int32_t complexity;
  145. /* channels */
  146. if (avctx->channels < 1 || avctx->channels > 2) {
  147. av_log(avctx, AV_LOG_ERROR, "Invalid channels (%d). Only stereo and "
  148. "mono are supported\n", avctx->channels);
  149. return AVERROR(EINVAL);
  150. }
  151. /* sample rate and encoding mode */
  152. switch (avctx->sample_rate) {
  153. case 8000: mode = &speex_nb_mode; break;
  154. case 16000: mode = &speex_wb_mode; break;
  155. case 32000: mode = &speex_uwb_mode; break;
  156. default:
  157. av_log(avctx, AV_LOG_ERROR, "Sample rate of %d Hz is not supported. "
  158. "Resample to 8, 16, or 32 kHz.\n", avctx->sample_rate);
  159. return AVERROR(EINVAL);
  160. }
  161. /* initialize libspeex */
  162. s->enc_state = speex_encoder_init(mode);
  163. if (!s->enc_state) {
  164. av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex\n");
  165. return -1;
  166. }
  167. speex_init_header(&s->header, avctx->sample_rate, avctx->channels, mode);
  168. /* rate control method and parameters */
  169. if (avctx->flags & CODEC_FLAG_QSCALE) {
  170. /* VBR */
  171. s->header.vbr = 1;
  172. s->vad = 1; /* VAD is always implicitly activated for VBR */
  173. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
  174. s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
  175. 0.0f, 10.0f);
  176. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR_QUALITY, &s->vbr_quality);
  177. } else {
  178. s->header.bitrate = avctx->bit_rate;
  179. if (avctx->bit_rate > 0) {
  180. /* CBR or ABR by bitrate */
  181. if (s->abr) {
  182. speex_encoder_ctl(s->enc_state, SPEEX_SET_ABR,
  183. &s->header.bitrate);
  184. speex_encoder_ctl(s->enc_state, SPEEX_GET_ABR,
  185. &s->header.bitrate);
  186. } else {
  187. speex_encoder_ctl(s->enc_state, SPEEX_SET_BITRATE,
  188. &s->header.bitrate);
  189. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  190. &s->header.bitrate);
  191. }
  192. } else {
  193. /* CBR by quality */
  194. speex_encoder_ctl(s->enc_state, SPEEX_SET_QUALITY,
  195. &s->cbr_quality);
  196. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  197. &s->header.bitrate);
  198. }
  199. /* stereo side information adds about 800 bps to the base bitrate */
  200. /* TODO: this should be calculated exactly */
  201. avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
  202. }
  203. /* VAD is activated with VBR or can be turned on by itself */
  204. if (s->vad)
  205. speex_encoder_ctl(s->enc_state, SPEEX_SET_VAD, &s->vad);
  206. /* Activiting Discontinuous Transmission */
  207. if (s->dtx) {
  208. speex_encoder_ctl(s->enc_state, SPEEX_SET_DTX, &s->dtx);
  209. if (!(s->abr || s->vad || s->header.vbr))
  210. av_log(avctx, AV_LOG_WARNING, "DTX is not much of use without ABR, VAD or VBR\n");
  211. }
  212. /* set encoding complexity */
  213. if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
  214. complexity = av_clip(avctx->compression_level, 0, 10);
  215. speex_encoder_ctl(s->enc_state, SPEEX_SET_COMPLEXITY, &complexity);
  216. }
  217. speex_encoder_ctl(s->enc_state, SPEEX_GET_COMPLEXITY, &complexity);
  218. avctx->compression_level = complexity;
  219. /* set packet size */
  220. avctx->frame_size = s->header.frame_size;
  221. s->header.frames_per_packet = s->frames_per_packet;
  222. /* set encoding delay */
  223. speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &avctx->initial_padding);
  224. ff_af_queue_init(avctx, &s->afq);
  225. /* create header packet bytes from header struct */
  226. /* note: libspeex allocates the memory for header_data, which is freed
  227. below with speex_header_free() */
  228. header_data = speex_header_to_packet(&s->header, &header_size);
  229. /* allocate extradata and coded_frame */
  230. avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
  231. if (!avctx->extradata) {
  232. speex_header_free(header_data);
  233. speex_encoder_destroy(s->enc_state);
  234. av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
  235. return AVERROR(ENOMEM);
  236. }
  237. /* copy header packet to extradata */
  238. memcpy(avctx->extradata, header_data, header_size);
  239. avctx->extradata_size = header_size;
  240. speex_header_free(header_data);
  241. /* init libspeex bitwriter */
  242. speex_bits_init(&s->bits);
  243. print_enc_params(avctx, s);
  244. return 0;
  245. }
  246. static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  247. const AVFrame *frame, int *got_packet_ptr)
  248. {
  249. LibSpeexEncContext *s = avctx->priv_data;
  250. int16_t *samples = frame ? (int16_t *)frame->data[0] : NULL;
  251. int ret;
  252. if (samples) {
  253. /* encode Speex frame */
  254. if (avctx->channels == 2)
  255. speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
  256. speex_encode_int(s->enc_state, samples, &s->bits);
  257. s->pkt_frame_count++;
  258. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  259. return ret;
  260. } else {
  261. /* handle end-of-stream */
  262. if (!s->pkt_frame_count)
  263. return 0;
  264. /* add extra terminator codes for unused frames in last packet */
  265. while (s->pkt_frame_count < s->frames_per_packet) {
  266. speex_bits_pack(&s->bits, 15, 5);
  267. s->pkt_frame_count++;
  268. }
  269. }
  270. /* write output if all frames for the packet have been encoded */
  271. if (s->pkt_frame_count == s->frames_per_packet) {
  272. s->pkt_frame_count = 0;
  273. if ((ret = ff_alloc_packet2(avctx, avpkt, speex_bits_nbytes(&s->bits))) < 0)
  274. return ret;
  275. ret = speex_bits_write(&s->bits, avpkt->data, avpkt->size);
  276. speex_bits_reset(&s->bits);
  277. /* Get the next frame pts/duration */
  278. ff_af_queue_remove(&s->afq, s->frames_per_packet * avctx->frame_size,
  279. &avpkt->pts, &avpkt->duration);
  280. avpkt->size = ret;
  281. *got_packet_ptr = 1;
  282. return 0;
  283. }
  284. return 0;
  285. }
  286. static av_cold int encode_close(AVCodecContext *avctx)
  287. {
  288. LibSpeexEncContext *s = avctx->priv_data;
  289. speex_bits_destroy(&s->bits);
  290. speex_encoder_destroy(s->enc_state);
  291. ff_af_queue_close(&s->afq);
  292. av_freep(&avctx->extradata);
  293. return 0;
  294. }
  295. #define OFFSET(x) offsetof(LibSpeexEncContext, x)
  296. #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  297. static const AVOption options[] = {
  298. { "abr", "Use average bit rate", OFFSET(abr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AE },
  299. { "cbr_quality", "Set quality value (0 to 10) for CBR", OFFSET(cbr_quality), AV_OPT_TYPE_INT, { .i64 = 8 }, 0, 10, AE },
  300. { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, 8, AE },
  301. { "vad", "Voice Activity Detection", OFFSET(vad), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AE },
  302. { "dtx", "Discontinuous Transmission", OFFSET(dtx), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AE },
  303. { NULL },
  304. };
  305. static const AVClass speex_class = {
  306. .class_name = "libspeex",
  307. .item_name = av_default_item_name,
  308. .option = options,
  309. .version = LIBAVUTIL_VERSION_INT,
  310. };
  311. static const AVCodecDefault defaults[] = {
  312. { "b", "0" },
  313. { "compression_level", "3" },
  314. { NULL },
  315. };
  316. AVCodec ff_libspeex_encoder = {
  317. .name = "libspeex",
  318. .long_name = NULL_IF_CONFIG_SMALL("libspeex Speex"),
  319. .type = AVMEDIA_TYPE_AUDIO,
  320. .id = AV_CODEC_ID_SPEEX,
  321. .priv_data_size = sizeof(LibSpeexEncContext),
  322. .init = encode_init,
  323. .encode2 = encode_frame,
  324. .close = encode_close,
  325. .capabilities = CODEC_CAP_DELAY,
  326. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  327. AV_SAMPLE_FMT_NONE },
  328. .channel_layouts = (const uint64_t[]){ AV_CH_LAYOUT_MONO,
  329. AV_CH_LAYOUT_STEREO,
  330. 0 },
  331. .supported_samplerates = (const int[]){ 8000, 16000, 32000, 0 },
  332. .priv_class = &speex_class,
  333. .defaults = defaults,
  334. };