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.

325 lines
12KB

  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/mathematics.h"
  69. #include "libavutil/opt.h"
  70. #include "avcodec.h"
  71. #include "internal.h"
  72. typedef struct {
  73. AVClass *class; ///< AVClass for private options
  74. SpeexBits bits; ///< libspeex bitwriter context
  75. SpeexHeader header; ///< libspeex header struct
  76. void *enc_state; ///< libspeex encoder state
  77. int frames_per_packet; ///< number of frames to encode in each packet
  78. float vbr_quality; ///< VBR quality 0.0 to 10.0
  79. int cbr_quality; ///< CBR quality 0 to 10
  80. int abr; ///< flag to enable ABR
  81. int pkt_frame_count; ///< frame count for the current packet
  82. int lookahead; ///< encoder delay
  83. int sample_count; ///< total sample count (used for pts)
  84. } LibSpeexEncContext;
  85. static av_cold void print_enc_params(AVCodecContext *avctx,
  86. LibSpeexEncContext *s)
  87. {
  88. const char *mode_str = "unknown";
  89. av_log(avctx, AV_LOG_DEBUG, "channels: %d\n", avctx->channels);
  90. switch (s->header.mode) {
  91. case SPEEX_MODEID_NB: mode_str = "narrowband"; break;
  92. case SPEEX_MODEID_WB: mode_str = "wideband"; break;
  93. case SPEEX_MODEID_UWB: mode_str = "ultra-wideband"; break;
  94. }
  95. av_log(avctx, AV_LOG_DEBUG, "mode: %s\n", mode_str);
  96. if (s->header.vbr) {
  97. av_log(avctx, AV_LOG_DEBUG, "rate control: VBR\n");
  98. av_log(avctx, AV_LOG_DEBUG, " quality: %f\n", s->vbr_quality);
  99. } else if (s->abr) {
  100. av_log(avctx, AV_LOG_DEBUG, "rate control: ABR\n");
  101. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  102. } else {
  103. av_log(avctx, AV_LOG_DEBUG, "rate control: CBR\n");
  104. av_log(avctx, AV_LOG_DEBUG, " bitrate: %d bps\n", avctx->bit_rate);
  105. }
  106. av_log(avctx, AV_LOG_DEBUG, "complexity: %d\n",
  107. avctx->compression_level);
  108. av_log(avctx, AV_LOG_DEBUG, "frame size: %d samples\n",
  109. avctx->frame_size);
  110. av_log(avctx, AV_LOG_DEBUG, "frames per packet: %d\n",
  111. s->frames_per_packet);
  112. av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
  113. avctx->frame_size * s->frames_per_packet);
  114. }
  115. static av_cold int encode_init(AVCodecContext *avctx)
  116. {
  117. LibSpeexEncContext *s = avctx->priv_data;
  118. const SpeexMode *mode;
  119. uint8_t *header_data;
  120. int header_size;
  121. int32_t complexity;
  122. /* channels */
  123. if (avctx->channels < 1 || avctx->channels > 2) {
  124. av_log(avctx, AV_LOG_ERROR, "Invalid channels (%d). Only stereo and "
  125. "mono are supported\n", avctx->channels);
  126. return AVERROR(EINVAL);
  127. }
  128. /* sample rate and encoding mode */
  129. switch (avctx->sample_rate) {
  130. case 8000: mode = &speex_nb_mode; break;
  131. case 16000: mode = &speex_wb_mode; break;
  132. case 32000: mode = &speex_uwb_mode; break;
  133. default:
  134. av_log(avctx, AV_LOG_ERROR, "Sample rate of %d Hz is not supported. "
  135. "Resample to 8, 16, or 32 kHz.\n", avctx->sample_rate);
  136. return AVERROR(EINVAL);
  137. }
  138. /* initialize libspeex */
  139. s->enc_state = speex_encoder_init(mode);
  140. if (!s->enc_state) {
  141. av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex\n");
  142. return -1;
  143. }
  144. speex_init_header(&s->header, avctx->sample_rate, avctx->channels, mode);
  145. /* rate control method and parameters */
  146. if (avctx->flags & CODEC_FLAG_QSCALE) {
  147. /* VBR */
  148. s->header.vbr = 1;
  149. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
  150. s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
  151. 0.0f, 10.0f);
  152. speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR_QUALITY, &s->vbr_quality);
  153. } else {
  154. s->header.bitrate = avctx->bit_rate;
  155. if (avctx->bit_rate > 0) {
  156. /* CBR or ABR by bitrate */
  157. if (s->abr) {
  158. speex_encoder_ctl(s->enc_state, SPEEX_SET_ABR,
  159. &s->header.bitrate);
  160. speex_encoder_ctl(s->enc_state, SPEEX_GET_ABR,
  161. &s->header.bitrate);
  162. } else {
  163. speex_encoder_ctl(s->enc_state, SPEEX_SET_BITRATE,
  164. &s->header.bitrate);
  165. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  166. &s->header.bitrate);
  167. }
  168. } else {
  169. /* CBR by quality */
  170. speex_encoder_ctl(s->enc_state, SPEEX_SET_QUALITY,
  171. &s->cbr_quality);
  172. speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
  173. &s->header.bitrate);
  174. }
  175. /* stereo side information adds about 800 bps to the base bitrate */
  176. /* TODO: this should be calculated exactly */
  177. avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
  178. }
  179. /* set encoding complexity */
  180. if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
  181. complexity = av_clip(avctx->compression_level, 0, 10);
  182. speex_encoder_ctl(s->enc_state, SPEEX_SET_COMPLEXITY, &complexity);
  183. }
  184. speex_encoder_ctl(s->enc_state, SPEEX_GET_COMPLEXITY, &complexity);
  185. avctx->compression_level = complexity;
  186. /* set packet size */
  187. avctx->frame_size = s->header.frame_size;
  188. s->header.frames_per_packet = s->frames_per_packet;
  189. /* set encoding delay */
  190. speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &s->lookahead);
  191. s->sample_count = -s->lookahead;
  192. /* create header packet bytes from header struct */
  193. /* note: libspeex allocates the memory for header_data, which is freed
  194. below with speex_header_free() */
  195. header_data = speex_header_to_packet(&s->header, &header_size);
  196. /* allocate extradata and coded_frame */
  197. avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
  198. avctx->coded_frame = avcodec_alloc_frame();
  199. if (!avctx->extradata || !avctx->coded_frame) {
  200. speex_header_free(header_data);
  201. speex_encoder_destroy(s->enc_state);
  202. av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
  203. return AVERROR(ENOMEM);
  204. }
  205. /* copy header packet to extradata */
  206. memcpy(avctx->extradata, header_data, header_size);
  207. avctx->extradata_size = header_size;
  208. speex_header_free(header_data);
  209. /* init libspeex bitwriter */
  210. speex_bits_init(&s->bits);
  211. print_enc_params(avctx, s);
  212. return 0;
  213. }
  214. static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size,
  215. void *data)
  216. {
  217. LibSpeexEncContext *s = avctx->priv_data;
  218. int16_t *samples = data;
  219. int sample_count = s->sample_count;
  220. if (data) {
  221. /* encode Speex frame */
  222. if (avctx->channels == 2)
  223. speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
  224. speex_encode_int(s->enc_state, samples, &s->bits);
  225. s->pkt_frame_count++;
  226. s->sample_count += avctx->frame_size;
  227. } else {
  228. /* handle end-of-stream */
  229. if (!s->pkt_frame_count)
  230. return 0;
  231. /* add extra terminator codes for unused frames in last packet */
  232. while (s->pkt_frame_count < s->frames_per_packet) {
  233. speex_bits_pack(&s->bits, 15, 5);
  234. s->pkt_frame_count++;
  235. }
  236. }
  237. /* write output if all frames for the packet have been encoded */
  238. if (s->pkt_frame_count == s->frames_per_packet) {
  239. s->pkt_frame_count = 0;
  240. avctx->coded_frame->pts =
  241. av_rescale_q(sample_count, (AVRational){ 1, avctx->sample_rate },
  242. avctx->time_base);
  243. if (buf_size > speex_bits_nbytes(&s->bits)) {
  244. int ret = speex_bits_write(&s->bits, frame, buf_size);
  245. speex_bits_reset(&s->bits);
  246. return ret;
  247. } else {
  248. av_log(avctx, AV_LOG_ERROR, "output buffer too small");
  249. return AVERROR(EINVAL);
  250. }
  251. }
  252. return 0;
  253. }
  254. static av_cold int encode_close(AVCodecContext *avctx)
  255. {
  256. LibSpeexEncContext *s = avctx->priv_data;
  257. speex_bits_destroy(&s->bits);
  258. speex_encoder_destroy(s->enc_state);
  259. av_freep(&avctx->coded_frame);
  260. av_freep(&avctx->extradata);
  261. return 0;
  262. }
  263. #define OFFSET(x) offsetof(LibSpeexEncContext, x)
  264. #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  265. static const AVOption options[] = {
  266. { "abr", "Use average bit rate", OFFSET(abr), AV_OPT_TYPE_INT, { 0 }, 0, 1, AE },
  267. { "cbr_quality", "Set quality value (0 to 10) for CBR", OFFSET(cbr_quality), AV_OPT_TYPE_INT, { 8 }, 0, 10, AE },
  268. { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { 1 }, 1, 8, AE },
  269. { NULL },
  270. };
  271. static const AVClass class = {
  272. .class_name = "libspeex",
  273. .item_name = av_default_item_name,
  274. .option = options,
  275. .version = LIBAVUTIL_VERSION_INT,
  276. };
  277. static const AVCodecDefault defaults[] = {
  278. { "b", "0" },
  279. { "compression_level", "3" },
  280. { NULL },
  281. };
  282. AVCodec ff_libspeex_encoder = {
  283. .name = "libspeex",
  284. .type = AVMEDIA_TYPE_AUDIO,
  285. .id = CODEC_ID_SPEEX,
  286. .priv_data_size = sizeof(LibSpeexEncContext),
  287. .init = encode_init,
  288. .encode = encode_frame,
  289. .close = encode_close,
  290. .capabilities = CODEC_CAP_DELAY,
  291. .sample_fmts = (const enum SampleFormat[]){ AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
  292. .long_name = NULL_IF_CONFIG_SMALL("libspeex Speex"),
  293. .priv_class = &class,
  294. .defaults = defaults,
  295. };