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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Symphonia
// Copyright (c) 2019 The Project Symphonia Developers.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

#![warn(rust_2018_idioms)]
#![forbid(unsafe_code)]

use symphonia_core::support_codec;

use symphonia_core::audio::{AudioBuffer, AudioBufferRef, AsAudioBufferRef, Signal, SignalSpec};
use symphonia_core::codecs::{CodecParameters, CodecDescriptor, Decoder, DecoderOptions};
// Signed Int PCM codecs
use symphonia_core::codecs::{CODEC_TYPE_PCM_S8, CODEC_TYPE_PCM_S16LE};
use symphonia_core::codecs::{CODEC_TYPE_PCM_S24LE, CODEC_TYPE_PCM_S32LE};
use symphonia_core::codecs::{CODEC_TYPE_PCM_S16BE, CODEC_TYPE_PCM_S24BE, CODEC_TYPE_PCM_S32BE};
// Unsigned Int PCM codecs
use symphonia_core::codecs::{CODEC_TYPE_PCM_U8, CODEC_TYPE_PCM_U16LE};
use symphonia_core::codecs::{CODEC_TYPE_PCM_U24LE, CODEC_TYPE_PCM_U32LE};
use symphonia_core::codecs::{CODEC_TYPE_PCM_U16BE, CODEC_TYPE_PCM_U24BE, CODEC_TYPE_PCM_U32BE};
// Floating point PCM codecs
use symphonia_core::codecs::{CODEC_TYPE_PCM_F32LE, CODEC_TYPE_PCM_F32BE};
use symphonia_core::codecs::{CODEC_TYPE_PCM_F64LE, CODEC_TYPE_PCM_F64BE};
// G711 ALaw and MuLaw PCM cdoecs.
use symphonia_core::codecs::{CODEC_TYPE_PCM_ALAW, CODEC_TYPE_PCM_MULAW};
use symphonia_core::conv::FromSample;
use symphonia_core::errors::{Result, unsupported_error};
use symphonia_core::formats::Packet;
use symphonia_core::io::ByteStream;

macro_rules! read_pcm_signed {
    ($buf:expr, $read:expr, $shift:expr) => {
        $buf.fill(| audio_planes, idx | -> Result<()> {
            for plane in audio_planes.planes() {
                plane[idx] = (($read as u32) << $shift) as i32;
            }
            Ok(())
        })
    };
}

macro_rules! read_pcm_unsigned {
    ($buf:expr, $read:expr, $shift:expr) => {
        $buf.fill(| audio_planes, idx | -> Result<()> {
            for plane in audio_planes.planes() {
                plane[idx] = (($read as u32) << $shift).wrapping_add(0x80000000) as i32
            }
            Ok(())
        })
    };
}

macro_rules! read_pcm_floating {
    ($buf:expr, $read:expr) => {
        $buf.fill(| audio_planes, idx | -> Result<()> {
            for plane in audio_planes.planes() {
                plane[idx] = i32::from_sample($read);
            }
            Ok(())
        })
    };
}

macro_rules! read_pcm_transfer_func {
    ($buf:expr, $func:expr) => {
        $buf.fill(| audio_planes, idx | -> Result<()> {
            for plane in audio_planes.planes() {
                plane[idx] = i32::from_sample($func);
            }
            Ok(())
        })
    };
}

// alaw_to_linear and mulaw_to_linear are adaptations of alaw2linear and ulaw2linear from g711.c by
// SUN Microsystems (unrestricted use license).
const XLAW_QUANT_MASK: u8 = 0x0f;
const XLAW_SEG_MASK: u8   = 0x70;
const XLAW_SEG_SHIFT: u32 = 4;

fn alaw_to_linear(mut a_val: u8) -> i16 {
    a_val ^= 0x55;

    let mut t = i16::from((a_val & XLAW_QUANT_MASK) << 4);
    let seg = (a_val & XLAW_SEG_MASK) >> XLAW_SEG_SHIFT;

    match seg {
        0 => t += 0x8,
        1 => t += 0x108,
        _ => t = (t + 0x108) << (seg - 1),
    }

    if a_val & 0x80 == 0x80 { t } else { -t }
}

fn mulaw_to_linear(mut mu_val: u8) -> i16 {
    const BIAS: i16 = 0x84;

    // Complement to obtain normal u-law value.
    mu_val = !mu_val;

    // Extract and bias the quantization bits. Then shift up by the segment number and subtract out
    // the bias.
    let mut t = i16::from((mu_val & XLAW_QUANT_MASK) << 3) + BIAS;
    t <<= (mu_val & XLAW_SEG_MASK) >> XLAW_SEG_SHIFT;

    if mu_val & 0x80 == 0x80 { t - BIAS } else { BIAS - t }
}

/// `PcmDecoder` implements a decoder for all raw PCM, and log-PCM codecs.
pub struct PcmDecoder {
    params: CodecParameters,
    sample_width: u32,
    buf: AudioBuffer<i32>,
}

impl Decoder for PcmDecoder {

    fn try_new(params: &CodecParameters, _options: &DecoderOptions) -> Result<Self> {
        let frames = match params.max_frames_per_packet {
            Some(frames) => frames,
            _            => return unsupported_error("pcm: maximum frames per packet is required"),
        };

        let rate = match params.sample_rate {
            Some(rate) => rate,
            _          => return unsupported_error("pcm: sample rate is required")
        };

        let spec = if let Some(channels) = params.channels {
            SignalSpec::new(rate, channels)
        }
        else if let Some(layout) = params.channel_layout {
            SignalSpec::new_with_layout(rate, layout)
        }
        else {
            return unsupported_error("pcm: channels or channel_layout is required");
        };

        // Signed and unsigned integer PCM codecs require the coded sample bit-width to be known.
        // Try to get the bits per coded sample parameter, or, if failing that, the bits per
        // sample parameter.
        let sample_width = params.bits_per_coded_sample.unwrap_or_else(
            || params.bits_per_sample.unwrap_or(0));

        // If the width is not known, then the bits per coded sample may be constant and
        // implicit to the codec.
        if sample_width == 0 {
            // A-Law, Mu-Law, and floating point codecs have an implicit coded sample bit-width. If
            // the codec is none of those, then decoding is not possible.
            match params.codec {
                CODEC_TYPE_PCM_F32LE | CODEC_TYPE_PCM_F32BE => (),
                CODEC_TYPE_PCM_F64LE | CODEC_TYPE_PCM_F64BE => (),
                CODEC_TYPE_PCM_ALAW | CODEC_TYPE_PCM_MULAW => (),
                _ => return unsupported_error("pcm: unknown bits per (coded) sample."),
            }
        }

        Ok(PcmDecoder {
            params: params.clone(),
            sample_width,
            buf: AudioBuffer::new(frames, spec),
        })
    }

    fn supported_codecs() -> &'static [CodecDescriptor] {
        &[
            support_codec!(
                CODEC_TYPE_PCM_S32LE,
                "pcm_s32le",
                "PCM Signed 32-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S32BE,
                "pcm_s32be",
                "PCM Signed 32-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S24LE,
                "pcm_s24le",
                "PCM Signed 24-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S24BE,
                "pcm_s24be",
                "PCM Signed 24-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S16LE,
                "pcm_s16le",
                "PCM Signed 16-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S16BE,
                "pcm_s16be",
                "PCM Signed 16-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_S8,
                "pcm_s8",
                "PCM Signed 8-bit Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U32LE,
                "pcm_u32le",
                "PCM Unsigned 32-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U32BE,
                "pcm_u32be",
                "PCM Unsigned 32-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U24LE,
                "pcm_u24le",
                "PCM Unsigned 24-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U24BE,
                "pcm_u24be",
                "PCM Unsigned 24-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U16LE,
                "pcm_u16le",
                "PCM Unsigned 16-bit Little-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U16BE,
                "pcm_u16be",
                "PCM Unsigned 16-bit Big-Endian Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_U8,
                "pcm_u8",
                "PCM Unsigned 8-bit Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_F32LE,
                "pcm_f32le",
                "PCM 32-bit Little-Endian Floating Point Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_F32BE,
                "pcm_f32be",
                "PCM 32-bit Big-Endian Floating Point Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_F64LE,
                "pcm_f64le",
                "PCM 64-bit Little-Endian Floating Point Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_F64BE,
                "pcm_f64be",
                "PCM 64-bit Big-Endian Floating Point Interleaved"
            ),
            support_codec!(
                CODEC_TYPE_PCM_ALAW ,
                "pcm_alaw" ,
                "PCM A-law"
            ),
            support_codec!(
                CODEC_TYPE_PCM_MULAW,
                "pcm_mulaw",
                "PCM Mu-law"
            ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S32LE_PLANAR,
            //     "pcm_s32le_planar",
            //     "PCM Signed 32-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S32BE_PLANAR,
            //     "pcm_s32be_planar",
            //     "PCM Signed 32-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S24LE_PLANAR,
            //     "pcm_s24le_planar",
            //     "PCM Signed 24-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S24BE_PLANAR,
            //     "pcm_s24be_planar",
            //     "PCM Signed 24-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S16LE_PLANAR,
            //     "pcm_s16le_planar",
            //     "PCM Signed 16-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S16BE_PLANAR,
            //     "pcm_s16be_planar",
            //     "PCM Signed 16-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_S8_PLANAR   ,
            //     "pcm_s8_planar"   ,
            //     "PCM Signed 8-bit Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U32LE_PLANAR,
            //     "pcm_u32le_planar",
            //     "PCM Unsigned 32-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U32BE_PLANAR,
            //     "pcm_u32be_planar",
            //     "PCM Unsigned 32-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U24LE_PLANAR,
            //     "pcm_u24le_planar",
            //     "PCM Unsigned 24-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U24BE_PLANAR,
            //     "pcm_u24be_planar",
            //     "PCM Unsigned 24-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U16LE_PLANAR,
            //     "pcm_u16le_planar",
            //     "PCM Unsigned 16-bit Little-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U16BE_PLANAR,
            //     "pcm_u16be_planar",
            //     "PCM Unsigned 16-bit Big-Endian Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_U8_PLANAR   ,
            //     "pcm_u8_planar"   ,
            //     "PCM Unsigned 8-bit Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_F32LE_PLANAR,
            //     "pcm_f32le_planar",
            //     "PCM 32-bit Little-Endian Floating Point Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_F32BE_PLANAR,
            //     "pcm_f32be_planar",
            //     "PCM 32-bit Big-Endian Floating Point Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_F64LE_PLANAR,
            //     "pcm_f64le_planar",
            //     "PCM 64-bit Little-Endian Floating Point Planar"
            // ),
            // support_codec!(
            //     CODEC_TYPE_PCM_F64BE_PLANAR,
            //     "pcm_f64be_planar",
            //     "PCM 64-bit Big-Endian Floating Point Planar"
            // ),
        ]
    }

    fn codec_params(&self) -> &CodecParameters {
        &self.params
    }

    fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
        let mut stream = packet.as_buf_stream();

        // Signed or unsigned integer PCM codecs must be shifted to expand the sample into the
        // entire i32 range. Only floating point samples may exceed 32 bits per coded sample, but
        // they cannot be shifted, so int_shift = 0.
        let int_shift = if self.sample_width <= 32 { 32 - self.sample_width } else { 0 };

        let _ = match self.params.codec {
            CODEC_TYPE_PCM_S32LE => read_pcm_signed!(self.buf,   stream.read_u32()?,    int_shift),
            CODEC_TYPE_PCM_S32BE => read_pcm_signed!(self.buf,   stream.read_be_u32()?, int_shift),
            CODEC_TYPE_PCM_S24LE => read_pcm_signed!(self.buf,   stream.read_u24()?,    int_shift),
            CODEC_TYPE_PCM_S24BE => read_pcm_signed!(self.buf,   stream.read_be_u24()?, int_shift),
            CODEC_TYPE_PCM_S16LE => read_pcm_signed!(self.buf,   stream.read_u16()?,    int_shift),
            CODEC_TYPE_PCM_S16BE => read_pcm_signed!(self.buf,   stream.read_be_u16()?, int_shift),
            CODEC_TYPE_PCM_S8    => read_pcm_signed!(self.buf,   stream.read_u8()?,     int_shift),
            CODEC_TYPE_PCM_U32LE => read_pcm_unsigned!(self.buf, stream.read_u32()?,    int_shift),
            CODEC_TYPE_PCM_U32BE => read_pcm_unsigned!(self.buf, stream.read_be_u32()?, int_shift),
            CODEC_TYPE_PCM_U24LE => read_pcm_unsigned!(self.buf, stream.read_u24()?,    int_shift),
            CODEC_TYPE_PCM_U24BE => read_pcm_unsigned!(self.buf, stream.read_be_u24()?, int_shift),
            CODEC_TYPE_PCM_U16LE => read_pcm_unsigned!(self.buf, stream.read_u16()?,    int_shift),
            CODEC_TYPE_PCM_U16BE => read_pcm_unsigned!(self.buf, stream.read_be_u16()?, int_shift),
            CODEC_TYPE_PCM_U8    => read_pcm_unsigned!(self.buf, stream.read_u8()?,     int_shift),
            CODEC_TYPE_PCM_F32LE => read_pcm_floating!(self.buf, stream.read_f32()?),
            CODEC_TYPE_PCM_F32BE => read_pcm_floating!(self.buf, stream.read_be_f32()?),
            CODEC_TYPE_PCM_F64LE => read_pcm_floating!(self.buf, stream.read_f64()?),
            CODEC_TYPE_PCM_F64BE => read_pcm_floating!(self.buf, stream.read_be_f64()?),
            CODEC_TYPE_PCM_ALAW  => {
                read_pcm_transfer_func!(self.buf, alaw_to_linear(stream.read_u8()?))
            },
            CODEC_TYPE_PCM_MULAW => {
                read_pcm_transfer_func!(self.buf, mulaw_to_linear(stream.read_u8()?))
            },
            // CODEC_TYPE_PCM_S32LE_PLANAR =>
            // CODEC_TYPE_PCM_S32BE_PLANAR =>
            // CODEC_TYPE_PCM_S24LE_PLANAR =>
            // CODEC_TYPE_PCM_S24BE_PLANAR =>
            // CODEC_TYPE_PCM_S16LE_PLANAR =>
            // CODEC_TYPE_PCM_S16BE_PLANAR =>
            // CODEC_TYPE_PCM_S8_PLANAR    =>
            // CODEC_TYPE_PCM_U32LE_PLANAR =>
            // CODEC_TYPE_PCM_U32BE_PLANAR =>
            // CODEC_TYPE_PCM_U24LE_PLANAR =>
            // CODEC_TYPE_PCM_U24BE_PLANAR =>
            // CODEC_TYPE_PCM_U16LE_PLANAR =>
            // CODEC_TYPE_PCM_U16BE_PLANAR =>
            // CODEC_TYPE_PCM_U8_PLANAR    =>
            // CODEC_TYPE_PCM_F32LE_PLANAR =>
            // CODEC_TYPE_PCM_F32BE_PLANAR =>
            // CODEC_TYPE_PCM_F64LE_PLANAR =>
            // CODEC_TYPE_PCM_F64BE_PLANAR =>
            _ => return unsupported_error("pcm: codec is unsupported.")
        };

        Ok(self.buf.as_audio_buffer_ref())
    }

    fn close(&mut self) {
        // Intentionally left empty.
    }
}