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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use crate::error::Error;

use ffmpeg4_sys::{
    self, av_frame_alloc, av_frame_free, av_frame_unref, av_freep, av_get_alt_sample_fmt,
    av_get_bytes_per_sample, av_get_channel_layout_nb_channels, av_get_sample_fmt_name,
    av_init_packet, av_packet_unref, av_read_frame, av_register_all, av_sample_fmt_is_planar,
    av_samples_alloc, av_samples_get_buffer_size, avcodec_alloc_context3, avcodec_close,
    avcodec_find_decoder, avcodec_free_context, avcodec_open2, avcodec_parameters_to_context,
    avcodec_receive_frame, avcodec_send_packet, avformat_close_input, avformat_find_stream_info,
    avformat_open_input, swr_alloc_set_opts, swr_convert, swr_get_out_samples, swr_init, AVCodec,
    AVCodecContext, AVFormatContext, AVFrame, AVMediaType, AVPacket, AVSampleFormat, AVStream,
};
use std::ffi::{CStr, CString};
use std::path::Path;
use std::ptr;
use std::slice;
use std::time::Duration;

use log::{error, info};

const AVERROR_EOF: i32 = -0x20_464_F45;
const AVERROR_EAGAIN: i32 = -11;
const AVERROR_EDEADLK: i32 = -35;
const DEFAULT_CONVERSION_FORMAT: AVSampleFormat = AVSampleFormat::AV_SAMPLE_FMT_S16;

pub struct Decoder {
    format_ctx: FormatContext,
    stream: Stream,
    codec_ctx: CodecContext,
    frame: Frame,
    packet: Packet,
    swr_ctx: Option<SwrContext>,
    current_frame: Vec<u8>,
    first_frame_stored: bool,
}

impl Decoder {
    pub fn open(path: impl AsRef<Path>) -> Result<Decoder, Error> {
        unsafe { av_register_all() };

        // Open the file and get the format context
        let format_ctx = FormatContext::open(&path.as_ref().display().to_string())?;

        // Find first audio stream in file
        format_ctx.find_stream_info()?;
        let stream = format_ctx.get_audio_stream()?;

        // Get the streams codec
        let codec = stream.get_codec()?;

        // Setup codec context and intialize
        let codec_ctx = codec.get_context()?;
        codec_ctx.copy_parameters_from_stream(&stream)?;
        codec_ctx.request_non_planar_format();
        codec_ctx.initialize()?;

        print_codec_info(&codec_ctx);

        // Allocate frame
        let frame = Frame::new()?;

        // Initialize packet
        let packet = Packet::new();

        // Initialize swr context, if conversion is needed
        let swr_ctx = if codec_ctx.sample_format() != DEFAULT_CONVERSION_FORMAT {
            Some(SwrContext::new(&codec_ctx)?)
        } else {
            None
        };

        Ok(Decoder {
            format_ctx,
            stream,
            codec_ctx,
            frame,
            packet,
            swr_ctx,
            current_frame: vec![],
            first_frame_stored: false,
        })
    }

    fn read_next_frame(&mut self) -> ReadFrameStatus {
        let status =
            unsafe { av_read_frame(self.format_ctx.inner, self.packet.inner.as_mut_ptr()) };

        match status {
            AVERROR_EOF => ReadFrameStatus::Eof,
            _ if status != 0 => ReadFrameStatus::Other(status),
            _ => ReadFrameStatus::Ok,
        }
    }

    fn send_packet_for_decoding(&mut self) -> SendPacketStatus {
        let status =
            unsafe { avcodec_send_packet(self.codec_ctx.inner, self.packet.inner.as_mut_ptr()) };

        match status {
            0 => SendPacketStatus::Ok,
            _ => SendPacketStatus::Other(status),
        }
    }

    fn receive_decoded_frame(&self) -> ReceiveFrameStatus {
        let status = unsafe { avcodec_receive_frame(self.codec_ctx.inner, self.frame.inner) };

        match status {
            0 => ReceiveFrameStatus::Ok,
            AVERROR_EAGAIN => ReceiveFrameStatus::Again,
            AVERROR_EDEADLK => ReceiveFrameStatus::Deadlk,
            _ => ReceiveFrameStatus::Other(status),
        }
    }

    fn convert_and_store_frame(&mut self) {
        let num_samples = self.frame.num_samples();
        let channel_layout = self.frame.channel_layout();
        let num_channels = unsafe { av_get_channel_layout_nb_channels(channel_layout) };

        let extended_data = self.frame.extended_data();

        let mut out_buf = std::ptr::null_mut::<u8>();

        let out_slice = if self.swr_ctx.is_some() {
            let out_samples =
                unsafe { swr_get_out_samples(self.swr_ctx.as_ref().unwrap().inner, num_samples) };

            unsafe {
                av_samples_alloc(
                    &mut out_buf,
                    ptr::null_mut(),
                    num_channels,
                    out_samples,
                    DEFAULT_CONVERSION_FORMAT,
                    0,
                )
            };

            unsafe {
                swr_convert(
                    self.swr_ctx.as_ref().unwrap().inner,
                    &mut out_buf,
                    out_samples,
                    extended_data,
                    num_samples,
                )
            };

            let out_size = unsafe {
                av_samples_get_buffer_size(
                    ptr::null_mut(),
                    num_channels,
                    out_samples,
                    DEFAULT_CONVERSION_FORMAT,
                    0,
                )
            };

            let out_slice = unsafe { slice::from_raw_parts(out_buf, out_size as usize) };

            out_slice
        } else {
            unsafe {
                slice::from_raw_parts(
                    extended_data.as_ref().unwrap().as_ref().unwrap(),
                    self.frame.inner.as_ref().unwrap().linesize[0] as usize,
                )
            }
        };

        if !self.current_frame.is_empty() {
            self.current_frame.drain(..);
        }

        self.current_frame.extend_from_slice(out_slice);

        if self.swr_ctx.is_some() {
            // Free samples buffer
            unsafe { av_freep(&mut out_buf as *mut _ as _) };
        }

        unsafe { av_frame_unref(self.frame.inner) };
    }

    fn frame_for_stream(&self) -> bool {
        unsafe { self.packet.inner.as_ptr().as_ref().unwrap().stream_index == self.stream.index }
    }

    fn reset_packet(&mut self) {
        unsafe { av_packet_unref(self.packet.inner.as_mut_ptr()) };
    }

    fn next_sample(&mut self) -> i16 {
        let sample_u8: [u8; 2] = [self.current_frame.remove(0), self.current_frame.remove(0)];

        ((sample_u8[1] as i16) << 8) | sample_u8[0] as i16
    }

    fn process_next_frame(&mut self) -> Option<Result<(), Error>> {
        match self.read_next_frame() {
            ReadFrameStatus::Ok => {}
            ReadFrameStatus::Eof => {
                return None;
            }
            ReadFrameStatus::Other(status) => {
                error!("{}", Error::ReadFrame(status));
                return None;
            }
        }

        if !self.frame_for_stream() {
            self.reset_packet();
            return self.process_next_frame();
        }

        match self.send_packet_for_decoding() {
            SendPacketStatus::Ok => self.reset_packet(),
            SendPacketStatus::Other(status) => {
                error!("{}", Error::SendPacket(status));
                return None;
            }
        }

        match self.receive_decoded_frame() {
            ReceiveFrameStatus::Ok => {}
            ReceiveFrameStatus::Again | ReceiveFrameStatus::Deadlk => {
                return self.process_next_frame()
            }
            ReceiveFrameStatus::Other(status) => {
                error!("{}", Error::ReceiveFrame(status));
                return None;
            }
        }

        self.convert_and_store_frame();

        Some(Ok(()))
    }

    fn cleanup(&mut self) {
        // Drain the decoder.
        drain_decoder(self.codec_ctx.inner).unwrap();

        unsafe {
            // Free all data used by the frame.
            av_frame_free(&mut self.frame.inner);

            // Close the context and free all data associated to it, but not the context itself.
            avcodec_close(self.codec_ctx.inner);

            // Free the context itself.
            avcodec_free_context(&mut self.codec_ctx.inner);

            // Close the input.
            avformat_close_input(&mut self.format_ctx.inner);
        }
    }

    pub(crate) fn _current_frame_len(&self) -> Option<usize> {
        Some(self.current_frame.len())
    }

    pub(crate) fn _channels(&self) -> u16 {
        self.codec_ctx.channels() as _
    }

    pub(crate) fn _sample_rate(&self) -> u32 {
        self.codec_ctx.sample_rate() as _
    }

    pub(crate) fn _total_duration(&self) -> Option<Duration> {
        //TODO let duration = self.stream.duration();
        None
    }
}

unsafe impl Send for Decoder {}

impl Iterator for Decoder {
    type Item = i16;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if !self.first_frame_stored {
            if self.process_next_frame().is_none() {
                self.cleanup();
                return None;
            }

            self.first_frame_stored = true;

            return Some(self.next_sample());
        }

        if !self.current_frame.is_empty() {
            return Some(self.next_sample());
        }

        match self.receive_decoded_frame() {
            ReceiveFrameStatus::Ok => {
                self.convert_and_store_frame();
                Some(self.next_sample())
            }
            ReceiveFrameStatus::Again | ReceiveFrameStatus::Deadlk => {
                if self.process_next_frame().is_none() {
                    self.cleanup();
                    return None;
                }

                Some(self.next_sample())
            }
            ReceiveFrameStatus::Other(status) => {
                error!("{}", Error::ReceiveFrame(status));
                self.cleanup();
                None
            }
        }
    }
}

struct FormatContext {
    inner: *mut AVFormatContext,
}

impl FormatContext {
    fn open(path: &str) -> Result<FormatContext, Error> {
        let mut inner = std::ptr::null_mut::<AVFormatContext>();

        let path = CString::new(path).unwrap();

        let status = unsafe {
            avformat_open_input(
                &mut inner,
                path.as_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        if status != 0 {
            return Err(Error::InitializeFormatContext);
        }

        Ok(FormatContext { inner })
    }

    /// Look at first few frames to determine stream info
    fn find_stream_info(&self) -> Result<(), Error> {
        let status = unsafe { avformat_find_stream_info(self.inner, ptr::null_mut()) };
        if status < 0 {
            return Err(Error::FindStreamInfo);
        }
        Ok(())
    }

    ///  Get the first audio stream
    fn get_audio_stream(&self) -> Result<Stream, Error> {
        let num_streams = unsafe { self.inner.as_ref().unwrap().nb_streams };
        let streams = unsafe { self.inner.as_ref().unwrap().streams };

        let streams = unsafe { slice::from_raw_parts(streams, num_streams as usize) };

        let stream_idx = find_audio_stream(streams)?;

        Ok(Stream::new(streams[0], stream_idx))
    }
}

struct SwrContext {
    inner: *mut ffmpeg4_sys::SwrContext,
}

impl SwrContext {
    fn new(codec_ctx: &CodecContext) -> Result<SwrContext, Error> {
        let swr_ctx: *mut ffmpeg4_sys::SwrContext = unsafe {
            swr_alloc_set_opts(
                ptr::null_mut(),
                codec_ctx.channel_layout() as i64,
                DEFAULT_CONVERSION_FORMAT,
                codec_ctx.sample_rate(),
                codec_ctx.channel_layout() as i64,
                codec_ctx.sample_format(),
                codec_ctx.sample_rate(),
                0,
                ptr::null_mut(),
            )
        };

        let status = unsafe { swr_init(swr_ctx) };
        if status != 0 {
            return Err(Error::InitializeSwr);
        }

        Ok(SwrContext { inner: swr_ctx })
    }
}

struct Packet {
    inner: std::mem::MaybeUninit<AVPacket>,
}

impl Packet {
    fn new() -> Packet {
        let mut packet = std::mem::MaybeUninit::uninit();

        unsafe { av_init_packet(packet.as_mut_ptr()) };

        Packet { inner: packet }
    }
}

struct Frame {
    inner: *mut AVFrame,
}

impl Frame {
    fn new() -> Result<Frame, Error> {
        let frame: *mut AVFrame = unsafe { av_frame_alloc() };

        if frame.is_null() {
            return Err(Error::NullFrame);
        }

        Ok(Frame { inner: frame })
    }

    fn num_samples(&self) -> i32 {
        unsafe { self.inner.as_ref().unwrap().nb_samples }
    }

    fn channel_layout(&self) -> u64 {
        unsafe { self.inner.as_ref().unwrap().channel_layout }
    }

    fn extended_data(&self) -> *mut *const u8 {
        unsafe { self.inner.as_ref().unwrap().extended_data as *mut *const u8 }
    }
}

struct Stream {
    inner: *mut AVStream,
    index: i32,
}

impl Stream {
    fn new(inner: *mut AVStream, index: i32) -> Stream {
        Stream { inner, index }
    }

    fn get_codec(&self) -> Result<Codec, Error> {
        // Get streams codec
        let codec_params = unsafe { self.inner.as_ref().unwrap().codecpar };
        let codec_id = unsafe { codec_params.as_ref().unwrap().codec_id };

        let codec: *mut AVCodec = unsafe { avcodec_find_decoder(codec_id) };
        if codec.is_null() {
            return Err(Error::NullCodec);
        }

        Ok(Codec::new(codec))
    }

    #[allow(dead_code)]
    fn duration(&self) -> i64 {
        unsafe { self.inner.as_ref().unwrap().duration }
    }
}

struct CodecContext {
    inner: *mut AVCodecContext,
    codec: *mut AVCodec,
}

impl CodecContext {
    fn new(inner: *mut AVCodecContext, codec: *mut AVCodec) -> CodecContext {
        CodecContext { inner, codec }
    }

    fn copy_parameters_from_stream(&self, stream: &Stream) -> Result<(), Error> {
        let params = unsafe { stream.inner.as_ref().unwrap().codecpar };

        let status = unsafe { avcodec_parameters_to_context(self.inner, params) };

        if status != 0 {
            return Err(Error::CodecParamsToContext);
        }

        Ok(())
    }

    fn request_non_planar_format(&self) {
        unsafe {
            let sample_fmt = self.inner.as_ref().unwrap().sample_fmt;
            let alt_format = av_get_alt_sample_fmt(sample_fmt, 0);

            self.inner.as_mut().unwrap().request_sample_fmt = alt_format;
        }
    }

    fn initialize(&self) -> Result<(), Error> {
        let status = unsafe { avcodec_open2(self.inner, self.codec, &mut std::ptr::null_mut()) };

        if status != 0 {
            return Err(Error::InitializeDecoder);
        }

        Ok(())
    }

    fn codec_name(&self) -> &str {
        let name = unsafe { CStr::from_ptr(self.codec.as_ref().unwrap().long_name) };

        name.to_str().unwrap()
    }

    fn sample_format(&self) -> AVSampleFormat {
        unsafe { self.inner.as_ref().unwrap().sample_fmt }
    }

    fn sample_format_name(&self) -> &str {
        let sample_fmt = unsafe { CStr::from_ptr(av_get_sample_fmt_name(self.sample_format())) };

        sample_fmt.to_str().unwrap()
    }

    fn sample_rate(&self) -> i32 {
        unsafe { self.inner.as_ref().unwrap().sample_rate }
    }

    fn sample_size(&self) -> i32 {
        unsafe { av_get_bytes_per_sample(self.inner.as_ref().unwrap().sample_fmt) }
    }

    fn channels(&self) -> i32 {
        unsafe { self.inner.as_ref().unwrap().channels }
    }

    fn channel_layout(&self) -> u64 {
        unsafe { self.inner.as_ref().unwrap().channel_layout }
    }

    fn is_planar(&self) -> i32 {
        unsafe { av_sample_fmt_is_planar(self.inner.as_ref().unwrap().sample_fmt) }
    }
}

struct Codec {
    inner: *mut AVCodec,
}

impl Codec {
    fn new(inner: *mut AVCodec) -> Codec {
        Codec { inner }
    }

    fn get_context(&self) -> Result<CodecContext, Error> {
        let ctx: *mut AVCodecContext = unsafe { avcodec_alloc_context3(self.inner) };

        if ctx.is_null() {
            return Err(Error::NullCodecContext);
        }

        Ok(CodecContext::new(ctx, self.inner))
    }
}

enum ReadFrameStatus {
    Ok,
    Eof,
    Other(i32),
}

enum SendPacketStatus {
    Ok,
    Other(i32),
}

enum ReceiveFrameStatus {
    Ok,
    Again,
    Deadlk,
    Other(i32),
}

fn find_audio_stream(streams: &[*mut AVStream]) -> Result<i32, Error> {
    for stream in streams {
        let codec_type = unsafe {
            stream
                .as_ref()
                .unwrap()
                .codecpar
                .as_ref()
                .unwrap()
                .codec_type
        };
        let index = unsafe { stream.as_ref().unwrap().index };

        if codec_type == AVMediaType::AVMEDIA_TYPE_AUDIO {
            return Ok(index);
        }
    }

    Err(Error::NoAudioStream)
}

fn print_codec_info(codec_ctx: &CodecContext) {
    info!("Codec:         {}", codec_ctx.codec_name());
    info!("Sample Format: {}", codec_ctx.sample_format_name());
    info!("Sample Rate:   {}", codec_ctx.sample_rate());
    info!("Sample Size:   {}", codec_ctx.sample_size());
    info!("Channels:      {}", codec_ctx.channels());
    info!("Planar:        {}", codec_ctx.is_planar());
}

fn drain_decoder(codec_ctx: *mut AVCodecContext) -> Result<(), Error> {
    let status = unsafe { avcodec_send_packet(codec_ctx, std::ptr::null()) };
    if status == 0 {
    } else {
        return Err(Error::DrainDecoder(status));
    }

    Ok(())
}