Another try at sorting out the thorny question of timing.
[dcpomatic.git] / src / lib / resampler.cc
1 extern "C" {
2 #include "libavutil/channel_layout.h"
3 }       
4 #include "resampler.h"
5 #include "audio_buffers.h"
6 #include "exceptions.h"
7
8 #include "i18n.h"
9
10 using boost::shared_ptr;
11
12 Resampler::Resampler (int in, int out, int channels)
13         : _in_rate (in)
14         , _out_rate (out)
15         , _channels (channels)
16 {
17         /* We will be using planar float data when we call the
18            resampler.  As far as I can see, the audio channel
19            layout is not necessary for our purposes; it seems
20            only to be used get the number of channels and
21            decide if rematrixing is needed.  It won't be, since
22            input and output layouts are the same.
23         */
24
25         _swr_context = swr_alloc_set_opts (
26                 0,
27                 av_get_default_channel_layout (_channels),
28                 AV_SAMPLE_FMT_FLTP,
29                 _out_rate,
30                 av_get_default_channel_layout (_channels),
31                 AV_SAMPLE_FMT_FLTP,
32                 _in_rate,
33                 0, 0
34                 );
35         
36         swr_init (_swr_context);
37 }
38
39 Resampler::~Resampler ()
40 {
41         swr_free (&_swr_context);
42 }
43
44 shared_ptr<const AudioBuffers>
45 Resampler::run (shared_ptr<const AudioBuffers> in)
46 {
47         /* Compute the resampled frames count and add 32 for luck */
48         int const max_resampled_frames = ceil ((double) in->frames() * _out_rate / _in_rate) + 32;
49         shared_ptr<AudioBuffers> resampled (new AudioBuffers (_channels, max_resampled_frames));
50
51         int const resampled_frames = swr_convert (
52                 _swr_context, (uint8_t **) resampled->data(), max_resampled_frames, (uint8_t const **) in->data(), in->frames()
53                 );
54         
55         if (resampled_frames < 0) {
56                 throw EncodeError (_("could not run sample-rate converter"));
57         }
58         
59         resampled->set_frames (resampled_frames);
60         return resampled;
61 }