Oolite
Loading...
Searching...
No Matches
OOALSoundDecoder.m
Go to the documentation of this file.
1/*
2
3OOALSoundDecoder.m
4
5
6OOALSound - OpenAL sound implementation for Oolite.
7Copyright (C) 2005-2013 Jens Ayton
8
9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in all
17copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25SOFTWARE.
26
27*/
28
29#import "OOALSoundDecoder.h"
31#import "OOLogging.h"
32#import "unzip.h"
33#import <vorbis/vorbisfile.h>
34
35enum {
36 kMaxDecodeSize = 1 << 20 // 2^20 frames = 4 MB
37};
38
39static size_t OOReadOXZVorbis(void* ptr, size_t size, size_t nmemb, void* datasource);
40static int OOCloseOXZVorbis(void* datasource);
41// not practical to implement these
42// static int OOSeekOXZVorbis (void *datasource, ogg_int64_t offset, int whence);
43// static long OOTellOXZVorbis (void *datasource);
44
46 OggVorbis_File _vf;
47 NSString* _name;
50@public
52}
53
54- (NSDictionary*)comments;
55
56@end
57
58@implementation OOALSoundDecoder
59
60- (id)initWithPath:(NSString*)inPath
61{
62 [self release];
63 self = nil;
64
65 if ([[inPath pathExtension] isEqual:@"ogg"]) {
66 self = [[OOALSoundVorbisCodec alloc] initWithPath:inPath];
67 }
68
69 return self;
70}
71
72+ (OOALSoundDecoder*)codecWithPath:(NSString*)inPath
73{
74 if ([[inPath pathExtension] isEqual:@"ogg"]) {
75 return [[[OOALSoundVorbisCodec alloc] initWithPath:inPath] autorelease];
76 }
77 return nil;
78}
79
80- (size_t)streamToBuffer:(char*)ioBuffer
81{
82 return 0;
83}
84
85- (BOOL)readCreatingBuffer:(char**)outBuffer withFrameCount:(size_t*)outSize
86{
87 if (NULL != outBuffer)
88 *outBuffer = NULL;
89 if (NULL != outSize)
90 *outSize = 0;
91
92 return NO;
93}
94
95- (size_t)sizeAsBuffer
96{
97 return 0;
98}
99
100- (BOOL)isStereo
101{
102 return NO;
103}
104
106{
107 return 0;
108}
109
110- (void)reset
111{
112 // nothing
113}
114
115- (NSString*)name
116{
117 return @"";
118}
119
120@end
121
122@implementation OOALSoundVorbisCodec
123
124- (id)initWithPath:(NSString*)path
125{
126 if ((self = [super init])) {
127 BOOL OK = NO;
128
129 _name = [[path lastPathComponent] retain];
130
131 NSUInteger i, cl;
132 NSArray* components = [path pathComponents];
133 cl = [components count];
134 for (i = 0; i < cl; i++) {
135 NSString* component = [components objectAtIndex:i];
136 if ([[[component pathExtension] lowercaseString] isEqualToString:@"oxz"]) {
137 break;
138 }
139 }
140 // if i == cl then the path is entirely uncompressed
141 if (i == cl) {
142 /* Get vorbis data from a standard file stream */
143 int err;
144 FILE* file;
145
146 _seekableStream = YES;
147
148 if (nil != path) {
149 file = fopen([path UTF8String], "rb");
150 if (NULL != file) {
151 err = ov_open_callbacks(file, &_vf, NULL, 0, OV_CALLBACKS_DEFAULT);
152 if (0 == err) {
153 OK = YES;
154 }
155 }
156 }
157
158 if (!OK) {
159 [self release];
160 self = nil;
161 }
162
163 } else {
164 _seekableStream = NO;
165
166 NSRange range;
167 range.location = 0;
168 range.length = i + 1;
169 NSString* zipFile = [NSString pathWithComponents:[components subarrayWithRange:range]];
170 range.location = i + 1;
171 range.length = cl - (i + 1);
172 NSString* containedFile = [NSString pathWithComponents:[components subarrayWithRange:range]];
173
174 const char* zipname = [zipFile UTF8String];
175 if (zipname != NULL) {
176 uf = unzOpen64(zipname);
177 }
178 if (uf == NULL) {
179 OOLog(kOOLogFileNotFound, @"Could not unzip OXZ at %@", zipFile);
180 [self release];
181 self = nil;
182 } else {
183 const char* filename = [containedFile UTF8String];
184 // unzLocateFile(*, *, 1) = case-sensitive extract
185 if (unzLocateFile(uf, filename, 1) != UNZ_OK) {
186 unzClose(uf);
187 [self release];
188 self = nil;
189 } else {
190 int err = UNZ_OK;
191 unz_file_info64 file_info = { 0 };
192 err = unzGetCurrentFileInfo64(uf, &file_info, NULL, 0, NULL, 0, NULL, 0);
193 if (err != UNZ_OK) {
194 unzClose(uf);
195 OOLog(kOOLogFileNotFound, @"Could not get properties of %@ within OXZ at %@", containedFile, zipFile);
196 [self release];
197 self = nil;
198 } else {
199 err = unzOpenCurrentFile(uf);
200 if (err != UNZ_OK) {
201 unzClose(uf);
202 OOLog(kOOLogFileNotFound, @"Could not read %@ within OXZ at %@", containedFile, zipFile);
203 [self release];
204 self = nil;
205 } else {
206 ov_callbacks _callbacks = {
207 OOReadOXZVorbis, // read sequentially
208 NULL, // no seek
209 OOCloseOXZVorbis, // close file
210 NULL, // no tell
211 };
212 err = ov_open_callbacks(self, &_vf, NULL, 0, _callbacks);
213 if (0 == err) {
214 OK = YES;
215 _readStarted = NO;
216 }
217 if (!OK) {
218 unzClose(uf);
219 [self release];
220 self = nil;
221 }
222 }
223 }
224 }
225 }
226 }
227 }
228#ifdef OOLITE_DEBUG_SOUND_FILE_OPENING
229 if (self != nil) {
230 OOLog(@"sound.retain", @"%@", _name);
231 }
232#endif
233 return self;
234}
235
236- (void)dealloc
237{
238#ifdef OOLITE_DEBUG_SOUND_FILE_OPENING
239 if (self != nil) {
240 OOLog(@"sound.release", @"%@", _name);
241 }
242#endif
243
244 [_name release];
245 ov_clear(&_vf);
246 unzClose(uf);
247
248 [super dealloc];
249}
250
251- (NSDictionary*)comments
252{
253 vorbis_comment* comments;
254 unsigned i, count;
255 NSMutableDictionary* result = nil;
256 NSString *comment, *key, *value;
257 NSRange range;
258
259 comments = ov_comment(&_vf, -1);
260 if (NULL != comments) {
261 count = comments->comments;
262 if (0 != count) {
263 result = [NSMutableDictionary dictionaryWithCapacity:count];
264 for (i = 0; i != count; ++i) {
265 comment = [[NSString alloc] initWithBytesNoCopy:comments->user_comments[i] length:comments->comment_lengths[i] encoding:NSUTF8StringEncoding freeWhenDone:NO];
266 range = [comment rangeOfString:@"="];
267 if (0 != range.length) {
268 key = [comment substringToIndex:range.location];
269 value = [comment substringFromIndex:range.location + 1];
270 } else {
271 key = comment;
272 value = @"";
273 }
274 [result setObject:value forKey:key];
275
276 [comment release];
277 }
278 }
279 }
280
281 return result;
282}
283
284- (BOOL)readCreatingBuffer:(char**)outBuffer withFrameCount:(size_t*)outSize
285{
286 char *buffer = NULL, *dst;
287 size_t sizeInFrames = 0;
288 int remaining;
289 long framesRead;
290 // 16-bit samples, either two or one track
291 int frameSize = [self isStereo] ? 4 : 2;
292 ogg_int64_t totalSizeInFrames;
293 BOOL OK = YES;
294
295 if (NULL != outBuffer)
296 *outBuffer = NULL;
297 if (NULL != outSize)
298 *outSize = 0;
299 if (NULL == outBuffer || NULL == outSize)
300 OK = NO;
301
302 if (OK) {
303 totalSizeInFrames = ov_pcm_total(&_vf, -1);
304 assert((uint64_t)totalSizeInFrames < (uint64_t)SIZE_MAX); // Should have been checked by caller
305 sizeInFrames = (size_t)totalSizeInFrames;
306 }
307
308 if (OK) {
309 buffer = malloc(sizeof(char) * frameSize * sizeInFrames);
310 if (!buffer)
311 OK = NO;
312 }
313
314 if (OK && sizeInFrames) {
315 remaining = (int)MIN(frameSize * sizeInFrames, (size_t)INT_MAX);
316 dst = buffer;
317
318 char pcmout[4096];
319
320 do {
321 int toRead = sizeof(pcmout);
322 if (remaining < toRead) {
323 toRead = remaining;
324 }
325 framesRead = ov_read(&_vf, pcmout, toRead, 0, 2, 1, NULL);
326 if (framesRead <= 0) {
327 if (OV_HOLE == framesRead)
328 continue;
329 // else:
330 break;
331 }
332
333 memcpy(dst, &pcmout, sizeof(char) * framesRead);
334
335 remaining -= framesRead;
336 dst += framesRead;
337 } while (0 < remaining);
338
339 sizeInFrames -= remaining; // In case we stopped at an error
340 }
341
342 if (OK) {
343 *outBuffer = buffer;
344 *outSize = sizeInFrames * frameSize;
345 } else {
346 if (buffer)
347 free(buffer);
348 }
349 return OK;
350}
351
352- (size_t)streamToBuffer:(char*)buffer
353{
354
355 int remaining = OOAL_STREAM_CHUNK_SIZE;
356 size_t streamed = 0;
357 long framesRead;
358
359 char* dst = buffer;
360 char pcmout[4096];
361 _readStarted = YES;
362 do {
363 int toRead = sizeof(pcmout);
364 if (remaining < toRead) {
365 toRead = remaining;
366 }
367 framesRead = ov_read(&_vf, pcmout, toRead, 0, 2, 1, NULL);
368 if (framesRead <= 0) {
369 if (OV_HOLE == framesRead)
370 continue;
371 // else:
372 break;
373 }
374 memcpy(dst, &pcmout, sizeof(char) * framesRead);
375 remaining -= sizeof(char) * framesRead;
376 dst += sizeof(char) * framesRead;
377 streamed += sizeof(char) * framesRead;
378 } while (0 < remaining);
379
380 return streamed;
381}
382
384{
385 ogg_int64_t size;
386 size = ov_pcm_total(&_vf, -1);
387 size *= sizeof(char) * ([self isStereo] ? 4 : 2);
388 if ((uint64_t)SIZE_MAX < (uint64_t)size)
389 size = (ogg_int64_t)SIZE_MAX;
390 return (size_t)size;
391}
392
393- (BOOL)isStereo
394{
395 return 1 < ov_info(&_vf, -1)->channels;
396}
397
398- (NSString*)description
399{
400 return [NSString stringWithFormat:@"<%@ %p>{\"%@\", comments=%@}", [self className], self, _name, [self comments]];
401}
402
404{
405 return ov_info(&_vf, -1)->rate;
406}
407
408- (void)reset
409{
410 if (!_readStarted) {
411 return; // don't need to do anything
412 }
413 if (_seekableStream) {
414 ov_pcm_seek(&_vf, 0);
415 return;
416 }
417 // reset current file pointer in OXZ
419 // reopen OGG streamer
420 ov_clear(&_vf);
421 ov_callbacks _callbacks = {
422 OOReadOXZVorbis, // read sequentially
423 NULL, // no seek
424 OOCloseOXZVorbis, // close file
425 NULL, // no tell
426 };
427 ov_open_callbacks(self, &_vf, NULL, 0, _callbacks);
428 _readStarted = NO;
429}
430
431- (NSString*)name
432{
433 return [[_name retain] autorelease];
434}
435
436@end
437
438static size_t OOReadOXZVorbis(void* ptr, size_t size, size_t nmemb, void* datasource)
439{
440 OOALSoundVorbisCodec* src = (OOALSoundVorbisCodec*)datasource;
441 size_t toRead = size * nmemb;
442 void* buf = (void*)malloc(toRead);
443 int err = UNZ_OK;
444 err = unzReadCurrentFile(src->uf, buf, toRead);
445 // OOLog(@"sound.replay",@"Read %d blocks, got %d",toRead,err);
446 if (err > 0) {
447 memcpy(ptr, buf, err);
448 }
449 if (err < 0) {
450 return OV_EREAD;
451 }
452 return err;
453}
454
455static int OOCloseOXZVorbis(void* datasource)
456{
457 // doing this prevents replaying
458 // OOALSoundVorbisCodec *src = (OOALSoundVorbisCodec *)datasource;
459 // unzClose(src->uf);
460 return 0;
461}
#define OOAL_STREAM_CHUNK_SIZE
@ kMaxDecodeSize
static size_t OOReadOXZVorbis(void *ptr, size_t size, size_t nmemb, void *datasource)
static int OOCloseOXZVorbis(void *datasource)
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogFileNotFound
Definition OOLogging.m:601
#define MIN(A, B)
Definition OOMaths.h:91
unsigned count
return nil
NSDictionary * comments()
voidpf void uLong size
Definition ioapi.h:126
const char * filename
Definition ioapi.h:125
typedef long(ZCALLBACK *tell_file_func) OF((voidpf opaque
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
voidpf void * buf
Definition ioapi.h:126
int ZEXPORT unzLocateFile(unzFile file, const char *szFileName, int iCaseSensitivity)
Definition unzip.c:1161
int ZEXPORT unzGetCurrentFileInfo64(unzFile file, unz_file_info64 *pfile_info, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize)
Definition unzip.c:1058
int ZEXPORT unzOpenCurrentFile(unzFile file)
Definition unzip.c:1558
int ZEXPORT unzReadCurrentFile(unzFile file, voidp buf, unsigned len)
Definition unzip.c:1600
unzFile ZEXPORT unzOpen64(const void *path)
Definition unzip.c:758
int ZEXPORT unzClose(unzFile file)
Definition unzip.c:768
struct unz_file_info64_s unz_file_info64
voidp unzFile
Definition unzip.h:72
#define UNZ_OK
Definition unzip.h:75