/
CDPlayer.c
636 lines (490 loc) · 18.9 KB
1
2
/*
SDL - Simple DirectMedia Layer
3
Copyright (C) 1997-2012 Sam Lantinga
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Sam Lantinga
slouken@libsdl.org
*/
22
#include "SDL_config.h"
23
24
25
#include "CDPlayer.h"
#include "AudioFilePlayer.h"
26
#include "SDLOSXCAGuard.h"
27
28
29
/* we're exporting these functions into C land for SDL_syscdrom.c */
/*extern "C" {*/
30
31
32
33
/*///////////////////////////////////////////////////////////////////////////
Constants
//////////////////////////////////////////////////////////////////////////*/
34
35
#define kAudioCDFilesystemID (UInt16)(('J' << 8) | 'H') /* 'JH'; this avoids compiler warning */
36
37
/* XML PList keys */
38
39
40
41
42
43
44
45
46
47
48
49
#define kRawTOCDataString "Format 0x02 TOC Data"
#define kSessionsString "Sessions"
#define kSessionTypeString "Session Type"
#define kTrackArrayString "Track Array"
#define kFirstTrackInSessionString "First Track"
#define kLastTrackInSessionString "Last Track"
#define kLeadoutBlockString "Leadout Block"
#define kDataKeyString "Data"
#define kPointKeyString "Point"
#define kSessionNumberKeyString "Session Number"
#define kStartBlockKeyString "Start Block"
50
51
52
/*///////////////////////////////////////////////////////////////////////////
Globals
//////////////////////////////////////////////////////////////////////////*/
53
54
55
#pragma mark -- Globals --
56
static int playBackWasInit = 0;
57
58
59
static AudioUnit theUnit;
static AudioFilePlayer* thePlayer = NULL;
static CDPlayerCompletionProc completionProc = NULL;
60
61
static SDL_mutex *apiMutex = NULL;
static SDL_sem *callbackSem;
62
63
static SDL_CD* theCDROM;
64
65
66
/*///////////////////////////////////////////////////////////////////////////
Prototypes
//////////////////////////////////////////////////////////////////////////*/
67
68
69
#pragma mark -- Prototypes --
70
static OSStatus CheckInit ();
71
72
static void FilePlayNotificationHandler (void* inRefCon, OSStatus inStatus);
73
74
static int RunCallBackThread (void* inRefCon);
75
76
77
78
79
80
#pragma mark -- Public Functions --
void Lock ()
{
81
82
if (!apiMutex) {
apiMutex = SDL_CreateMutex();
83
}
84
SDL_mutexP(apiMutex);
85
86
87
88
}
void Unlock ()
{
89
SDL_mutexV(apiMutex);
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
}
int DetectAudioCDVolumes(FSVolumeRefNum *volumes, int numVolumes)
{
int volumeIndex;
int cdVolumeCount = 0;
OSStatus result = noErr;
for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++)
{
FSVolumeRefNum actualVolume;
FSVolumeInfo volumeInfo;
memset (&volumeInfo, 0, sizeof(volumeInfo));
result = FSGetVolumeInfo (kFSInvalidVolumeRefNum,
volumeIndex,
&actualVolume,
kFSVolInfoFSInfo,
&volumeInfo,
110
111
NULL,
NULL);
112
113
114
if (result == noErr)
{
115
if (volumeInfo.filesystemID == kAudioCDFilesystemID) /* It's an audio CD */
116
{
117
118
119
120
121
122
123
124
if (volumes != NULL && cdVolumeCount < numVolumes)
volumes[cdVolumeCount] = actualVolume;
cdVolumeCount++;
}
}
else
{
125
126
/* I'm commenting this out because it seems to be harmless */
/*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result);*/
127
128
129
130
131
132
133
134
135
136
}
}
return cdVolumeCount;
}
int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD)
{
HFSUniStr255 dataForkName;
OSStatus theErr;
137
FSIORefNum forkRefNum;
138
139
140
141
142
143
144
SInt64 forkSize;
Ptr forkData = 0;
ByteCount actualRead;
CFDataRef dataRef = 0;
CFPropertyListRef propertyListRef = 0;
FSRefParam fsRefPB;
FSRef tocPlistFSRef;
145
FSRef rootRef;
146
const char* error = "Unspecified Error";
147
148
149
150
151
152
153
154
155
156
const UniChar uniName[] = { '.','T','O','C','.','p','l','i','s','t' };
theErr = FSGetVolumeInfo(theVolume, 0, 0, kFSVolInfoNone, 0, 0, &rootRef);
if(theErr != noErr) {
error = "FSGetVolumeInfo";
goto bail;
}
SDL_memset(&fsRefPB, '\0', sizeof (fsRefPB));
157
/* get stuff from .TOC.plist */
158
fsRefPB.ref = &rootRef;
159
fsRefPB.newRef = &tocPlistFSRef;
160
161
162
163
164
fsRefPB.nameLength = sizeof (uniName) / sizeof (uniName[0]);
fsRefPB.name = uniName;
fsRefPB.textEncodingHint = kTextEncodingUnknown;
theErr = PBMakeFSRefUnicodeSync (&fsRefPB);
165
if(theErr != noErr) {
166
error = "PBMakeFSRefUnicodeSync";
167
168
169
goto bail;
}
170
/* Load and parse the TOC XML data */
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
theErr = FSGetDataForkName (&dataForkName);
if (theErr != noErr) {
error = "FSGetDataForkName";
goto bail;
}
theErr = FSOpenFork (&tocPlistFSRef, dataForkName.length, dataForkName.unicode, fsRdPerm, &forkRefNum);
if (theErr != noErr) {
error = "FSOpenFork";
goto bail;
}
theErr = FSGetForkSize (forkRefNum, &forkSize);
if (theErr != noErr) {
error = "FSGetForkSize";
goto bail;
}
190
/* Allocate some memory for the XML data */
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
forkData = NewPtr (forkSize);
if(forkData == NULL) {
error = "NewPtr";
goto bail;
}
theErr = FSReadFork (forkRefNum, fsFromStart, 0 /* offset location */, forkSize, forkData, &actualRead);
if(theErr != noErr) {
error = "FSReadFork";
goto bail;
}
dataRef = CFDataCreate (kCFAllocatorDefault, (UInt8 *)forkData, forkSize);
if(dataRef == 0) {
error = "CFDataCreate";
goto bail;
}
propertyListRef = CFPropertyListCreateFromXMLData (kCFAllocatorDefault,
dataRef,
kCFPropertyListImmutable,
NULL);
if (propertyListRef == NULL) {
error = "CFPropertyListCreateFromXMLData";
goto bail;
}
218
/* Now we got the Property List in memory. Parse it. */
219
220
/* First, make sure the root item is a CFDictionary. If not, release and bail. */
221
222
223
224
225
226
227
228
229
if(CFGetTypeID(propertyListRef)== CFDictionaryGetTypeID())
{
CFDictionaryRef dictRef = (CFDictionaryRef)propertyListRef;
CFDataRef theRawTOCDataRef;
CFArrayRef theSessionArrayRef;
CFIndex numSessions;
CFIndex index;
230
/* This is how we get the Raw TOC Data */
231
232
theRawTOCDataRef = (CFDataRef)CFDictionaryGetValue (dictRef, CFSTR(kRawTOCDataString));
233
/* Get the session array info. */
234
235
theSessionArrayRef = (CFArrayRef)CFDictionaryGetValue (dictRef, CFSTR(kSessionsString));
236
/* Find out how many sessions there are. */
237
238
numSessions = CFArrayGetCount (theSessionArrayRef);
239
/* Initialize the total number of tracks to 0 */
240
241
theCD->numtracks = 0;
242
/* Iterate over all sessions, collecting the track data */
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
for(index = 0; index < numSessions; index++)
{
CFDictionaryRef theSessionDict;
CFNumberRef leadoutBlock;
CFArrayRef trackArray;
CFIndex numTracks;
CFIndex trackIndex;
UInt32 value = 0;
theSessionDict = (CFDictionaryRef) CFArrayGetValueAtIndex (theSessionArrayRef, index);
leadoutBlock = (CFNumberRef) CFDictionaryGetValue (theSessionDict, CFSTR(kLeadoutBlockString));
trackArray = (CFArrayRef)CFDictionaryGetValue (theSessionDict, CFSTR(kTrackArrayString));
numTracks = CFArrayGetCount (trackArray);
for(trackIndex = 0; trackIndex < numTracks; trackIndex++) {
CFDictionaryRef theTrackDict;
CFNumberRef trackNumber;
CFNumberRef sessionNumber;
CFNumberRef startBlock;
CFBooleanRef isDataTrack;
UInt32 value;
theTrackDict = (CFDictionaryRef) CFArrayGetValueAtIndex (trackArray, trackIndex);
trackNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kPointKeyString));
sessionNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kSessionNumberKeyString));
startBlock = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kStartBlockKeyString));
isDataTrack = (CFBooleanRef) CFDictionaryGetValue (theTrackDict, CFSTR(kDataKeyString));
275
/* Fill in the SDL_CD struct */
276
277
278
279
280
281
282
283
284
285
int idx = theCD->numtracks++;
CFNumberGetValue (trackNumber, kCFNumberSInt32Type, &value);
theCD->track[idx].id = value;
CFNumberGetValue (startBlock, kCFNumberSInt32Type, &value);
theCD->track[idx].offset = value;
theCD->track[idx].type = (isDataTrack == kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK;
286
/* Since the track lengths are not stored in .TOC.plist we compute them. */
287
288
289
290
291
if (trackIndex > 0) {
theCD->track[idx-1].length = theCD->track[idx].offset - theCD->track[idx-1].offset;
}
}
292
/* Compute the length of the last track */
293
294
295
296
297
CFNumberGetValue (leadoutBlock, kCFNumberSInt32Type, &value);
theCD->track[theCD->numtracks-1].length =
value - theCD->track[theCD->numtracks-1].offset;
298
/* Set offset to leadout track */
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
theCD->track[theCD->numtracks].offset = value;
}
}
theErr = 0;
goto cleanup;
bail:
SDL_SetError ("ReadTOCData: %s returned %d", error, theErr);
theErr = -1;
cleanup:
if (propertyListRef != NULL)
CFRelease(propertyListRef);
if (dataRef != NULL)
CFRelease(dataRef);
if (forkData != NULL)
DisposePtr(forkData);
FSCloseFork (forkRefNum);
return theErr;
}
int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks)
{
OSStatus result = -1;
FSIterator iterator;
ItemCount actualObjects;
FSRef rootDirectory;
FSRef ref;
HFSUniStr255 nameStr;
result = FSGetVolumeInfo (theVolume,
0,
NULL,
kFSVolInfoFSInfo,
NULL,
NULL,
&rootDirectory);
if (result != noErr) {
SDL_SetError ("ListTrackFiles: FSGetVolumeInfo returned %d", result);
342
return result;
343
344
345
346
347
348
349
350
351
352
353
354
355
}
result = FSOpenIterator (&rootDirectory, kFSIterateFlat, &iterator);
if (result == noErr) {
do
{
result = FSGetCatalogInfoBulk (iterator, 1, &actualObjects,
NULL, kFSCatInfoNone, NULL, &ref, NULL, &nameStr);
if (result == noErr) {
CFStringRef name;
name = CFStringCreateWithCharacters (NULL, nameStr.unicode, nameStr.length);
356
/* Look for .aiff extension */
357
358
if (CFStringHasSuffix (name, CFSTR(".aiff")) ||
CFStringHasSuffix (name, CFSTR(".cdda"))) {
359
360
/* Extract the track id from the filename */
361
int trackID = 0, i = 0;
362
363
364
365
while (i < nameStr.length && !isdigit(nameStr.unicode[i])) {
++i;
}
while (i < nameStr.length && isdigit(nameStr.unicode[i])) {
366
trackID = 10 * trackID +(nameStr.unicode[i] - '0');
367
++i;
368
}
369
370
371
372
373
374
#if DEBUG_CDROM
printf("Found AIFF for track %d: '%s'\n", trackID,
CFStringGetCStringPtr (name, CFStringGetSystemEncoding()));
#endif
375
/* Track ID's start at 1, but we want to start at 0 */
376
377
378
379
380
381
382
383
384
385
386
387
388
trackID--;
assert(0 <= trackID && trackID <= SDL_MAX_TRACKS);
if (trackID < numTracks)
memcpy (&trackFiles[trackID], &ref, sizeof(FSRef));
}
CFRelease (name);
}
} while(noErr == result);
FSCloseIterator (iterator);
}
389
return 0;
390
391
392
393
394
395
396
397
398
}
int LoadFile (const FSRef *ref, int startFrame, int stopFrame)
{
int error = -1;
if (CheckInit () < 0)
goto bail;
399
/* release any currently playing file */
400
401
402
403
404
405
406
if (ReleaseFile () < 0)
goto bail;
#if DEBUG_CDROM
printf ("LoadFile: %d %d\n", startFrame, stopFrame);
#endif
407
/*try {*/
408
409
/* create a new player, and attach to the audio unit */
410
411
thePlayer = new_AudioFilePlayer(ref);
412
413
if (thePlayer == NULL) {
SDL_SetError ("LoadFile: Could not create player");
414
return -3; /*throw (-3);*/
415
416
}
417
418
if (!thePlayer->SetDestination(thePlayer, &theUnit))
goto bail;
419
420
if (startFrame >= 0)
421
thePlayer->SetStartFrame (thePlayer, startFrame);
422
423
if (stopFrame >= 0 && stopFrame > startFrame)
424
thePlayer->SetStopFrame (thePlayer, stopFrame);
425
426
427
/* we set the notifier later */
/*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL);*/
428
429
430
if (!thePlayer->Connect(thePlayer))
goto bail;
431
432
#if DEBUG_CDROM
433
thePlayer->Print(thePlayer);
434
435
fflush (stdout);
#endif
436
437
438
439
440
/*}
catch (...)
{
goto bail;
}*/
441
442
443
444
445
446
447
448
449
450
451
error = 0;
bail:
return error;
}
int ReleaseFile ()
{
int error = -1;
452
453
/* (Don't see any way that the original C++ code could throw here.) --ryan. */
/*try {*/
454
455
if (thePlayer != NULL) {
456
thePlayer->Disconnect(thePlayer);
457
458
delete_AudioFilePlayer(thePlayer);
459
460
461
thePlayer = NULL;
}
462
463
464
465
466
/*}
catch (...)
{
goto bail;
}*/
467
468
469
error = 0;
470
/* bail: */
471
472
473
474
475
476
477
478
479
480
return error;
}
int PlayFile ()
{
OSStatus result = -1;
if (CheckInit () < 0)
goto bail;
481
/*try {*/
482
483
484
// start processing of the audio unit
result = AudioOutputUnitStart (theUnit);
485
if (result) goto bail; //THROW_RESULT("PlayFile: AudioOutputUnitStart")
486
487
488
489
490
491
/*}
catch (...)
{
goto bail;
}*/
492
493
494
495
496
497
498
499
500
501
502
503
504
505
result = 0;
bail:
return result;
}
int PauseFile ()
{
OSStatus result = -1;
if (CheckInit () < 0)
goto bail;
506
/*try {*/
507
508
/* stop processing the audio unit */
509
result = AudioOutputUnitStop (theUnit);
510
511
512
513
514
515
if (result) goto bail; /*THROW_RESULT("PauseFile: AudioOutputUnitStop")*/
/*}
catch (...)
{
goto bail;
}*/
516
517
518
519
520
521
522
523
524
525
526
527
result = 0;
bail:
return result;
}
void SetCompletionProc (CDPlayerCompletionProc proc, SDL_CD *cdrom)
{
assert(thePlayer != NULL);
theCDROM = cdrom;
completionProc = proc;
528
thePlayer->SetNotifier (thePlayer, FilePlayNotificationHandler, cdrom);
529
530
531
532
533
534
535
536
537
}
int GetCurrentFrame ()
{
int frame;
if (thePlayer == NULL)
frame = 0;
else
538
frame = thePlayer->GetCurrentFrame (thePlayer);
539
540
541
542
543
544
545
return frame;
}
#pragma mark -- Private Functions --
546
static OSStatus CheckInit ()
547
548
549
550
551
552
{
if (playBackWasInit)
return 0;
OSStatus result = noErr;
553
/* Create the callback semaphore */
554
555
callbackSem = SDL_CreateSemaphore(0);
556
/* Start callback thread */
557
SDL_CreateThread(RunCallBackThread, NULL);
558
559
{ /*try {*/
560
561
ComponentDescription desc;
562
563
564
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
565
566
567
568
569
570
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
Component comp = FindNextComponent (NULL, &desc);
if (comp == NULL) {
SDL_SetError ("CheckInit: FindNextComponent returned NULL");
571
if (result) return -1; //throw(internalComponentErr);
572
573
574
}
result = OpenAComponent (comp, &theUnit);
575
if (result) return -1; //THROW_RESULT("CheckInit: OpenAComponent")
576
577
578
// you need to initialize the output unit before you set it as a destination
result = AudioUnitInitialize (theUnit);
579
if (result) return -1; //THROW_RESULT("CheckInit: AudioUnitInitialize")
580
581
582
583
playBackWasInit = true;
}
584
585
586
587
/*catch (...)
{
return -1;
}*/
588
589
590
591
return 0;
}
592
static void FilePlayNotificationHandler(void * inRefCon, OSStatus inStatus)
593
594
595
{
if (inStatus == kAudioFilePlay_FileIsFinished) {
596
/* notify non-CA thread to perform the callback */
597
SDL_SemPost(callbackSem);
598
599
600
601
602
603
604
605
606
607
608
609
610
} else if (inStatus == kAudioFilePlayErr_FilePlayUnderrun) {
SDL_SetError ("CDPlayer Notification: buffer underrun");
} else if (inStatus == kAudioFilePlay_PlayerIsUninitialized) {
SDL_SetError ("CDPlayer Notification: player is uninitialized");
} else {
SDL_SetError ("CDPlayer Notification: unknown error %ld", inStatus);
}
}
611
static int RunCallBackThread (void *param)
612
{
613
for (;;) {
614
615
SDL_SemWait(callbackSem);
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
if (completionProc && theCDROM) {
#if DEBUG_CDROM
printf ("callback!\n");
#endif
(*completionProc)(theCDROM);
} else {
#if DEBUG_CDROM
printf ("callback?\n");
#endif
}
}
#if DEBUG_CDROM
printf ("thread dying now...\n");
#endif
633
return 0;
634
635
}
636
/*}; // extern "C" */