mp3lame-encoder 0.2.4

High level bindings to mp3lame encoder
Documentation
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//!High level wrapper over [mp3lame-sys](https://crates.io/crates/mp3lame-sys)
//!
//!## Example
//!
//!```rust
//!use mp3lame_encoder::{Builder, Id3Tag, DualPcm, FlushNoGap};
//!
//!let id3tag = Id3Tag {
//!    title: b"My title",
//!    artist: &[],
//!    album: b"My album",
//!    album_art: &[],
//!    year: b"Current year",
//!    comment: b"Just my comment",
//!};
//!
//!//Methods prefixed with `with_*` return Self for convenience
//!let mut mp3_encoder = Builder::new().expect("Create LAME builder")
//!    .with_num_channels(2).expect("set channels")
//!    .with_sample_rate(44_100).expect("set sample rate")
//!    .with_brate(mp3lame_encoder::Bitrate::Kbps192).expect("set brate")
//!    .with_quality(mp3lame_encoder::Quality::Best).expect("set quality")
//!    .with_vbr_mode(mp3lame_encoder::VbrMode::Mtrh).expect("set VBR")
//!    .with_vbr_quality(mp3lame_encoder::Quality::Best).expect("set VBR quality")
//!    .with_to_write_vbr_tag(true).expect("set to write VBR tag")
//!    .with_id3_tag(id3tag).expect("set tags")
//!    .build().expect("To initialize LAME encoder");
//!
//!//use actual PCM data
//!let input = DualPcm {
//!    left: &[0u16, 1024],
//!    right: &[0u16, 1024],
//!};
//!
//!let mut mp3_out_buffer = Vec::new();
//!mp3_out_buffer.reserve(mp3lame_encoder::max_required_buffer_size(input.left.len()));
//!let encoded_size = mp3_encoder.encode(input, mp3_out_buffer.spare_capacity_mut()).expect("To encode");
//!unsafe {
//!    mp3_out_buffer.set_len(mp3_out_buffer.len().wrapping_add(encoded_size));
//!}
//!
//!let encoded_size = mp3_encoder.flush::<FlushNoGap>(mp3_out_buffer.spare_capacity_mut()).expect("to flush");
//!unsafe {
//!    mp3_out_buffer.set_len(mp3_out_buffer.len().wrapping_add(encoded_size));
//!}
//!//At this point your mp3_out_buffer should have full MP3 data, ready to be written on file system or whatever
//!
//!if mp3_encoder.lame_tag_size() > 0 {
//!   let id3v2_tag_boundary = mp3_encoder.id3v2_tag_size();
//!   assert_eq!(id3v2_tag_boundary, 158);
//!   let mut lame_tag = [core::mem::MaybeUninit::uninit(); 1024];
//!   assert!(lame_tag.len() >= mp3_encoder.lame_tag_size(), "Increase buffer size");
//!   let lame_tag_size = mp3_encoder.lame_tag_encode(&mut lame_tag).expect("to write lame tag");
//!   assert_eq!(mp3_encoder.lame_tag_size(), lame_tag_size.get());
//!
//!   //If you need VBR tag then you need to write mp3 file in following order
//!   //- id3v2 tag
//!   //- VBR tag
//!   //- actual mp3 content
//!   let chunks_to_write = [
//!       &mp3_out_buffer[..id3v2_tag_boundary],
//!       unsafe {
//!           core::slice::from_raw_parts(lame_tag.as_ptr() as *const u8, lame_tag_size.get())
//!       },
//!       &mp3_out_buffer[id3v2_tag_boundary..],
//!   ];
//!} else {
//!   let chunks_to_write = [
//!       &mp3_out_buffer[..]
//!   ];
//!}
//!```

#![no_std]
#![warn(missing_docs)]
#![allow(clippy::style)]
#![allow(clippy::missing_safety_doc)]
#![cfg_attr(rustfmt, rustfmt_skip)]

#[cfg(feature = "std")]
extern crate std;

extern crate alloc;

pub use mp3lame_sys as ffi;

use alloc::vec::Vec;
use core::mem::{self, MaybeUninit};
use core::num::{NonZeroU32, NonZeroUsize};
use core::ptr::{self, NonNull};
use core::{cmp, fmt};
use core::ffi::c_int;

mod input;
pub use input::*;

///Maximum size of album art
pub const MAX_ALBUM_ART_SIZE: usize = 128 * 1024;

///Calculates maximum required size for specified number of samples.
///
///Note that actual requirement may vary depending on encoder parameters,
///but this size should be generally enough for encoding given number of samples
pub const fn max_required_buffer_size(sample_number: usize) -> usize {
    //add 25% sample number + mp3 frame size 7200
    let mut sample_extra_size = sample_number / 4;
    if (sample_number % 4) > 0 {
        sample_extra_size = sample_extra_size.wrapping_add(1);
    }
    sample_number.wrapping_add(sample_extra_size).wrapping_add(7200)
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
///ID3 setter errors
pub enum Id3TagError {
    ///Specified buffer exceed limit of 128kb
    AlbumArtOverflow,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
///Encoder builder errors
pub enum BuildError {
    ///Generic error, indicates invalid input or state
    Generic,
    ///Failed to allocate memory
    NoMem,
    ///Invalid brate
    BadBRate,
    ///Invalid sample frequency
    BadSampleFreq,
    ///Internal error
    InternalError,
    ///Other errors, most likely unexpected.
    Other(c_int),
}

impl BuildError {
    #[inline(always)]
    fn from_c_int(code: c_int) -> Result<(), Self> {
        if code >= 0 {
            return Ok(())
        }

        match code {
            -1 => Err(Self::Generic),
            -10 => Err(Self::NoMem),
            -11 => Err(Self::BadBRate),
            -12 => Err(Self::BadSampleFreq),
            -13 => Err(Self::InternalError),
            _ => Err(Self::Other(code)),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BuildError {
}

impl fmt::Display for BuildError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Generic => fmt.write_str("error"),
            Self::NoMem => fmt.write_str("alloc failure"),
            Self::BadBRate => fmt.write_str("bad bitrate"),
            Self::BadSampleFreq => fmt.write_str("bad sample frequency"),
            Self::InternalError => fmt.write_str("internal error"),
            Self::Other(code) => fmt.write_fmt(format_args!("error code={code}")),
        }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
///Encoder errors
pub enum EncodeError {
    ///Indicates output buffer is insufficient.
    ///
    ///Consider using [max_required_buffer_size] to determine required
    ///space to alloc.
    BufferTooSmall,
    ///Failed to allocate memory
    NoMem,
    ///Invalid encoder state
    ///
    ///Should not happen if encoder created through builder
    InvalidState,
    ///Psycho acoustic problems, whatever it means.
    PsychoAcoustic,
    ///Other errors, most likely unexpected.
    Other(c_int),
}

impl EncodeError {
    #[inline(always)]
    fn from_c_int(code: c_int) -> Result<usize, Self> {
        if code >= 0 {
            return Ok(code as usize)
        }

        match code {
            -1 => Err(Self::BufferTooSmall),
            -2 => Err(Self::NoMem),
            -3 => Err(Self::InvalidState),
            -4 => Err(Self::PsychoAcoustic),
            _ => Err(Self::Other(code)),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for EncodeError {
}

impl fmt::Display for EncodeError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::BufferTooSmall => fmt.write_str("output buffer is insufficient for encoder output"),
            Self::NoMem => fmt.write_str("alloc failure"),
            Self::InvalidState => fmt.write_str("attempt to use uninitialized encoder"),
            Self::PsychoAcoustic => fmt.write_str("psycho acoustic problems"),
            Self::Other(code) => fmt.write_fmt(format_args!("error code={code}")),
        }
    }
}


///Enumeration of valid values for `set_brate`
#[derive(Copy, Clone)]
#[repr(u16)]
pub enum Bitrate {
    ///8_000
    Kbps8 = 8,
    ///16_000
    Kbps16 = 16,
    ///24_000
    Kbps24 = 24,
    ///32_000
    Kbps32 = 32,
    ///40_000
    Kbps40 = 40,
    ///48_000
    Kbps48 = 48,
    ///64_000
    Kbps64 = 64,
    ///80_000
    Kbps80 = 80,
    ///96_000
    Kbps96 = 96,
    ///112_000
    Kbps112 = 112,
    ///128_000
    Kbps128 = 128,
    ///160_000
    Kbps160 = 160,
    ///192_000
    Kbps192 = 192,
    ///224_000
    Kbps224 = 224,
    ///256_000
    Kbps256 = 256,
    ///320_000
    Kbps320 = 320,
}

///Alias to `Bitrate` with incorrect spelling
pub use Bitrate as Birtate;

#[derive(Copy, Clone)]
#[repr(u8)]
///Possible VBR types
pub enum VbrMode {
    ///Off.
    Off = ffi::vbr_mode::vbr_off as u8,
    ///MT.
    Mt = ffi::vbr_mode::vbr_mt as u8,
    ///RH.
    Rh = ffi::vbr_mode::vbr_rh as u8,
    ///ABR.
    Abr = ffi::vbr_mode::vbr_abr as u8,
    ///MTRH.
    Mtrh = ffi::vbr_mode::vbr_mtrh as u8,
}

impl Default for VbrMode {
    #[inline(always)]
    fn default() -> Self {
        Self::Mtrh
    }
}

#[derive(Copy, Clone)]
#[repr(u8)]
///Possible modes for encoder
pub enum Mode {
    ///Mono.
    Mono = ffi::MPEG_mode::MONO as u8,
    ///Stereo.
    Stereo = ffi::MPEG_mode::STEREO as u8,
    ///Joint stereo.
    JointStereo = ffi::MPEG_mode::JOINT_STEREO as u8,
    ///Dual channel
    ///
    ///Unsupported so far.
    DaulChannel = ffi::MPEG_mode::DUAL_CHANNEL as u8,
    ///Not set.
    NotSet = ffi::MPEG_mode::NOT_SET as u8,
}

///Possible quality parameter.
///From best(0) to worst(9)
#[derive(Copy, Clone)]
#[repr(u8)]
pub enum Quality {
    ///Best possible quality
    Best = 0,
    ///Second best
    SecondBest = 1,
    ///Close to best
    NearBest = 2,
    ///Very nice
    VeryNice = 3,
    ///Nice
    Nice = 4,
    ///Good
    Good = 5,
    ///Decent
    Decent = 6,
    ///Okayish
    Ok = 7,
    ///Almost worst
    SecondWorst = 8,
    ///Worst
    Worst = 9,
}

#[derive(Copy, Clone)]
///ID3 tag as raw bytes.
///
///Use empty slice for `None`
///
///At the current moment, only up to 250 characters will be copied.
pub struct Id3Tag<'a> {
    ///Track's Title
    pub title: &'a [u8],
    ///Artist name
    pub artist: &'a [u8],
    ///Album name
    pub album: &'a [u8],
    ///Album art
    ///
    ///Must be image data.
    ///
    ///Allowed formats: PNG, JPG, GIF
    ///
    ///Maximum size is defined by constant MAX_ALBUM_ART_SIZE
    ///When setting this metadata, make sure allocate at least MAX_ALBUM_ART_SIZE
    pub album_art: &'a [u8],
    ///Year
    pub year: &'a [u8],
    ///Comment
    pub comment: &'a [u8],
}

impl Id3Tag<'_> {
    #[inline(always)]
    ///Returns true if any is set
    pub const fn is_any_set(&self) -> bool {
        !self.title.is_empty() || !self.artist.is_empty() || !self.album.is_empty() || !self.album_art.is_empty() || !self.year.is_empty() || !self.comment.is_empty()
    }
}

///Builder of C LAME encoder.
pub struct Builder {
    inner: NonNull<ffi::lame_global_flags>,
}

impl Builder {
    #[inline]
    ///Creates new encoder with default parameters: J-Stereo, 44.1khz 128kbps CBR mp3 file at quality 5
    ///
    ///Returns `None` if unable to allocate struct.
    pub fn new() -> Option<Self> {
        let ptr = unsafe {
            ffi::lame_init()
        };

        NonNull::new(ptr).map(|inner| Self {
            inner
        })
    }

    #[inline(always)]
    ///Get access to underlying LAME structure, without dropping ownership.
    ///
    ///User must guarantee not to close or dealloc this pointer
    pub unsafe fn as_ptr(&mut self) -> *mut ffi::lame_global_flags {
        self.ptr()
    }

    #[inline(always)]
    fn ptr(&mut self) -> *mut ffi::lame_global_flags {
        self.inner.as_ptr()
    }

    #[inline]
    ///Sets output sample rate.
    ///
    ///The default `None` allows LAME to pick the best value.
    ///The supported values are:
    /// - MPEG1: `32_000`, `44_100` and `48_000`
    /// - MPEG2: `16_000`, `22_050` and `24_000`
    /// - MPEG2.5: `8_000`, `11_025` and `12_000`
    ///
    ///Returns `Ok(())` the requested value is supported and was set successfully.
    pub fn set_output_sample_rate(&mut self, rate: Option<NonZeroU32>) -> Result<(), BuildError> {
        let rate = rate.map_or(0, NonZeroU32::get).try_into().unwrap_or(c_int::MAX);

        let res = unsafe {
             ffi::lame_set_out_samplerate(self.ptr(), rate)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets output sample rate using the builder pattern.
    ///
    ///The default `None` allows LAME to pick the best value.
    ///The supported values are:
    /// - MPEG1: `32_000`, `44_100` and `48_000`
    /// - MPEG2: `16_000`, `22_050` and `24_000`
    /// - MPEG2.5: `8_000`, `11_025` and `12_000`
    ///
    ///Returns `Ok(())` the requested value is supported and was set successfully.
    pub fn with_output_sample_rate(mut self, rate: Option<NonZeroU32>) -> Result<Self, BuildError> {
        self.set_output_sample_rate(rate)?;
        Ok(self)
    }

    #[inline]
    ///Sets input sample rate.
    ///
    ///Defaults to 44_100.
    ///
    ///Returns whether it is supported or not.
    pub fn set_sample_rate(&mut self, rate: u32) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_in_samplerate(self.ptr(), rate.try_into().unwrap_or(c_int::MAX))
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets input sample rate using the builder pattern.
    ///
    ///Defaults to 44_100.
    ///
    ///Returns an error if it is not supported.
    pub fn with_sample_rate(mut self, rate: u32) -> Result<Self, BuildError> {
        self.set_sample_rate(rate)?;
        Ok(self)
    }

    #[inline]
    ///Sets number of channels.
    ///
    ///Defaults to 2.
    ///
    ///Returns whether it is supported or not.
    pub fn set_num_channels(&mut self, num: u8) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_num_channels(self.ptr(), num as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets sample rate using the builder pattern.
    ///
    ///Defaults to 2.
    ///
    ///Returns an error if it is not supported.
    pub fn with_num_channels(mut self, num: u8) -> Result<Self, BuildError> {
        self.set_num_channels(num)?;
        Ok(self)
    }

    #[inline]
    ///Sets bitrate (as kbps).
    ///
    ///Defaults to compression ratio of 11.
    ///
    ///Returns whether it is supported or not.
    pub fn set_brate(&mut self, brate: Bitrate) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_brate(self.ptr(), brate as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets bitrate (as kbps) using the builder pattern.
    ///
    ///Defaults to compression ratio of 11.
    ///
    ///Returns an error if it is not supported.
    pub fn with_brate(mut self, brate: Bitrate) -> Result<Self, BuildError> {
        self.set_brate(brate)?;
        Ok(self)
    }

    #[inline]
    ///Sets MPEG mode.
    ///
    ///Default is picked by LAME depending on compression ration and input channels.
    ///
    ///Returns whether it is supported or not.
    pub fn set_mode(&mut self, mode: Mode) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_mode(self.ptr(), mode as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets MPEG mode using the builder pattern.
    ///
    ///Default is picked by LAME depending on compression ration and input channels.
    ///
    ///Returns an error if it is not supported.
    pub fn with_mode(mut self, mode: Mode) -> Result<Self, BuildError> {
        self.set_mode(mode)?;
        Ok(self)
    }

    #[inline]
    ///Sets quality.
    ///
    ///Default is good one(5)
    ///
    ///Returns whether it is supported or not.
    pub fn set_quality(&mut self, quality: Quality) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_quality(self.ptr(), quality as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets quality using the builder pattern.
    ///
    ///Default is good one(5)
    ///
    ///Returns an error if it is not supported.
    pub fn with_quality(mut self, quality: Quality) -> Result<Self, BuildError> {
        self.set_quality(quality)?;
        Ok(self)
    }

    #[inline]
    ///Sets VBR quality.
    ///
    ///Returns whether it is supported or not.
    pub fn set_vbr_quality(&mut self, quality: Quality) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_VBR_q(self.ptr(), quality as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets VBR quality using the builder pattern.
    ///
    ///Returns an error if it is not supported.
    pub fn with_vbr_quality(mut self, quality: Quality) -> Result<Self, BuildError> {
        self.set_vbr_quality(quality)?;
        Ok(self)
    }

    #[inline]
    ///Sets whether to write VBR tag.
    ///
    ///Default is true.
    ///
    ///Returns whether it is supported or not.
    pub fn set_to_write_vbr_tag(&mut self, value: bool) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_bWriteVbrTag(self.ptr(), value as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets whether to write VBR tag using the builder pattern.
    ///
    ///Default is true.
    ///
    ///Returns an error if it is not supported.
    pub fn with_to_write_vbr_tag(mut self, value: bool) -> Result<Self, BuildError> {
        self.set_to_write_vbr_tag(value)?;
        Ok(self)
    }

    #[inline]
    ///Sets VBR mode.
    ///
    ///Default is off (i.e. CBR)
    ///
    ///Returns whether it is supported or not.
    pub fn set_vbr_mode(&mut self, value: VbrMode) -> Result<(), BuildError> {
        let res = unsafe {
            ffi::lame_set_VBR(self.ptr(), value as _)
        };

        BuildError::from_c_int(res)
    }

    #[inline]
    ///Sets VBR mode using the bulder pattern.
    ///
    ///Default is off (i.e. CBR)
    ///
    ///Returns an error if it is not supported.
    pub fn with_vbr_mode(mut self, value: VbrMode) -> Result<Self, BuildError> {
        self.set_vbr_mode(value)?;
        Ok(self)
    }

    #[inline]
    ///Sets id3tag tag.
    ///
    ///If [FlushGap] is used, then `v1` will not be added.
    ///But `v2` is always added at the beginning.
    ///
    ///Returns whether it is supported or not.
    pub fn set_id3_tag(&mut self, value: Id3Tag<'_>) -> Result<(), Id3TagError> {
        if !value.is_any_set() {
            return Ok(());
        }

        const MAX_BUFFER: usize = 250;
        let mut buffer = [0u8; MAX_BUFFER + 1];

        unsafe {
            ffi::id3tag_init(self.ptr());
            ffi::id3tag_add_v2(self.ptr());

            if !value.album_art.is_empty() {
                let size = value.album_art.len();
                if size > MAX_ALBUM_ART_SIZE {
                    return Err(Id3TagError::AlbumArtOverflow);
                }
                let ptr = value.album_art.as_ptr();
                ffi::id3tag_set_albumart(self.ptr(), ptr as _, size);
            }

            if !value.title.is_empty() {
                let size = cmp::min(MAX_BUFFER, value.title.len());
                ptr::copy_nonoverlapping(value.title.as_ptr(), buffer.as_mut_ptr(), size);
                buffer[size] = 0;
                ffi::id3tag_set_title(self.ptr(), buffer.as_ptr() as _);
            }

            if !value.album.is_empty() {
                let size = cmp::min(MAX_BUFFER, value.album.len());
                ptr::copy_nonoverlapping(value.album.as_ptr(), buffer.as_mut_ptr(), size);
                buffer[size] = 0;
                ffi::id3tag_set_album(self.ptr(), buffer.as_ptr() as _);
            }

            if !value.artist.is_empty() {
                let size = cmp::min(MAX_BUFFER, value.artist.len());
                ptr::copy_nonoverlapping(value.artist.as_ptr(), buffer.as_mut_ptr(), size);
                buffer[size] = 0;
                ffi::id3tag_set_artist(self.ptr(), buffer.as_ptr() as _);
            }

            if !value.year.is_empty() {
                let size = cmp::min(MAX_BUFFER, value.year.len());
                ptr::copy_nonoverlapping(value.year.as_ptr(), buffer.as_mut_ptr(), size);
                buffer[size] = 0;
                ffi::id3tag_set_year(self.ptr(), buffer.as_ptr() as _);
            }

            if !value.comment.is_empty() {
                let size = cmp::min(MAX_BUFFER, value.comment.len());
                ptr::copy_nonoverlapping(value.comment.as_ptr(), buffer.as_mut_ptr(), size);
                buffer[size] = 0;
                ffi::id3tag_set_comment(self.ptr(), buffer.as_ptr() as _);
            }
        }

        Ok(())
    }

    #[inline]
    ///Sets id3tag tag using the builder pattern.
    ///
    ///If [FlushGap] is used, then `v1` will not be added.
    ///
    ///Returns an error if it is not supported.
    pub fn with_id3_tag(mut self, value: Id3Tag<'_>) -> Result<Self, Id3TagError> {
        self.set_id3_tag(value)?;
        Ok(self)
    }

    #[inline]
    ///Attempts to initialize encoder with specified parameters.
    ///
    ///Returns `None` if parameters are invalid or incompatible.
    pub fn build(mut self) -> Result<Encoder, BuildError> {
        let res = unsafe {
            ffi::lame_init_params(self.ptr())
        };

        match BuildError::from_c_int(res) {
            Ok(()) => {
                let inner = self.inner;
                mem::forget(self);
                Ok(Encoder { inner })
            },
            Err(error) => Err(error),
        }
    }
}

impl Drop for Builder {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ffi::lame_close(self.ptr())
        };
    }
}

///LAME Encoder.
pub struct Encoder {
    inner: NonNull<ffi::lame_global_flags>,
}

impl Encoder {
    #[inline(always)]
    fn ptr(&self) -> *mut ffi::lame_global_flags {
        self.inner.as_ptr()
    }

    #[inline]
    ///Returns sample rate.
    pub fn sample_rate(&self) -> u32 {
        unsafe {
            ffi::lame_get_in_samplerate(self.ptr()) as u32
        }
    }

    #[inline]
    ///Returns number of channels.
    pub fn num_channels(&self) -> u8 {
        unsafe {
            ffi::lame_get_num_channels(self.ptr()) as u8
        }
    }

    #[inline]
    ///Returns indication whether encoder is configured to write LAME tag
    pub fn is_lame_tag_written(&self) -> bool {
        unsafe {
            ffi::lame_get_bWriteVbrTag(self.ptr()) != 0
        }
    }

    #[inline]
    ///Returns size of ths [Id3Tag] written, if any
    pub fn id3v2_tag_size(&self) -> usize {
        unsafe {
            ffi::lame_get_id3v2_tag(self.ptr(), ptr::null_mut(), 0)
        }
    }

    #[inline]
    ///Retrieves size of the lame tag
    pub fn lame_tag_size(&self) -> usize {
        unsafe {
            ffi::lame_get_lametag_frame(self.ptr(), ptr::null_mut(), 0)
        }
    }

    #[inline]
    ///Attempts to write lame tag into `output` returning number of written bytes in case of success
    ///
    ///Note that if you write [Id3Tag] you must not write this tag at the start.
    ///Instead you must insert Lame Tag after [Id3Tag] position.
    ///
    ///To determine where [Id3Tag] ends in output stream, you can use [Encoder::id3v2_tag_size]
    ///which returns full size of [Id3Tag] metadata written (therefore indicating where actual mp3
    ///content is starting)
    pub fn lame_tag_encode(&self, output: &mut [MaybeUninit<u8>]) -> Option<NonZeroUsize> {
        //lame_get_lametag_frame() returns full required size in case `output` is not sufficient,
        //so first manually check buffer size
        if output.len() < self.lame_tag_size() {
            None
        } else {
            NonZeroUsize::new(unsafe {
                ffi::lame_get_lametag_frame(self.ptr(), output.as_mut_ptr() as _, output.len())
            })
        }
    }

    #[inline]
    ///Attempts to write lame tag into `output` returning number of written bytes in case of success
    ///
    ///Refer to [Encoder::lame_tag_encode] for details
    pub fn lame_tag_encode_to_vec(&self, output: &mut Vec<u8>) -> Option<NonZeroUsize> {
        let original_len = output.len();
        match self.lame_tag_encode(output.spare_capacity_mut()) {
            Some(written) => {
                unsafe {
                    output.set_len(original_len.saturating_add(written.get()));
                }
                Some(written)
            },
            None => None
        }
    }

    #[inline]
    ///Attempts to encode PCM data, writing whatever available onto `output` buffer
    ///
    ///### Arguments:
    ///
    /// - `input` - Data input. Can be [MonoPcm], [DualPcm] or [InterleavedPcm]
    /// - `output` - Output buffer to write into.
    ///
    ///### Result:
    ///On success, returns number of bytes written (can be 0).
    ///Otherwise returns error indicating potential issue.
    pub fn encode(&mut self, input: impl EncoderInput, output: &mut [MaybeUninit<u8>]) -> Result<usize, EncodeError> {
        let output_len = output.len();
        let output_buf = output.as_mut_ptr();

        let result = input.encode(self, output_buf as _, output_len);

        EncodeError::from_c_int(result)
    }

    #[inline(always)]
    ///Attempts to encode PCM data, writing whatever available onto `output` buffer
    ///
    ///`output` size is adjusted on success only
    ///
    ///Refer for details to `encode()`
    pub fn encode_to_vec(&mut self, input: impl EncoderInput, output: &mut Vec<u8>) -> Result<usize, EncodeError> {
        let original_len = output.len();
        match self.encode(input, output.spare_capacity_mut()) {
            Ok(written) => {
                unsafe {
                    output.set_len(original_len.saturating_add(written));
                }
                Ok(written)
            },
            Err(error) => Err(error),
        }
    }

    #[inline]
    ///Attempts flush all data, writing whatever available onto `output` buffer
    ///Padding with 0 to complete MP3
    ///
    ///### Type:
    ///
    ///- [FlushNoGap] - performs flush, using ancillary data to fill gaps;
    ///- [FlushGap] - performs flush, padding with 0;
    ///
    ///### Arguments:
    ///
    /// - `output` - Output buffer to write into. As it is final action, you need at least 7200 bytes to hold at MP3 data.
    ///
    ///### Result:
    ///On success, returns number of bytes written (can be 0).
    ///Otherwise returns error indicating potential issue.
    pub fn flush<T: EncoderFlush>(&mut self, output: &mut [MaybeUninit<u8>]) -> Result<usize, EncodeError> {
        let output_len = output.len();
        let output_buf = output.as_mut_ptr();

        let result = T::flush(self, output_buf as _, output_len);

        EncodeError::from_c_int(result)
    }

    #[inline(always)]
    ///Attempts flush all data, writing whatever available onto `output` buffer.
    ///
    ///`output` size is adjusted on success only
    ///
    ///Refer for details to `flush()`
    pub fn flush_to_vec<T: EncoderFlush>(&mut self, output: &mut Vec<u8>) -> Result<usize, EncodeError> {
        let original_len = output.len();
        match self.flush::<T>(output.spare_capacity_mut()) {
            Ok(written) => {
                unsafe {
                    output.set_len(original_len.saturating_add(written));
                }
                Ok(written)
            },
            Err(error) => Err(error),
        }
    }
}

impl Drop for Encoder {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ffi::lame_close(self.ptr())
        };
    }
}

/// According to LAME 3.99.5 HACKING, it is thread-safe.
unsafe impl Send for Encoder {}
/// According to LAME 3.99.5 HACKING, it is thread-safe.
unsafe impl Sync for Encoder {}

///Creates default encoder with 192kbps bitrate and best possible quality.
pub fn encoder() -> Result<Encoder, BuildError> {
    match Builder::new() {
        Some(mut builder) => {
            builder.set_brate(Bitrate::Kbps192)?;
            builder.set_quality(Quality::Best)?;
            builder.build()
        },
        None => Err(BuildError::NoMem)
    }
}