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.

370 lines
14KB

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