-
Notifications
You must be signed in to change notification settings - Fork 3
/
dr_mp3.h
4695 lines (4056 loc) · 173 KB
/
dr_mp3.h
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MP3 audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
dr_mp3 - v0.6.15 - 2020-07-25
David Reid - [email protected]
GitHub: https://github.com/mackron/dr_libs
Based on minimp3 (https://github.com/lieff/minimp3) which is where the real work was done. See the bottom of this file for differences between minimp3 and dr_mp3.
*/
/*
RELEASE NOTES - VERSION 0.6
===========================
Version 0.6 includes breaking changes with the configuration of decoders. The ability to customize the number of output channels and the sample rate has been
removed. You must now use the channel count and sample rate reported by the MP3 stream itself, and all channel and sample rate conversion must be done
yourself.
Changes to Initialization
-------------------------
Previously, `drmp3_init()`, etc. took a pointer to a `drmp3_config` object that allowed you to customize the output channels and sample rate. This has been
removed. If you need the old behaviour you will need to convert the data yourself or just not upgrade. The following APIs have changed.
`drmp3_init()`
`drmp3_init_memory()`
`drmp3_init_file()`
Miscellaneous Changes
---------------------
Support for loading a file from a `wchar_t` string has been added via the `drmp3_init_file_w()` API.
*/
/*
Introducation
=============
dr_mp3 is a single file library. To use it, do something like the following in one .c file.
```c
#define DR_MP3_IMPLEMENTATION
#include "dr_mp3.h"
```
You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, do something like the following:
```c
drmp3 mp3;
if (!drmp3_init_file(&mp3, "MySong.mp3", NULL)) {
// Failed to open file
}
...
drmp3_uint64 framesRead = drmp3_read_pcm_frames_f32(pMP3, framesToRead, pFrames);
```
The drmp3 object is transparent so you can get access to the channel count and sample rate like so:
```
drmp3_uint32 channels = mp3.channels;
drmp3_uint32 sampleRate = mp3.sampleRate;
```
The example above initializes a decoder from a file, but you can also initialize it from a block of memory and read and seek callbacks with
`drmp3_init_memory()` and `drmp3_init()` respectively.
You do not need to do any annoying memory management when reading PCM frames - this is all managed internally. You can request any number of PCM frames in each
call to `drmp3_read_pcm_frames_f32()` and it will return as many PCM frames as it can, up to the requested amount.
You can also decode an entire file in one go with `drmp3_open_and_read_pcm_frames_f32()`, `drmp3_open_memory_and_read_pcm_frames_f32()` and
`drmp3_open_file_and_read_pcm_frames_f32()`.
Build Options
=============
#define these options before including this file.
#define DR_MP3_NO_STDIO
Disable drmp3_init_file(), etc.
#define DR_MP3_NO_SIMD
Disable SIMD optimizations.
*/
#ifndef dr_mp3_h
#define dr_mp3_h
#ifdef __cplusplus
extern "C" {
#endif
#define DRMP3_STRINGIFY(x) #x
#define DRMP3_XSTRINGIFY(x) DRMP3_STRINGIFY(x)
#define DRMP3_VERSION_MAJOR 0
#define DRMP3_VERSION_MINOR 6
#define DRMP3_VERSION_REVISION 15
#define DRMP3_VERSION_STRING DRMP3_XSTRINGIFY(DRMP3_VERSION_MAJOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_MINOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_REVISION)
#include <stddef.h> /* For size_t. */
/* Sized types. Prefer built-in types. Fall back to stdint. */
#ifdef _MSC_VER
#if defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlanguage-extension-token"
#pragma GCC diagnostic ignored "-Wlong-long"
#pragma GCC diagnostic ignored "-Wc++11-long-long"
#endif
typedef signed __int8 drmp3_int8;
typedef unsigned __int8 drmp3_uint8;
typedef signed __int16 drmp3_int16;
typedef unsigned __int16 drmp3_uint16;
typedef signed __int32 drmp3_int32;
typedef unsigned __int32 drmp3_uint32;
typedef signed __int64 drmp3_int64;
typedef unsigned __int64 drmp3_uint64;
#if defined(__clang__)
#pragma GCC diagnostic pop
#endif
#else
#include <stdint.h>
typedef int8_t drmp3_int8;
typedef uint8_t drmp3_uint8;
typedef int16_t drmp3_int16;
typedef uint16_t drmp3_uint16;
typedef int32_t drmp3_int32;
typedef uint32_t drmp3_uint32;
typedef int64_t drmp3_int64;
typedef uint64_t drmp3_uint64;
#endif
typedef drmp3_uint8 drmp3_bool8;
typedef drmp3_uint32 drmp3_bool32;
#define DRMP3_TRUE 1
#define DRMP3_FALSE 0
#if !defined(DRMP3_API)
#if defined(DRMP3_DLL)
#if defined(_WIN32)
#define DRMP3_DLL_IMPORT __declspec(dllimport)
#define DRMP3_DLL_EXPORT __declspec(dllexport)
#define DRMP3_DLL_PRIVATE static
#else
#if defined(__GNUC__) && __GNUC__ >= 4
#define DRMP3_DLL_IMPORT __attribute__((visibility("default")))
#define DRMP3_DLL_EXPORT __attribute__((visibility("default")))
#define DRMP3_DLL_PRIVATE __attribute__((visibility("hidden")))
#else
#define DRMP3_DLL_IMPORT
#define DRMP3_DLL_EXPORT
#define DRMP3_DLL_PRIVATE static
#endif
#endif
#if defined(DR_MP3_IMPLEMENTATION) || defined(DRMP3_IMPLEMENTATION)
#define DRMP3_API DRMP3_DLL_EXPORT
#else
#define DRMP3_API DRMP3_DLL_IMPORT
#endif
#define DRMP3_PRIVATE DRMP3_DLL_PRIVATE
#else
#define DRMP3_API extern
#define DRMP3_PRIVATE static
#endif
#endif
typedef drmp3_int32 drmp3_result;
#define DRMP3_SUCCESS 0
#define DRMP3_ERROR -1 /* A generic error. */
#define DRMP3_INVALID_ARGS -2
#define DRMP3_INVALID_OPERATION -3
#define DRMP3_OUT_OF_MEMORY -4
#define DRMP3_OUT_OF_RANGE -5
#define DRMP3_ACCESS_DENIED -6
#define DRMP3_DOES_NOT_EXIST -7
#define DRMP3_ALREADY_EXISTS -8
#define DRMP3_TOO_MANY_OPEN_FILES -9
#define DRMP3_INVALID_FILE -10
#define DRMP3_TOO_BIG -11
#define DRMP3_PATH_TOO_LONG -12
#define DRMP3_NAME_TOO_LONG -13
#define DRMP3_NOT_DIRECTORY -14
#define DRMP3_IS_DIRECTORY -15
#define DRMP3_DIRECTORY_NOT_EMPTY -16
#define DRMP3_END_OF_FILE -17
#define DRMP3_NO_SPACE -18
#define DRMP3_BUSY -19
#define DRMP3_IO_ERROR -20
#define DRMP3_INTERRUPT -21
#define DRMP3_UNAVAILABLE -22
#define DRMP3_ALREADY_IN_USE -23
#define DRMP3_BAD_ADDRESS -24
#define DRMP3_BAD_SEEK -25
#define DRMP3_BAD_PIPE -26
#define DRMP3_DEADLOCK -27
#define DRMP3_TOO_MANY_LINKS -28
#define DRMP3_NOT_IMPLEMENTED -29
#define DRMP3_NO_MESSAGE -30
#define DRMP3_BAD_MESSAGE -31
#define DRMP3_NO_DATA_AVAILABLE -32
#define DRMP3_INVALID_DATA -33
#define DRMP3_TIMEOUT -34
#define DRMP3_NO_NETWORK -35
#define DRMP3_NOT_UNIQUE -36
#define DRMP3_NOT_SOCKET -37
#define DRMP3_NO_ADDRESS -38
#define DRMP3_BAD_PROTOCOL -39
#define DRMP3_PROTOCOL_UNAVAILABLE -40
#define DRMP3_PROTOCOL_NOT_SUPPORTED -41
#define DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED -42
#define DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED -43
#define DRMP3_SOCKET_NOT_SUPPORTED -44
#define DRMP3_CONNECTION_RESET -45
#define DRMP3_ALREADY_CONNECTED -46
#define DRMP3_NOT_CONNECTED -47
#define DRMP3_CONNECTION_REFUSED -48
#define DRMP3_NO_HOST -49
#define DRMP3_IN_PROGRESS -50
#define DRMP3_CANCELLED -51
#define DRMP3_MEMORY_ALREADY_MAPPED -52
#define DRMP3_AT_END -53
#define DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152
#define DRMP3_MAX_SAMPLES_PER_FRAME (DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2)
#ifdef _MSC_VER
#define DRMP3_INLINE __forceinline
#elif defined(__GNUC__)
/*
I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
I am using "__inline__" only when we're compiling in strict ANSI mode.
*/
#if defined(__STRICT_ANSI__)
#define DRMP3_INLINE __inline__ __attribute__((always_inline))
#else
#define DRMP3_INLINE inline __attribute__((always_inline))
#endif
#else
#define DRMP3_INLINE
#endif
DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision);
DRMP3_API const char* drmp3_version_string(void);
/*
Low Level Push API
==================
*/
typedef struct
{
int frame_bytes, channels, hz, layer, bitrate_kbps;
} drmp3dec_frame_info;
typedef struct
{
float mdct_overlap[2][9*32], qmf_state[15*2*32];
int reserv, free_format_bytes;
drmp3_uint8 header[4], reserv_buf[511];
} drmp3dec;
/* Initializes a low level decoder. */
DRMP3_API void drmp3dec_init(drmp3dec *dec);
/* Reads a frame from a low level decoder. */
DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info);
/* Helper for converting between f32 and s16. */
DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples);
/*
Main API (Pull API)
===================
*/
#ifndef DRMP3_DEFAULT_CHANNELS
#define DRMP3_DEFAULT_CHANNELS 2
#endif
#ifndef DRMP3_DEFAULT_SAMPLE_RATE
#define DRMP3_DEFAULT_SAMPLE_RATE 44100
#endif
typedef enum
{
drmp3_seek_origin_start,
drmp3_seek_origin_current
} drmp3_seek_origin;
typedef struct
{
drmp3_uint64 seekPosInBytes; /* Points to the first byte of an MP3 frame. */
drmp3_uint64 pcmFrameIndex; /* The index of the PCM frame this seek point targets. */
drmp3_uint16 mp3FramesToDiscard; /* The number of whole MP3 frames to be discarded before pcmFramesToDiscard. */
drmp3_uint16 pcmFramesToDiscard; /* The number of leading samples to read and discard. These are discarded after mp3FramesToDiscard. */
} drmp3_seek_point;
/*
Callback for when data is read. Return value is the number of bytes actually read.
pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family.
pBufferOut [out] The output buffer.
bytesToRead [in] The number of bytes to read.
Returns the number of bytes actually read.
A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until
either the entire bytesToRead is filled or you have reached the end of the stream.
*/
typedef size_t (* drmp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
/*
Callback for when data needs to be seeked.
pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family.
offset [in] The number of bytes to move, relative to the origin. Will never be negative.
origin [in] The origin of the seek - the current position or the start of the stream.
Returns whether or not the seek was successful.
Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which
will be either drmp3_seek_origin_start or drmp3_seek_origin_current.
*/
typedef drmp3_bool32 (* drmp3_seek_proc)(void* pUserData, int offset, drmp3_seek_origin origin);
typedef struct
{
void* pUserData;
void* (* onMalloc)(size_t sz, void* pUserData);
void* (* onRealloc)(void* p, size_t sz, void* pUserData);
void (* onFree)(void* p, void* pUserData);
} drmp3_allocation_callbacks;
typedef struct
{
drmp3_uint32 channels;
drmp3_uint32 sampleRate;
} drmp3_config;
typedef struct
{
drmp3dec decoder;
drmp3dec_frame_info frameInfo;
drmp3_uint32 channels;
drmp3_uint32 sampleRate;
drmp3_read_proc onRead;
drmp3_seek_proc onSeek;
void* pUserData;
drmp3_allocation_callbacks allocationCallbacks;
drmp3_uint32 mp3FrameChannels; /* The number of channels in the currently loaded MP3 frame. Internal use only. */
drmp3_uint32 mp3FrameSampleRate; /* The sample rate of the currently loaded MP3 frame. Internal use only. */
drmp3_uint32 pcmFramesConsumedInMP3Frame;
drmp3_uint32 pcmFramesRemainingInMP3Frame;
drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME]; /* <-- Multipled by sizeof(float) to ensure there's enough room for DR_MP3_FLOAT_OUTPUT. */
drmp3_uint64 currentPCMFrame; /* The current PCM frame, globally, based on the output sample rate. Mainly used for seeking. */
drmp3_uint64 streamCursor; /* The current byte the decoder is sitting on in the raw stream. */
drmp3_seek_point* pSeekPoints; /* NULL by default. Set with drmp3_bind_seek_table(). Memory is owned by the client. dr_mp3 will never attempt to free this pointer. */
drmp3_uint32 seekPointCount; /* The number of items in pSeekPoints. When set to 0 assumes to no seek table. Defaults to zero. */
size_t dataSize;
size_t dataCapacity;
size_t dataConsumed;
drmp3_uint8* pData;
drmp3_bool32 atEnd : 1;
struct
{
const drmp3_uint8* pData;
size_t dataSize;
size_t currentReadPos;
} memory; /* Only used for decoders that were opened against a block of memory. */
} drmp3;
/*
Initializes an MP3 decoder.
onRead [in] The function to call when data needs to be read from the client.
onSeek [in] The function to call when the read position of the client data needs to move.
pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
Returns true if successful; false otherwise.
Close the loader with drmp3_uninit().
See also: drmp3_init_file(), drmp3_init_memory(), drmp3_uninit()
*/
DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks);
/*
Initializes an MP3 decoder from a block of memory.
This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
the lifetime of the drmp3 object.
The buffer should contain the contents of the entire MP3 file.
*/
DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifndef DR_MP3_NO_STDIO
/*
Initializes an MP3 decoder from a file.
This holds the internal FILE object until drmp3_uninit() is called. Keep this in mind if you're caching drmp3
objects because the operating system may restrict the number of file handles an application can have open at
any given time.
*/
DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
#endif
/*
Uninitializes an MP3 decoder.
*/
DRMP3_API void drmp3_uninit(drmp3* pMP3);
/*
Reads PCM frames as interleaved 32-bit IEEE floating point PCM.
Note that framesToRead specifies the number of PCM frames to read, _not_ the number of MP3 frames.
*/
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut);
/*
Reads PCM frames as interleaved signed 16-bit integer PCM.
Note that framesToRead specifies the number of PCM frames to read, _not_ the number of MP3 frames.
*/
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut);
/*
Seeks to a specific frame.
Note that this is _not_ an MP3 frame, but rather a PCM frame.
*/
DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex);
/*
Calculates the total number of PCM frames in the MP3 stream. Cannot be used for infinite streams such as internet
radio. Runs in linear time. Returns 0 on error.
*/
DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3);
/*
Calculates the total number of MP3 frames in the MP3 stream. Cannot be used for infinite streams such as internet
radio. Runs in linear time. Returns 0 on error.
*/
DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3);
/*
Calculates the total number of MP3 and PCM frames in the MP3 stream. Cannot be used for infinite streams such as internet
radio. Runs in linear time. Returns 0 on error.
This is equivalent to calling drmp3_get_mp3_frame_count() and drmp3_get_pcm_frame_count() except that it's more efficient.
*/
DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount);
/*
Calculates the seekpoints based on PCM frames. This is slow.
pSeekpoint count is a pointer to a uint32 containing the seekpoint count. On input it contains the desired count.
On output it contains the actual count. The reason for this design is that the client may request too many
seekpoints, in which case dr_mp3 will return a corrected count.
Note that seektable seeking is not quite sample exact when the MP3 stream contains inconsistent sample rates.
*/
DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints);
/*
Binds a seek table to the decoder.
This does _not_ make a copy of pSeekPoints - it only references it. It is up to the application to ensure this
remains valid while it is bound to the decoder.
Use drmp3_calculate_seek_points() to calculate the seek points.
*/
DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints);
/*
Opens an decodes an entire MP3 stream as a single operation.
On output pConfig will receive the channel count and sample rate of the stream.
Free the returned pointer with drmp3_free().
*/
DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifndef DR_MP3_NO_STDIO
DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
#endif
/*
Allocates a block of memory on the heap.
*/
DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks);
/*
Frees any memory that was allocated by a public drmp3 API.
*/
DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifdef __cplusplus
}
#endif
#endif /* dr_mp3_h */
/************************************************************************************************************************************************************
************************************************************************************************************************************************************
IMPLEMENTATION
************************************************************************************************************************************************************
************************************************************************************************************************************************************/
#if defined(DR_MP3_IMPLEMENTATION) || defined(DRMP3_IMPLEMENTATION)
#ifndef dr_mp3_c
#define dr_mp3_c
#include <stdlib.h>
#include <string.h>
#include <limits.h> /* For INT_MAX */
DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision)
{
if (pMajor) {
*pMajor = DRMP3_VERSION_MAJOR;
}
if (pMinor) {
*pMinor = DRMP3_VERSION_MINOR;
}
if (pRevision) {
*pRevision = DRMP3_VERSION_REVISION;
}
}
DRMP3_API const char* drmp3_version_string(void)
{
return DRMP3_VERSION_STRING;
}
/* Disable SIMD when compiling with TCC for now. */
#if defined(__TINYC__)
#define DR_MP3_NO_SIMD
#endif
#define DRMP3_OFFSET_PTR(p, offset) ((void*)((drmp3_uint8*)(p) + (offset)))
#define DRMP3_MAX_FREE_FORMAT_FRAME_SIZE 2304 /* more than ISO spec's */
#ifndef DRMP3_MAX_FRAME_SYNC_MATCHES
#define DRMP3_MAX_FRAME_SYNC_MATCHES 10
#endif
#define DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES DRMP3_MAX_FREE_FORMAT_FRAME_SIZE /* MUST be >= 320000/8/32000*1152 = 1440 */
#define DRMP3_MAX_BITRESERVOIR_BYTES 511
#define DRMP3_SHORT_BLOCK_TYPE 2
#define DRMP3_STOP_BLOCK_TYPE 3
#define DRMP3_MODE_MONO 3
#define DRMP3_MODE_JOINT_STEREO 1
#define DRMP3_HDR_SIZE 4
#define DRMP3_HDR_IS_MONO(h) (((h[3]) & 0xC0) == 0xC0)
#define DRMP3_HDR_IS_MS_STEREO(h) (((h[3]) & 0xE0) == 0x60)
#define DRMP3_HDR_IS_FREE_FORMAT(h) (((h[2]) & 0xF0) == 0)
#define DRMP3_HDR_IS_CRC(h) (!((h[1]) & 1))
#define DRMP3_HDR_TEST_PADDING(h) ((h[2]) & 0x2)
#define DRMP3_HDR_TEST_MPEG1(h) ((h[1]) & 0x8)
#define DRMP3_HDR_TEST_NOT_MPEG25(h) ((h[1]) & 0x10)
#define DRMP3_HDR_TEST_I_STEREO(h) ((h[3]) & 0x10)
#define DRMP3_HDR_TEST_MS_STEREO(h) ((h[3]) & 0x20)
#define DRMP3_HDR_GET_STEREO_MODE(h) (((h[3]) >> 6) & 3)
#define DRMP3_HDR_GET_STEREO_MODE_EXT(h) (((h[3]) >> 4) & 3)
#define DRMP3_HDR_GET_LAYER(h) (((h[1]) >> 1) & 3)
#define DRMP3_HDR_GET_BITRATE(h) ((h[2]) >> 4)
#define DRMP3_HDR_GET_SAMPLE_RATE(h) (((h[2]) >> 2) & 3)
#define DRMP3_HDR_GET_MY_SAMPLE_RATE(h) (DRMP3_HDR_GET_SAMPLE_RATE(h) + (((h[1] >> 3) & 1) + ((h[1] >> 4) & 1))*3)
#define DRMP3_HDR_IS_FRAME_576(h) ((h[1] & 14) == 2)
#define DRMP3_HDR_IS_LAYER_1(h) ((h[1] & 6) == 6)
#define DRMP3_BITS_DEQUANTIZER_OUT -1
#define DRMP3_MAX_SCF (255 + DRMP3_BITS_DEQUANTIZER_OUT*4 - 210)
#define DRMP3_MAX_SCFI ((DRMP3_MAX_SCF + 3) & ~3)
#define DRMP3_MIN(a, b) ((a) > (b) ? (b) : (a))
#define DRMP3_MAX(a, b) ((a) < (b) ? (b) : (a))
#if !defined(DR_MP3_NO_SIMD)
#if !defined(DR_MP3_ONLY_SIMD) && (defined(_M_X64) || defined(_M_ARM64) || defined(__x86_64__) || defined(__aarch64__))
/* x64 always have SSE2, arm64 always have neon, no need for generic code */
#define DR_MP3_ONLY_SIMD
#endif
#if ((defined(_MSC_VER) && _MSC_VER >= 1400) && (defined(_M_IX86) || defined(_M_X64))) || ((defined(__i386__) || defined(__x86_64__)) && defined(__SSE2__))
#if defined(_MSC_VER)
#include <intrin.h>
#endif
#include <emmintrin.h>
#define DRMP3_HAVE_SSE 1
#define DRMP3_HAVE_SIMD 1
#define DRMP3_VSTORE _mm_storeu_ps
#define DRMP3_VLD _mm_loadu_ps
#define DRMP3_VSET _mm_set1_ps
#define DRMP3_VADD _mm_add_ps
#define DRMP3_VSUB _mm_sub_ps
#define DRMP3_VMUL _mm_mul_ps
#define DRMP3_VMAC(a, x, y) _mm_add_ps(a, _mm_mul_ps(x, y))
#define DRMP3_VMSB(a, x, y) _mm_sub_ps(a, _mm_mul_ps(x, y))
#define DRMP3_VMUL_S(x, s) _mm_mul_ps(x, _mm_set1_ps(s))
#define DRMP3_VREV(x) _mm_shuffle_ps(x, x, _MM_SHUFFLE(0, 1, 2, 3))
typedef __m128 drmp3_f4;
#if defined(_MSC_VER) || defined(DR_MP3_ONLY_SIMD)
#define drmp3_cpuid __cpuid
#else
static __inline__ __attribute__((always_inline)) void drmp3_cpuid(int CPUInfo[], const int InfoType)
{
#if defined(__PIC__)
__asm__ __volatile__(
#if defined(__x86_64__)
"push %%rbx\n"
"cpuid\n"
"xchgl %%ebx, %1\n"
"pop %%rbx\n"
#else
"xchgl %%ebx, %1\n"
"cpuid\n"
"xchgl %%ebx, %1\n"
#endif
: "=a" (CPUInfo[0]), "=r" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
: "a" (InfoType));
#else
__asm__ __volatile__(
"cpuid"
: "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
: "a" (InfoType));
#endif
}
#endif
static int drmp3_have_simd(void)
{
#ifdef DR_MP3_ONLY_SIMD
return 1;
#else
static int g_have_simd;
int CPUInfo[4];
#ifdef MINIMP3_TEST
static int g_counter;
if (g_counter++ > 100)
return 0;
#endif
if (g_have_simd)
goto end;
drmp3_cpuid(CPUInfo, 0);
if (CPUInfo[0] > 0)
{
drmp3_cpuid(CPUInfo, 1);
g_have_simd = (CPUInfo[3] & (1 << 26)) + 1; /* SSE2 */
return g_have_simd - 1;
}
end:
return g_have_simd - 1;
#endif
}
#elif defined(__ARM_NEON) || defined(__aarch64__)
#include <arm_neon.h>
#define DRMP3_HAVE_SSE 0
#define DRMP3_HAVE_SIMD 1
#define DRMP3_VSTORE vst1q_f32
#define DRMP3_VLD vld1q_f32
#define DRMP3_VSET vmovq_n_f32
#define DRMP3_VADD vaddq_f32
#define DRMP3_VSUB vsubq_f32
#define DRMP3_VMUL vmulq_f32
#define DRMP3_VMAC(a, x, y) vmlaq_f32(a, x, y)
#define DRMP3_VMSB(a, x, y) vmlsq_f32(a, x, y)
#define DRMP3_VMUL_S(x, s) vmulq_f32(x, vmovq_n_f32(s))
#define DRMP3_VREV(x) vcombine_f32(vget_high_f32(vrev64q_f32(x)), vget_low_f32(vrev64q_f32(x)))
typedef float32x4_t drmp3_f4;
static int drmp3_have_simd(void)
{ /* TODO: detect neon for !DR_MP3_ONLY_SIMD */
return 1;
}
#else
#define DRMP3_HAVE_SSE 0
#define DRMP3_HAVE_SIMD 0
#ifdef DR_MP3_ONLY_SIMD
#error DR_MP3_ONLY_SIMD used, but SSE/NEON not enabled
#endif
#endif
#else
#define DRMP3_HAVE_SIMD 0
#endif
#if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) && !defined(__aarch64__)
#define DRMP3_HAVE_ARMV6 1
static __inline__ __attribute__((always_inline)) drmp3_int32 drmp3_clip_int16_arm(int32_t a)
{
drmp3_int32 x = 0;
__asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
return x;
}
#endif
typedef struct
{
const drmp3_uint8 *buf;
int pos, limit;
} drmp3_bs;
typedef struct
{
float scf[3*64];
drmp3_uint8 total_bands, stereo_bands, bitalloc[64], scfcod[64];
} drmp3_L12_scale_info;
typedef struct
{
drmp3_uint8 tab_offset, code_tab_width, band_count;
} drmp3_L12_subband_alloc;
typedef struct
{
const drmp3_uint8 *sfbtab;
drmp3_uint16 part_23_length, big_values, scalefac_compress;
drmp3_uint8 global_gain, block_type, mixed_block_flag, n_long_sfb, n_short_sfb;
drmp3_uint8 table_select[3], region_count[3], subblock_gain[3];
drmp3_uint8 preflag, scalefac_scale, count1_table, scfsi;
} drmp3_L3_gr_info;
typedef struct
{
drmp3_bs bs;
drmp3_uint8 maindata[DRMP3_MAX_BITRESERVOIR_BYTES + DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES];
drmp3_L3_gr_info gr_info[4];
float grbuf[2][576], scf[40], syn[18 + 15][2*32];
drmp3_uint8 ist_pos[2][39];
} drmp3dec_scratch;
static void drmp3_bs_init(drmp3_bs *bs, const drmp3_uint8 *data, int bytes)
{
bs->buf = data;
bs->pos = 0;
bs->limit = bytes*8;
}
static drmp3_uint32 drmp3_bs_get_bits(drmp3_bs *bs, int n)
{
drmp3_uint32 next, cache = 0, s = bs->pos & 7;
int shl = n + s;
const drmp3_uint8 *p = bs->buf + (bs->pos >> 3);
if ((bs->pos += n) > bs->limit)
return 0;
next = *p++ & (255 >> s);
while ((shl -= 8) > 0)
{
cache |= next << shl;
next = *p++;
}
return cache | (next >> -shl);
}
static int drmp3_hdr_valid(const drmp3_uint8 *h)
{
return h[0] == 0xff &&
((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
(DRMP3_HDR_GET_LAYER(h) != 0) &&
(DRMP3_HDR_GET_BITRATE(h) != 15) &&
(DRMP3_HDR_GET_SAMPLE_RATE(h) != 3);
}
static int drmp3_hdr_compare(const drmp3_uint8 *h1, const drmp3_uint8 *h2)
{
return drmp3_hdr_valid(h2) &&
((h1[1] ^ h2[1]) & 0xFE) == 0 &&
((h1[2] ^ h2[2]) & 0x0C) == 0 &&
!(DRMP3_HDR_IS_FREE_FORMAT(h1) ^ DRMP3_HDR_IS_FREE_FORMAT(h2));
}
static unsigned drmp3_hdr_bitrate_kbps(const drmp3_uint8 *h)
{
static const drmp3_uint8 halfrate[2][3][15] = {
{ { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,16,24,28,32,40,48,56,64,72,80,88,96,112,128 } },
{ { 0,16,20,24,28,32,40,48,56,64,80,96,112,128,160 }, { 0,16,24,28,32,40,48,56,64,80,96,112,128,160,192 }, { 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224 } },
};
return 2*halfrate[!!DRMP3_HDR_TEST_MPEG1(h)][DRMP3_HDR_GET_LAYER(h) - 1][DRMP3_HDR_GET_BITRATE(h)];
}
static unsigned drmp3_hdr_sample_rate_hz(const drmp3_uint8 *h)
{
static const unsigned g_hz[3] = { 44100, 48000, 32000 };
return g_hz[DRMP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!DRMP3_HDR_TEST_MPEG1(h) >> (int)!DRMP3_HDR_TEST_NOT_MPEG25(h);
}
static unsigned drmp3_hdr_frame_samples(const drmp3_uint8 *h)
{
return DRMP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)DRMP3_HDR_IS_FRAME_576(h));
}
static int drmp3_hdr_frame_bytes(const drmp3_uint8 *h, int free_format_size)
{
int frame_bytes = drmp3_hdr_frame_samples(h)*drmp3_hdr_bitrate_kbps(h)*125/drmp3_hdr_sample_rate_hz(h);
if (DRMP3_HDR_IS_LAYER_1(h))
{
frame_bytes &= ~3; /* slot align */
}
return frame_bytes ? frame_bytes : free_format_size;
}
static int drmp3_hdr_padding(const drmp3_uint8 *h)
{
return DRMP3_HDR_TEST_PADDING(h) ? (DRMP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0;
}
#ifndef DR_MP3_ONLY_MP3
static const drmp3_L12_subband_alloc *drmp3_L12_subband_alloc_table(const drmp3_uint8 *hdr, drmp3_L12_scale_info *sci)
{
const drmp3_L12_subband_alloc *alloc;
int mode = DRMP3_HDR_GET_STEREO_MODE(hdr);
int nbands, stereo_bands = (mode == DRMP3_MODE_MONO) ? 0 : (mode == DRMP3_MODE_JOINT_STEREO) ? (DRMP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32;
if (DRMP3_HDR_IS_LAYER_1(hdr))
{
static const drmp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } };
alloc = g_alloc_L1;
nbands = 32;
} else if (!DRMP3_HDR_TEST_MPEG1(hdr))
{
static const drmp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } };
alloc = g_alloc_L2M2;
nbands = 30;
} else
{
static const drmp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } };
int sample_rate_idx = DRMP3_HDR_GET_SAMPLE_RATE(hdr);
unsigned kbps = drmp3_hdr_bitrate_kbps(hdr) >> (int)(mode != DRMP3_MODE_MONO);
if (!kbps) /* free-format */
{
kbps = 192;
}
alloc = g_alloc_L2M1;
nbands = 27;
if (kbps < 56)
{
static const drmp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } };
alloc = g_alloc_L2M1_lowrate;
nbands = sample_rate_idx == 2 ? 12 : 8;
} else if (kbps >= 96 && sample_rate_idx != 1)
{
nbands = 30;
}
}
sci->total_bands = (drmp3_uint8)nbands;
sci->stereo_bands = (drmp3_uint8)DRMP3_MIN(stereo_bands, nbands);
return alloc;
}
static void drmp3_L12_read_scalefactors(drmp3_bs *bs, drmp3_uint8 *pba, drmp3_uint8 *scfcod, int bands, float *scf)
{
static const float g_deq_L12[18*3] = {
#define DRMP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x
DRMP3_DQ(3),DRMP3_DQ(7),DRMP3_DQ(15),DRMP3_DQ(31),DRMP3_DQ(63),DRMP3_DQ(127),DRMP3_DQ(255),DRMP3_DQ(511),DRMP3_DQ(1023),DRMP3_DQ(2047),DRMP3_DQ(4095),DRMP3_DQ(8191),DRMP3_DQ(16383),DRMP3_DQ(32767),DRMP3_DQ(65535),DRMP3_DQ(3),DRMP3_DQ(5),DRMP3_DQ(9)
};
int i, m;
for (i = 0; i < bands; i++)
{
float s = 0;
int ba = *pba++;
int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0;
for (m = 4; m; m >>= 1)
{
if (mask & m)
{
int b = drmp3_bs_get_bits(bs, 6);
s = g_deq_L12[ba*3 - 6 + b % 3]*(int)(1 << 21 >> b/3);
}
*scf++ = s;
}
}
}
static void drmp3_L12_read_scale_info(const drmp3_uint8 *hdr, drmp3_bs *bs, drmp3_L12_scale_info *sci)
{
static const drmp3_uint8 g_bitalloc_code_tab[] = {
0,17, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16,
0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,16,
0,17,18, 3,19,4,5,16,
0,17,18,16,
0,17,18,19, 4,5,6, 7,8, 9,10,11,12,13,14,15,
0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,14,
0, 2, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16
};
const drmp3_L12_subband_alloc *subband_alloc = drmp3_L12_subband_alloc_table(hdr, sci);
int i, k = 0, ba_bits = 0;
const drmp3_uint8 *ba_code_tab = g_bitalloc_code_tab;
for (i = 0; i < sci->total_bands; i++)
{
drmp3_uint8 ba;
if (i == k)
{
k += subband_alloc->band_count;
ba_bits = subband_alloc->code_tab_width;
ba_code_tab = g_bitalloc_code_tab + subband_alloc->tab_offset;
subband_alloc++;
}
ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
sci->bitalloc[2*i] = ba;
if (i < sci->stereo_bands)
{
ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
}
sci->bitalloc[2*i + 1] = sci->stereo_bands ? ba : 0;
}
for (i = 0; i < 2*sci->total_bands; i++)
{
sci->scfcod[i] = (drmp3_uint8)(sci->bitalloc[i] ? DRMP3_HDR_IS_LAYER_1(hdr) ? 2 : drmp3_bs_get_bits(bs, 2) : 6);
}
drmp3_L12_read_scalefactors(bs, sci->bitalloc, sci->scfcod, sci->total_bands*2, sci->scf);
for (i = sci->stereo_bands; i < sci->total_bands; i++)
{
sci->bitalloc[2*i + 1] = 0;
}
}
static int drmp3_L12_dequantize_granule(float *grbuf, drmp3_bs *bs, drmp3_L12_scale_info *sci, int group_size)
{
int i, j, k, choff = 576;
for (j = 0; j < 4; j++)
{
float *dst = grbuf + group_size*j;
for (i = 0; i < 2*sci->total_bands; i++)
{
int ba = sci->bitalloc[i];
if (ba != 0)
{
if (ba < 17)
{
int half = (1 << (ba - 1)) - 1;
for (k = 0; k < group_size; k++)
{
dst[k] = (float)((int)drmp3_bs_get_bits(bs, ba) - half);
}
} else
{
unsigned mod = (2 << (ba - 17)) + 1; /* 3, 5, 9 */
unsigned code = drmp3_bs_get_bits(bs, mod + 2 - (mod >> 3)); /* 5, 7, 10 */
for (k = 0; k < group_size; k++, code /= mod)
{
dst[k] = (float)((int)(code % mod - mod/2));
}
}
}
dst += choff;
choff = 18 - choff;
}
}
return group_size*4;
}
static void drmp3_L12_apply_scf_384(drmp3_L12_scale_info *sci, const float *scf, float *dst)
{
int i, k;
memcpy(dst + 576 + sci->stereo_bands*18, dst + sci->stereo_bands*18, (sci->total_bands - sci->stereo_bands)*18*sizeof(float));
for (i = 0; i < sci->total_bands; i++, dst += 18, scf += 6)
{
for (k = 0; k < 12; k++)
{
dst[k + 0] *= scf[0];
dst[k + 576] *= scf[3];
}
}
}
#endif
static int drmp3_L3_read_side_info(drmp3_bs *bs, drmp3_L3_gr_info *gr, const drmp3_uint8 *hdr)
{
static const drmp3_uint8 g_scf_long[8][23] = {