forked from sbooth/SFBAudioEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSFBMPEGDecoder.m
365 lines (289 loc) · 10.6 KB
/
SFBMPEGDecoder.m
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
//
// Copyright (c) 2006-2025 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
@import os.log;
// TODO: Figure out a way to selectively disable diagnostic warnings for module imports
@import mpg123;
@import AVFAudioExtensions;
#import "SFBMPEGDecoder.h"
#import "NSData+SFBExtensions.h"
#import "NSError+SFBURLPresentation.h"
SFBAudioDecoderName const SFBAudioDecoderNameMPEG = @"org.sbooth.AudioEngine.Decoder.MPEG";
// ========================================
// Initialization
static void Setupmpg123(void) __attribute__ ((constructor));
static void Setupmpg123(void)
{
// What happens if this fails?
int result = mpg123_init();
if(result != MPG123_OK)
os_log_error(gSFBAudioDecoderLog, "Unable to initialize mpg123: %{public}s", mpg123_plain_strerror(result));
}
static void Teardownmpg123(void) __attribute__ ((destructor));
static void Teardownmpg123(void)
{
mpg123_exit();
}
// ========================================
// Callbacks
static ssize_t read_callback(void *iohandle, void *ptr, size_t size)
{
NSCParameterAssert(iohandle != NULL);
SFBMPEGDecoder *decoder = (__bridge SFBMPEGDecoder *)iohandle;
NSInteger bytesRead;
if(![decoder->_inputSource readBytes:ptr length:(NSInteger)size bytesRead:&bytesRead error:nil])
return -1;
return (ssize_t)bytesRead;
}
static off_t lseek_callback(void *iohandle, off_t offset, int whence)
{
NSCParameterAssert(iohandle != NULL);
SFBMPEGDecoder *decoder = (__bridge SFBMPEGDecoder *)iohandle;
if(!decoder->_inputSource.supportsSeeking)
return -1;
// Adjust offset as required
switch(whence) {
case SEEK_SET:
// offset remains unchanged
break;
case SEEK_CUR: {
NSInteger inputSourceOffset;
if([decoder->_inputSource getOffset:&inputSourceOffset error:nil])
offset += inputSourceOffset;
break;
}
case SEEK_END: {
NSInteger inputSourceLength;
if([decoder->_inputSource getLength:&inputSourceLength error:nil])
offset += inputSourceLength;
break;
}
}
if(![decoder->_inputSource seekToOffset:offset error:nil])
return -1;
return offset;
}
@interface SFBMPEGDecoder ()
{
@private
mpg123_handle *_mpg123;
AVAudioFramePosition _framePosition;
AVAudioPCMBuffer *_buffer;
}
@end
@implementation SFBMPEGDecoder
+ (void)load
{
[SFBAudioDecoder registerSubclass:[self class]];
}
+ (NSSet *)supportedPathExtensions
{
return [NSSet setWithObject:@"mp3"];
}
+ (NSSet *)supportedMIMETypes
{
return [NSSet setWithObject:@"audio/mpeg"];
}
+ (SFBAudioDecoderName)decoderName
{
return SFBAudioDecoderNameMPEG;
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
NSParameterAssert(formatIsSupported != NULL);
NSData *header = [inputSource readHeaderOfLength:SFBMP3DetectionSize skipID3v2Tag:YES error:error];
if(!header)
return NO;
if([header isMP3Header])
*formatIsSupported = SFBTernaryTruthValueTrue;
else
*formatIsSupported = SFBTernaryTruthValueFalse;
return YES;
}
- (BOOL)decodingIsLossless
{
return NO;
}
- (BOOL)openReturningError:(NSError **)error
{
if(![super openReturningError:error])
return NO;
_mpg123 = mpg123_new(NULL, NULL);
if(!_mpg123) {
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid MP3 file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid MP3 file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
// Force decode to floating point instead of 16-bit signed integer
mpg123_param(_mpg123, MPG123_FLAGS, MPG123_FORCE_FLOAT | MPG123_SKIP_ID3V2 | MPG123_GAPLESS | MPG123_QUIET, 0);
mpg123_param(_mpg123, MPG123_RESYNC_LIMIT, 2048, 0);
if(mpg123_replace_reader_handle(_mpg123, read_callback, lseek_callback, NULL) != MPG123_OK) {
mpg123_delete(_mpg123);
_mpg123 = NULL;
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid MP3 file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid MP3 file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
if(mpg123_open_handle(_mpg123, (__bridge void *)self) != MPG123_OK) {
mpg123_delete(_mpg123);
_mpg123 = NULL;
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid MP3 file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid MP3 file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
long rate;
int channels, encoding;
if(mpg123_getformat(_mpg123, &rate, &channels, &encoding) != MPG123_OK || encoding != MPG123_ENC_FLOAT_32 || channels <= 0) {
mpg123_close(_mpg123);
mpg123_delete(_mpg123);
_mpg123 = NULL;
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid MP3 file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid MP3 file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
AVAudioChannelLayout *channelLayout = nil;
switch(channels) {
case 1: channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_Mono]; break;
case 2: channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_Stereo]; break;
default:
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:(kAudioChannelLayoutTag_Unknown | (UInt32)channels)];
break;
}
_processingFormat = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32 sampleRate:rate interleaved:NO channelLayout:channelLayout];
size_t bufferSizeBytes = mpg123_outblock(_mpg123);
UInt32 framesPerMPEGFrame = (UInt32)(bufferSizeBytes / ((size_t)channels * sizeof(float)));
// Set up the source format
AudioStreamBasicDescription sourceStreamDescription = {0};
sourceStreamDescription.mFormatID = kAudioFormatMPEGLayer3;
struct mpg123_frameinfo mi;
if(mpg123_info(_mpg123, &mi) == MPG123_OK) {
switch(mi.layer) {
case 1: sourceStreamDescription.mFormatID = kAudioFormatMPEGLayer1; break;
case 2: sourceStreamDescription.mFormatID = kAudioFormatMPEGLayer2; break;
case 3: sourceStreamDescription.mFormatID = kAudioFormatMPEGLayer3; break;
}
}
sourceStreamDescription.mSampleRate = rate;
sourceStreamDescription.mChannelsPerFrame = (UInt32)channels;
sourceStreamDescription.mFramesPerPacket = framesPerMPEGFrame;
_sourceFormat = [[AVAudioFormat alloc] initWithStreamDescription:&sourceStreamDescription channelLayout:channelLayout];
if(mpg123_scan(_mpg123) != MPG123_OK) {
mpg123_close(_mpg123);
mpg123_delete(_mpg123);
_mpg123 = NULL;
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid MP3 file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid MP3 file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
_buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:_processingFormat frameCapacity:framesPerMPEGFrame];
_buffer.frameLength = 0;
return YES;
}
- (BOOL)closeReturningError:(NSError **)error
{
if(_mpg123) {
mpg123_close(_mpg123);
mpg123_delete(_mpg123);
_mpg123 = NULL;
}
return [super closeReturningError:error];
}
- (BOOL)isOpen
{
return _mpg123 != NULL;
}
- (AVAudioFramePosition)framePosition
{
return _framePosition;
}
- (AVAudioFramePosition)frameLength
{
return mpg123_length(_mpg123);
}
- (BOOL)decodeIntoBuffer:(AVAudioPCMBuffer *)buffer frameLength:(AVAudioFrameCount)frameLength error:(NSError **)error
{
NSParameterAssert(buffer != nil);
NSParameterAssert([buffer.format isEqual:_processingFormat]);
// Reset output buffer data size
buffer.frameLength = 0;
if(frameLength > buffer.frameCapacity)
frameLength = buffer.frameCapacity;
if(frameLength == 0)
return YES;
AVAudioFrameCount framesProcessed = 0;
for(;;) {
AVAudioFrameCount framesRemaining = frameLength - framesProcessed;
AVAudioFrameCount framesCopied = [buffer appendFromBuffer:_buffer readingFromOffset:0 frameLength:framesRemaining];
[_buffer trimAtOffset:0 frameLength:framesCopied];
framesProcessed += framesCopied;
// All requested frames were read
if(framesProcessed == frameLength)
break;
// Read and decode an MPEG frame
off_t frameNumber;
unsigned char *audioData = NULL;
size_t bytesDecoded = 0;
int result = mpg123_decode_frame(_mpg123, &frameNumber, &audioData, &bytesDecoded);
// EOS
if(result == MPG123_DONE)
break;
else if(result != MPG123_OK) {
os_log_error(gSFBAudioDecoderLog, "mpg123_decode_frame failed: %{public}s", mpg123_strerror(_mpg123));
if(error)
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain code:SFBAudioDecoderErrorCodeInternalError userInfo:@{ NSURLErrorKey: _inputSource.url }];
return NO;
}
// Deinterleave the samples
AVAudioFrameCount framesDecoded = (AVAudioFrameCount)(bytesDecoded / (sizeof(float) * _buffer.format.channelCount));
float * const *floatChannelData = _buffer.floatChannelData;
AVAudioChannelCount channelCount = _buffer.format.channelCount;
for(AVAudioChannelCount channel = 0; channel < channelCount; ++channel) {
const float *input = (float *)audioData + channel;
float *output = floatChannelData[channel];
for(AVAudioFrameCount frame = 0; frame < framesDecoded; ++frame) {
*output++ = *input;
input += channelCount;
}
}
_buffer.frameLength = framesDecoded;
}
_framePosition += framesProcessed;
return YES;
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error
{
NSParameterAssert(frame >= 0);
off_t offset = mpg123_seek(_mpg123, frame, SEEK_SET);
if(offset >= 0)
_framePosition = offset;
return offset >= 0;
}
@end