/*1* Copyright (C) 2011-2013 Michael Niedermayer ([email protected])2*3* This file is part of libswresample4*5* libswresample is free software; you can redistribute it and/or6* modify it under the terms of the GNU Lesser General Public7* License as published by the Free Software Foundation; either8* version 2.1 of the License, or (at your option) any later version.9*10* libswresample is distributed in the hope that it will be useful,11* but WITHOUT ANY WARRANTY; without even the implied warranty of12* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU13* Lesser General Public License for more details.14*15* You should have received a copy of the GNU Lesser General Public16* License along with libswresample; if not, write to the Free Software17* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA18*/1920#ifndef SWRESAMPLE_SWRESAMPLE_H21#define SWRESAMPLE_SWRESAMPLE_H2223/**24* @file25* @ingroup lswr26* libswresample public header27*/2829/**30* @defgroup lswr Libswresample31* @{32*33* Libswresample (lswr) is a library that handles audio resampling, sample34* format conversion and mixing.35*36* Interaction with lswr is done through SwrContext, which is37* allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters38* must be set with the @ref avoptions API.39*40* The first thing you will need to do in order to use lswr is to allocate41* SwrContext. This can be done with swr_alloc() or swr_alloc_set_opts(). If you42* are using the former, you must set options through the @ref avoptions API.43* The latter function provides the same feature, but it allows you to set some44* common options in the same statement.45*46* For example the following code will setup conversion from planar float sample47* format to interleaved signed 16-bit integer, downsampling from 48kHz to48* 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing49* matrix). This is using the swr_alloc() function.50* @code51* SwrContext *swr = swr_alloc();52* av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_5POINT1, 0);53* av_opt_set_channel_layout(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);54* av_opt_set_int(swr, "in_sample_rate", 48000, 0);55* av_opt_set_int(swr, "out_sample_rate", 44100, 0);56* av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);57* av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);58* @endcode59*60* The same job can be done using swr_alloc_set_opts() as well:61* @code62* SwrContext *swr = swr_alloc_set_opts(NULL, // we're allocating a new context63* AV_CH_LAYOUT_STEREO, // out_ch_layout64* AV_SAMPLE_FMT_S16, // out_sample_fmt65* 44100, // out_sample_rate66* AV_CH_LAYOUT_5POINT1, // in_ch_layout67* AV_SAMPLE_FMT_FLTP, // in_sample_fmt68* 48000, // in_sample_rate69* 0, // log_offset70* NULL); // log_ctx71* @endcode72*73* Once all values have been set, it must be initialized with swr_init(). If74* you need to change the conversion parameters, you can change the parameters75* using @ref AVOptions, as described above in the first example; or by using76* swr_alloc_set_opts(), but with the first argument the allocated context.77* You must then call swr_init() again.78*79* The conversion itself is done by repeatedly calling swr_convert().80* Note that the samples may get buffered in swr if you provide insufficient81* output space or if sample rate conversion is done, which requires "future"82* samples. Samples that do not require future input can be retrieved at any83* time by using swr_convert() (in_count can be set to 0).84* At the end of conversion the resampling buffer can be flushed by calling85* swr_convert() with NULL in and 0 in_count.86*87* The samples used in the conversion process can be managed with the libavutil88* @ref lavu_sampmanip "samples manipulation" API, including av_samples_alloc()89* function used in the following example.90*91* The delay between input and output, can at any time be found by using92* swr_get_delay().93*94* The following code demonstrates the conversion loop assuming the parameters95* from above and caller-defined functions get_input() and handle_output():96* @code97* uint8_t **input;98* int in_samples;99*100* while (get_input(&input, &in_samples)) {101* uint8_t *output;102* int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) +103* in_samples, 44100, 48000, AV_ROUND_UP);104* av_samples_alloc(&output, NULL, 2, out_samples,105* AV_SAMPLE_FMT_S16, 0);106* out_samples = swr_convert(swr, &output, out_samples,107* input, in_samples);108* handle_output(output, out_samples);109* av_freep(&output);110* }111* @endcode112*113* When the conversion is finished, the conversion114* context and everything associated with it must be freed with swr_free().115* A swr_close() function is also available, but it exists mainly for116* compatibility with libavresample, and is not required to be called.117*118* There will be no memory leak if the data is not completely flushed before119* swr_free().120*/121122#include <stdint.h>123#include "libavutil/frame.h"124#include "libavutil/samplefmt.h"125126#include "libswresample/version.h"127128#if LIBSWRESAMPLE_VERSION_MAJOR < 1129#define SWR_CH_MAX 32 ///< Maximum number of channels130#endif131132/**133* @name Option constants134* These constants are used for the @ref avoptions interface for lswr.135* @{136*137*/138139#define SWR_FLAG_RESAMPLE 1 ///< Force resampling even if equal sample rate140//TODO use int resample ?141//long term TODO can we enable this dynamically?142143/** Dithering algorithms */144enum SwrDitherType {145SWR_DITHER_NONE = 0,146SWR_DITHER_RECTANGULAR,147SWR_DITHER_TRIANGULAR,148SWR_DITHER_TRIANGULAR_HIGHPASS,149150SWR_DITHER_NS = 64, ///< not part of API/ABI151SWR_DITHER_NS_LIPSHITZ,152SWR_DITHER_NS_F_WEIGHTED,153SWR_DITHER_NS_MODIFIED_E_WEIGHTED,154SWR_DITHER_NS_IMPROVED_E_WEIGHTED,155SWR_DITHER_NS_SHIBATA,156SWR_DITHER_NS_LOW_SHIBATA,157SWR_DITHER_NS_HIGH_SHIBATA,158SWR_DITHER_NB, ///< not part of API/ABI159};160161/** Resampling Engines */162enum SwrEngine {163SWR_ENGINE_SWR, /**< SW Resampler */164SWR_ENGINE_SOXR, /**< SoX Resampler */165SWR_ENGINE_NB, ///< not part of API/ABI166};167168/** Resampling Filter Types */169enum SwrFilterType {170SWR_FILTER_TYPE_CUBIC, /**< Cubic */171SWR_FILTER_TYPE_BLACKMAN_NUTTALL, /**< Blackman Nuttall windowed sinc */172SWR_FILTER_TYPE_KAISER, /**< Kaiser windowed sinc */173};174175/**176* @}177*/178179/**180* The libswresample context. Unlike libavcodec and libavformat, this structure181* is opaque. This means that if you would like to set options, you must use182* the @ref avoptions API and cannot directly set values to members of the183* structure.184*/185typedef struct SwrContext SwrContext;186187/**188* Get the AVClass for SwrContext. It can be used in combination with189* AV_OPT_SEARCH_FAKE_OBJ for examining options.190*191* @see av_opt_find().192* @return the AVClass of SwrContext193*/194const AVClass *swr_get_class(void);195196/**197* @name SwrContext constructor functions198* @{199*/200201/**202* Allocate SwrContext.203*204* If you use this function you will need to set the parameters (manually or205* with swr_alloc_set_opts()) before calling swr_init().206*207* @see swr_alloc_set_opts(), swr_init(), swr_free()208* @return NULL on error, allocated context otherwise209*/210struct SwrContext *swr_alloc(void);211212/**213* Initialize context after user parameters have been set.214* @note The context must be configured using the AVOption API.215*216* @see av_opt_set_int()217* @see av_opt_set_dict()218*219* @param[in,out] s Swr context to initialize220* @return AVERROR error code in case of failure.221*/222int swr_init(struct SwrContext *s);223224/**225* Check whether an swr context has been initialized or not.226*227* @param[in] s Swr context to check228* @see swr_init()229* @return positive if it has been initialized, 0 if not initialized230*/231int swr_is_initialized(struct SwrContext *s);232233/**234* Allocate SwrContext if needed and set/reset common parameters.235*236* This function does not require s to be allocated with swr_alloc(). On the237* other hand, swr_alloc() can use swr_alloc_set_opts() to set the parameters238* on the allocated context.239*240* @param s existing Swr context if available, or NULL if not241* @param out_ch_layout output channel layout (AV_CH_LAYOUT_*)242* @param out_sample_fmt output sample format (AV_SAMPLE_FMT_*).243* @param out_sample_rate output sample rate (frequency in Hz)244* @param in_ch_layout input channel layout (AV_CH_LAYOUT_*)245* @param in_sample_fmt input sample format (AV_SAMPLE_FMT_*).246* @param in_sample_rate input sample rate (frequency in Hz)247* @param log_offset logging level offset248* @param log_ctx parent logging context, can be NULL249*250* @see swr_init(), swr_free()251* @return NULL on error, allocated context otherwise252*/253struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,254int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate,255int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate,256int log_offset, void *log_ctx);257258/**259* @}260*261* @name SwrContext destructor functions262* @{263*/264265/**266* Free the given SwrContext and set the pointer to NULL.267*268* @param[in] s a pointer to a pointer to Swr context269*/270void swr_free(struct SwrContext **s);271272/**273* Closes the context so that swr_is_initialized() returns 0.274*275* The context can be brought back to life by running swr_init(),276* swr_init() can also be used without swr_close().277* This function is mainly provided for simplifying the usecase278* where one tries to support libavresample and libswresample.279*280* @param[in,out] s Swr context to be closed281*/282void swr_close(struct SwrContext *s);283284/**285* @}286*287* @name Core conversion functions288* @{289*/290291/** Convert audio.292*293* in and in_count can be set to 0 to flush the last few samples out at the294* end.295*296* If more input is provided than output space, then the input will be buffered.297* You can avoid this buffering by using swr_get_out_samples() to retrieve an298* upper bound on the required number of output samples for the given number of299* input samples. Conversion will run directly without copying whenever possible.300*301* @param s allocated Swr context, with parameters set302* @param out output buffers, only the first one need be set in case of packed audio303* @param out_count amount of space available for output in samples per channel304* @param in input buffers, only the first one need to be set in case of packed audio305* @param in_count number of input samples available in one channel306*307* @return number of samples output per channel, negative value on error308*/309int swr_convert(struct SwrContext *s, uint8_t **out, int out_count,310const uint8_t **in , int in_count);311312/**313* Convert the next timestamp from input to output314* timestamps are in 1/(in_sample_rate * out_sample_rate) units.315*316* @note There are 2 slightly differently behaving modes.317* @li When automatic timestamp compensation is not used, (min_compensation >= FLT_MAX)318* in this case timestamps will be passed through with delays compensated319* @li When automatic timestamp compensation is used, (min_compensation < FLT_MAX)320* in this case the output timestamps will match output sample numbers.321* See ffmpeg-resampler(1) for the two modes of compensation.322*323* @param s[in] initialized Swr context324* @param pts[in] timestamp for the next input sample, INT64_MIN if unknown325* @see swr_set_compensation(), swr_drop_output(), and swr_inject_silence() are326* function used internally for timestamp compensation.327* @return the output timestamp for the next output sample328*/329int64_t swr_next_pts(struct SwrContext *s, int64_t pts);330331/**332* @}333*334* @name Low-level option setting functions335* These functons provide a means to set low-level options that is not possible336* with the AVOption API.337* @{338*/339340/**341* Activate resampling compensation ("soft" compensation). This function is342* internally called when needed in swr_next_pts().343*344* @param[in,out] s allocated Swr context. If it is not initialized,345* or SWR_FLAG_RESAMPLE is not set, swr_init() is346* called with the flag set.347* @param[in] sample_delta delta in PTS per sample348* @param[in] compensation_distance number of samples to compensate for349* @return >= 0 on success, AVERROR error codes if:350* @li @c s is NULL,351* @li @c compensation_distance is less than 0,352* @li @c compensation_distance is 0 but sample_delta is not,353* @li compensation unsupported by resampler, or354* @li swr_init() fails when called.355*/356int swr_set_compensation(struct SwrContext *s, int sample_delta, int compensation_distance);357358/**359* Set a customized input channel mapping.360*361* @param[in,out] s allocated Swr context, not yet initialized362* @param[in] channel_map customized input channel mapping (array of channel363* indexes, -1 for a muted channel)364* @return >= 0 on success, or AVERROR error code in case of failure.365*/366int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map);367368/**369* Set a customized remix matrix.370*371* @param s allocated Swr context, not yet initialized372* @param matrix remix coefficients; matrix[i + stride * o] is373* the weight of input channel i in output channel o374* @param stride offset between lines of the matrix375* @return >= 0 on success, or AVERROR error code in case of failure.376*/377int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride);378379/**380* @}381*382* @name Sample handling functions383* @{384*/385386/**387* Drops the specified number of output samples.388*389* This function, along with swr_inject_silence(), is called by swr_next_pts()390* if needed for "hard" compensation.391*392* @param s allocated Swr context393* @param count number of samples to be dropped394*395* @return >= 0 on success, or a negative AVERROR code on failure396*/397int swr_drop_output(struct SwrContext *s, int count);398399/**400* Injects the specified number of silence samples.401*402* This function, along with swr_drop_output(), is called by swr_next_pts()403* if needed for "hard" compensation.404*405* @param s allocated Swr context406* @param count number of samples to be dropped407*408* @return >= 0 on success, or a negative AVERROR code on failure409*/410int swr_inject_silence(struct SwrContext *s, int count);411412/**413* Gets the delay the next input sample will experience relative to the next output sample.414*415* Swresample can buffer data if more input has been provided than available416* output space, also converting between sample rates needs a delay.417* This function returns the sum of all such delays.418* The exact delay is not necessarily an integer value in either input or419* output sample rate. Especially when downsampling by a large value, the420* output sample rate may be a poor choice to represent the delay, similarly421* for upsampling and the input sample rate.422*423* @param s swr context424* @param base timebase in which the returned delay will be:425* @li if it's set to 1 the returned delay is in seconds426* @li if it's set to 1000 the returned delay is in milliseconds427* @li if it's set to the input sample rate then the returned428* delay is in input samples429* @li if it's set to the output sample rate then the returned430* delay is in output samples431* @li if it's the least common multiple of in_sample_rate and432* out_sample_rate then an exact rounding-free delay will be433* returned434* @returns the delay in 1 / @c base units.435*/436int64_t swr_get_delay(struct SwrContext *s, int64_t base);437438/**439* Find an upper bound on the number of samples that the next swr_convert440* call will output, if called with in_samples of input samples. This441* depends on the internal state, and anything changing the internal state442* (like further swr_convert() calls) will may change the number of samples443* swr_get_out_samples() returns for the same number of input samples.444*445* @param in_samples number of input samples.446* @note any call to swr_inject_silence(), swr_convert(), swr_next_pts()447* or swr_set_compensation() invalidates this limit448* @note it is recommended to pass the correct available buffer size449* to all functions like swr_convert() even if swr_get_out_samples()450* indicates that less would be used.451* @returns an upper bound on the number of samples that the next swr_convert452* will output or a negative value to indicate an error453*/454int swr_get_out_samples(struct SwrContext *s, int in_samples);455456/**457* @}458*459* @name Configuration accessors460* @{461*/462463/**464* Return the @ref LIBSWRESAMPLE_VERSION_INT constant.465*466* This is useful to check if the build-time libswresample has the same version467* as the run-time one.468*469* @returns the unsigned int-typed version470*/471unsigned swresample_version(void);472473/**474* Return the swr build-time configuration.475*476* @returns the build-time @c ./configure flags477*/478const char *swresample_configuration(void);479480/**481* Return the swr license.482*483* @returns the license of libswresample, determined at build-time484*/485const char *swresample_license(void);486487/**488* @}489*490* @name AVFrame based API491* @{492*/493494/**495* Convert the samples in the input AVFrame and write them to the output AVFrame.496*497* Input and output AVFrames must have channel_layout, sample_rate and format set.498*499* If the output AVFrame does not have the data pointers allocated the nb_samples500* field will be set using av_frame_get_buffer()501* is called to allocate the frame.502*503* The output AVFrame can be NULL or have fewer allocated samples than required.504* In this case, any remaining samples not written to the output will be added505* to an internal FIFO buffer, to be returned at the next call to this function506* or to swr_convert().507*508* If converting sample rate, there may be data remaining in the internal509* resampling delay buffer. swr_get_delay() tells the number of510* remaining samples. To get this data as output, call this function or511* swr_convert() with NULL input.512*513* If the SwrContext configuration does not match the output and514* input AVFrame settings the conversion does not take place and depending on515* which AVFrame is not matching AVERROR_OUTPUT_CHANGED, AVERROR_INPUT_CHANGED516* or the result of a bitwise-OR of them is returned.517*518* @see swr_delay()519* @see swr_convert()520* @see swr_get_delay()521*522* @param swr audio resample context523* @param output output AVFrame524* @param input input AVFrame525* @return 0 on success, AVERROR on failure or nonmatching526* configuration.527*/528int swr_convert_frame(SwrContext *swr,529AVFrame *output, const AVFrame *input);530531/**532* Configure or reconfigure the SwrContext using the information533* provided by the AVFrames.534*535* The original resampling context is reset even on failure.536* The function calls swr_close() internally if the context is open.537*538* @see swr_close();539*540* @param swr audio resample context541* @param output output AVFrame542* @param input input AVFrame543* @return 0 on success, AVERROR on failure.544*/545int swr_config_frame(SwrContext *swr, const AVFrame *out, const AVFrame *in);546547/**548* @}549* @}550*/551552#endif /* SWRESAMPLE_SWRESAMPLE_H */553554555