1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
//! Audio transcoder.
//!
//! This module contains just a convenience struct combining
//! audio decoder/resampler/encoder into a single pipeline.

use std::collections::VecDeque;

use crate::Error;

use crate::{
    codec::{
        audio::{
            AudioDecoder, AudioDecoderBuilder, AudioEncoder, AudioEncoderBuilder, AudioFrame,
            AudioResampler,
        },
        AudioCodecParameters, CodecError, Decoder, Encoder,
    },
    packet::Packet,
    time::TimeBase,
};

/// Builder for the AudioTranscoder.
pub struct AudioTranscoderBuilder {
    input: AudioCodecParameters,
    output: AudioCodecParameters,

    decoder_builder: AudioDecoderBuilder,
    encoder_builder: AudioEncoderBuilder,
}

impl AudioTranscoderBuilder {
    /// Create a new builder.
    fn new(input: AudioCodecParameters, output: AudioCodecParameters) -> Result<Self, Error> {
        let decoder_builder = AudioDecoder::from_codec_parameters(&input)?;
        let encoder_builder = AudioEncoder::from_codec_parameters(&output)?;

        let res = Self {
            input,
            output,

            decoder_builder,
            encoder_builder,
        };

        Ok(res)
    }

    /// Set a decoder option.
    pub fn set_decoder_option<V>(mut self, name: &str, value: V) -> Self
    where
        V: ToString,
    {
        self.decoder_builder = self.decoder_builder.set_option(name, value);
        self
    }

    /// Set an encoder option.
    pub fn set_encoder_option<V>(mut self, name: &str, value: V) -> Self
    where
        V: ToString,
    {
        self.encoder_builder = self.encoder_builder.set_option(name, value);
        self
    }

    /// Build the transcoder.
    pub fn build(self) -> Result<AudioTranscoder, Error> {
        let decoder = self
            .decoder_builder
            .time_base(TimeBase::new(1, self.input.sample_rate()))
            .build()?;

        let encoder = self
            .encoder_builder
            .time_base(TimeBase::new(1, self.output.sample_rate()))
            .build()?;

        let source_channel_layout = self.input.channel_layout();
        let target_channel_layout = self.output.channel_layout();

        let resampler = AudioResampler::builder()
            .source_channel_layout(source_channel_layout.to_owned())
            .source_sample_format(self.input.sample_format())
            .source_sample_rate(self.input.sample_rate())
            .target_channel_layout(target_channel_layout.to_owned())
            .target_sample_format(self.output.sample_format())
            .target_sample_rate(self.output.sample_rate())
            .target_frame_samples(encoder.samples_per_frame())
            .build()?;

        let res = AudioTranscoder {
            audio_decoder: decoder,
            audio_encoder: encoder,
            audio_resampler: resampler,

            ready: VecDeque::new(),
        };

        Ok(res)
    }
}

/// Audio transcoder.
///
/// # Transcoder operation
/// 1. Push a packet to the transcoder.
/// 2. Take all packets from the transcoder until you get None.
/// 3. If there are more packets to be transcoded, continue with 1.
/// 4. Flush the transcoder.
/// 5. Take all packets from the transcoder until you get None.
pub struct AudioTranscoder {
    audio_decoder: AudioDecoder,
    audio_encoder: AudioEncoder,
    audio_resampler: AudioResampler,

    ready: VecDeque<Packet>,
}

impl AudioTranscoder {
    /// Create a new transcoder for a given input and output.
    pub fn new(
        input: AudioCodecParameters,
        output: AudioCodecParameters,
    ) -> Result<AudioTranscoder, Error> {
        AudioTranscoderBuilder::new(input, output)?.build()
    }

    /// Create a new transcoder builder for a given input and output.
    pub fn builder(
        input: AudioCodecParameters,
        output: AudioCodecParameters,
    ) -> Result<AudioTranscoderBuilder, Error> {
        AudioTranscoderBuilder::new(input, output)
    }

    /// Get codec parameters of the transcoded stream.
    pub fn codec_parameters(&self) -> AudioCodecParameters {
        self.audio_encoder.codec_parameters()
    }

    /// Push a given packet to the transcoder.
    ///
    /// # Panics
    /// The method panics if the operation is not expected (i.e. another
    /// operation needs to be done).
    pub fn push(&mut self, packet: Packet) -> Result<(), Error> {
        self.try_push(packet).map_err(|err| err.unwrap_inner())
    }

    /// Push a given packet to the transcoder.
    pub fn try_push(&mut self, packet: Packet) -> Result<(), CodecError> {
        if !self.ready.is_empty() {
            return Err(CodecError::again(
                "take all transcoded packets before pushing another packet for transcoding",
            ));
        }

        self.push_to_decoder(packet)?;

        Ok(())
    }

    /// Flush the transcoder.
    ///
    /// # Panics
    /// The method panics if the operation is not expected (i.e. another
    /// operation needs to be done).
    pub fn flush(&mut self) -> Result<(), Error> {
        self.try_flush().map_err(|err| err.unwrap_inner())
    }

    /// Flush the transcoder.
    pub fn try_flush(&mut self) -> Result<(), CodecError> {
        if !self.ready.is_empty() {
            return Err(CodecError::again(
                "take all transcoded packets before flushing the transcoder",
            ));
        }

        self.flush_decoder()?;
        self.flush_resampler()?;
        self.flush_encoder()?;

        Ok(())
    }

    /// Take the next packet from the transcoder.
    pub fn take(&mut self) -> Result<Option<Packet>, Error> {
        Ok(self.ready.pop_front())
    }

    /// Push a given packet to the internal decoder, take all decoded frames
    /// and pass them to the push_to_resampler method.
    fn push_to_decoder(&mut self, packet: Packet) -> Result<(), CodecError> {
        self.audio_decoder.try_push(packet)?;

        while let Some(frame) = self.audio_decoder.take()? {
            // XXX: this is to skip the initial padding; a correct solution
            // would be to skip a given number of samples
            if frame.pts().timestamp() >= 0 {
                self.push_to_resampler(frame)?;
            }
        }

        Ok(())
    }

    /// Push a given frame to the internal resampler, take all resampled frames
    /// and pass them to the push_to_encoder method.
    fn push_to_resampler(&mut self, frame: AudioFrame) -> Result<(), CodecError> {
        self.audio_resampler.try_push(frame)?;

        while let Some(frame) = self.audio_resampler.take()? {
            self.push_to_encoder(frame)?;
        }

        Ok(())
    }

    /// Push a given frame to the internal encoder, take all encoded packets
    /// and push them to the internal ready queue.
    fn push_to_encoder(&mut self, frame: AudioFrame) -> Result<(), CodecError> {
        self.audio_encoder.try_push(frame)?;

        while let Some(packet) = self.audio_encoder.take()? {
            self.push_to_output(packet);
        }

        Ok(())
    }

    /// Push a given packet to the output buffer.
    fn push_to_output(&mut self, packet: Packet) {
        self.ready.push_back(packet);
    }

    /// Flush the internal decoder, take all decoded frames and pass them to
    /// the push_to_resampler method.
    fn flush_decoder(&mut self) -> Result<(), CodecError> {
        self.audio_decoder.try_flush()?;

        while let Some(frame) = self.audio_decoder.take()? {
            self.push_to_resampler(frame)?;
        }

        Ok(())
    }

    /// Flush the internal resampler, take all resampled frames and pass them
    /// to the push_to_encoder method.
    fn flush_resampler(&mut self) -> Result<(), CodecError> {
        self.audio_resampler.try_flush()?;

        while let Some(frame) = self.audio_resampler.take()? {
            self.push_to_encoder(frame)?;
        }

        Ok(())
    }

    /// Flush the internal encoder, take all encoded packets and push them into
    /// the internal ready queue.
    fn flush_encoder(&mut self) -> Result<(), CodecError> {
        self.audio_encoder.try_flush()?;

        while let Some(packet) = self.audio_encoder.take()? {
            self.push_to_output(packet);
        }

        Ok(())
    }
}