This repository has been archived by the owner on Feb 11, 2021. It is now read-only.
/
CDPlayer.c
670 lines (524 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 Sam Lantinga
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
#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"
48
49
#define kStartBlockKeyString "Start Block"
50
51
52
/*///////////////////////////////////////////////////////////////////////////
Globals
//////////////////////////////////////////////////////////////////////////*/
53
54
55
#pragma mark -- Globals --
56
57
58
59
60
61
62
static int playBackWasInit = 0;
static AudioUnit theUnit;
static AudioFilePlayer *thePlayer = NULL;
static CDPlayerCompletionProc completionProc = NULL;
static SDL_mutex *apiMutex = NULL;
static SDL_sem *callbackSem;
static SDL_CD *theCDROM;
63
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
#pragma mark -- Public Functions --
79
void
80
Lock()
81
{
82
if (!apiMutex) {
83
apiMutex = SDL_CreateMutex();
84
}
85
SDL_mutexP(apiMutex);
86
87
}
88
void
89
Unlock()
90
{
91
SDL_mutexV(apiMutex);
92
93
}
94
int
95
DetectAudioCDVolumes(FSVolumeRefNum * volumes, int numVolumes)
96
97
98
99
{
int volumeIndex;
int cdVolumeCount = 0;
OSStatus result = noErr;
100
101
102
103
104
for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++) {
FSVolumeRefNum actualVolume;
FSVolumeInfo volumeInfo;
105
memset(&volumeInfo, 0, sizeof(volumeInfo));
106
107
108
109
110
result = FSGetVolumeInfo(kFSInvalidVolumeRefNum,
volumeIndex,
&actualVolume,
kFSVolInfoFSInfo, &volumeInfo, NULL, NULL);
111
112
113
if (result == noErr) {
if (volumeInfo.filesystemID == kAudioCDFilesystemID) { /* It's an audio CD */
114
115
if (volumes != NULL && cdVolumeCount < numVolumes)
volumes[cdVolumeCount] = actualVolume;
116
117
118
cdVolumeCount++;
}
119
} else {
120
/* I'm commenting this out because it seems to be harmless */
121
/*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result); */
122
123
}
}
124
125
126
127
return cdVolumeCount;
}
128
int
129
ReadTOCData(FSVolumeRefNum theVolume, SDL_CD * theCD)
130
{
131
132
133
134
135
136
137
HFSUniStr255 dataForkName;
OSStatus theErr;
SInt16 forkRefNum;
SInt64 forkSize;
Ptr forkData = 0;
ByteCount actualRead;
CFDataRef dataRef = 0;
138
139
CFPropertyListRef propertyListRef = 0;
140
141
142
143
144
FSRefParam fsRefPB;
FSRef tocPlistFSRef;
const char *error = "Unspecified Error";
145
/* get stuff from .TOC.plist */
146
147
148
149
150
fsRefPB.ioCompletion = NULL;
fsRefPB.ioNamePtr = "\p.TOC.plist";
fsRefPB.ioVRefNum = theVolume;
fsRefPB.ioDirID = 0;
fsRefPB.newRef = &tocPlistFSRef;
151
152
theErr = PBMakeFSRefSync(&fsRefPB);
153
if (theErr != noErr) {
154
155
156
error = "PBMakeFSRefSync";
goto bail;
}
157
158
/* Load and parse the TOC XML data */
159
160
theErr = FSGetDataForkName(&dataForkName);
161
162
163
164
if (theErr != noErr) {
error = "FSGetDataForkName";
goto bail;
}
165
166
theErr =
167
168
FSOpenFork(&tocPlistFSRef, dataForkName.length, dataForkName.unicode,
fsRdPerm, &forkRefNum);
169
170
171
172
if (theErr != noErr) {
error = "FSOpenFork";
goto bail;
}
173
174
theErr = FSGetForkSize(forkRefNum, &forkSize);
175
176
177
178
if (theErr != noErr) {
error = "FSGetForkSize";
goto bail;
}
179
180
/* Allocate some memory for the XML data */
181
forkData = NewPtr(forkSize);
182
if (forkData == NULL) {
183
184
185
error = "NewPtr";
goto bail;
}
186
187
188
theErr = FSReadFork(forkRefNum, fsFromStart, 0 /* offset location */ ,
forkSize, forkData, &actualRead);
189
if (theErr != noErr) {
190
191
192
error = "FSReadFork";
goto bail;
}
193
194
dataRef = CFDataCreate(kCFAllocatorDefault, (UInt8 *) forkData, forkSize);
195
if (dataRef == 0) {
196
197
198
199
error = "CFDataCreate";
goto bail;
}
200
201
202
203
propertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault,
dataRef,
kCFPropertyListImmutable,
NULL);
204
205
206
207
208
if (propertyListRef == NULL) {
error = "CFPropertyListCreateFromXMLData";
goto bail;
}
209
/* Now we got the Property List in memory. Parse it. */
210
211
/* First, make sure the root item is a CFDictionary. If not, release and bail. */
212
if (CFGetTypeID(propertyListRef) == CFDictionaryGetTypeID()) {
213
214
215
216
217
218
219
CFDictionaryRef dictRef = (CFDictionaryRef) propertyListRef;
CFDataRef theRawTOCDataRef;
CFArrayRef theSessionArrayRef;
CFIndex numSessions;
CFIndex index;
220
/* This is how we get the Raw TOC Data */
221
theRawTOCDataRef =
222
223
(CFDataRef) CFDictionaryGetValue(dictRef,
CFSTR(kRawTOCDataString));
224
225
/* Get the session array info. */
226
theSessionArrayRef =
227
228
(CFArrayRef) CFDictionaryGetValue(dictRef,
CFSTR(kSessionsString));
229
230
/* Find out how many sessions there are. */
231
numSessions = CFArrayGetCount(theSessionArrayRef);
232
233
/* Initialize the total number of tracks to 0 */
234
theCD->numtracks = 0;
235
236
/* Iterate over all sessions, collecting the track data */
237
for (index = 0; index < numSessions; index++) {
238
CFDictionaryRef theSessionDict;
239
240
241
242
243
244
245
CFNumberRef leadoutBlock;
CFArrayRef trackArray;
CFIndex numTracks;
CFIndex trackIndex;
UInt32 value = 0;
theSessionDict = (CFDictionaryRef)
246
CFArrayGetValueAtIndex(theSessionArrayRef, index);
247
leadoutBlock =
248
249
250
(CFNumberRef) CFDictionaryGetValue(theSessionDict,
CFSTR
(kLeadoutBlockString));
251
252
trackArray =
253
254
(CFArrayRef) CFDictionaryGetValue(theSessionDict,
CFSTR(kTrackArrayString));
255
256
numTracks = CFArrayGetCount(trackArray);
257
258
259
for (trackIndex = 0; trackIndex < numTracks; trackIndex++) {
260
CFDictionaryRef theTrackDict;
261
262
263
264
265
266
267
CFNumberRef trackNumber;
CFNumberRef sessionNumber;
CFNumberRef startBlock;
CFBooleanRef isDataTrack;
UInt32 value;
theTrackDict = (CFDictionaryRef)
268
CFArrayGetValueAtIndex(trackArray, trackIndex);
269
270
trackNumber =
271
272
273
(CFNumberRef) CFDictionaryGetValue(theTrackDict,
CFSTR
(kPointKeyString));
274
sessionNumber =
275
276
277
(CFNumberRef) CFDictionaryGetValue(theTrackDict,
CFSTR
(kSessionNumberKeyString));
278
startBlock =
279
280
281
(CFNumberRef) CFDictionaryGetValue(theTrackDict,
CFSTR
(kStartBlockKeyString));
282
isDataTrack =
283
284
285
(CFBooleanRef) CFDictionaryGetValue(theTrackDict,
CFSTR
(kDataKeyString));
286
287
/* Fill in the SDL_CD struct */
288
289
int idx = theCD->numtracks++;
290
CFNumberGetValue(trackNumber, kCFNumberSInt32Type, &value);
291
theCD->track[idx].id = value;
292
293
CFNumberGetValue(startBlock, kCFNumberSInt32Type, &value);
294
295
theCD->track[idx].offset = value;
296
297
298
theCD->track[idx].type =
(isDataTrack ==
kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK;
299
300
/* Since the track lengths are not stored in .TOC.plist we compute them. */
301
if (trackIndex > 0) {
302
303
304
theCD->track[idx - 1].length =
theCD->track[idx].offset - theCD->track[idx -
1].offset;
305
306
}
}
307
308
/* Compute the length of the last track */
309
CFNumberGetValue(leadoutBlock, kCFNumberSInt32Type, &value);
310
311
312
theCD->track[theCD->numtracks - 1].length =
value - theCD->track[theCD->numtracks - 1].offset;
313
314
/* Set offset to leadout track */
315
316
theCD->track[theCD->numtracks].offset = value;
}
317
318
319
320
321
}
theErr = 0;
goto cleanup;
322
bail:
323
SDL_SetError("ReadTOCData: %s returned %d", error, theErr);
324
theErr = -1;
325
cleanup:
326
327
if (propertyListRef != NULL)
328
CFRelease(propertyListRef);
329
if (dataRef != NULL)
330
CFRelease(dataRef);
331
if (forkData != NULL)
332
DisposePtr(forkData);
333
334
FSCloseFork(forkRefNum);
335
336
337
338
return theErr;
}
339
int
340
ListTrackFiles(FSVolumeRefNum theVolume, FSRef * trackFiles, int numTracks)
341
{
342
343
344
345
346
347
348
OSStatus result = -1;
FSIterator iterator;
ItemCount actualObjects;
FSRef rootDirectory;
FSRef ref;
HFSUniStr255 nameStr;
349
350
351
352
result = FSGetVolumeInfo(theVolume,
0,
NULL,
kFSVolInfoFSInfo, NULL, NULL, &rootDirectory);
353
354
if (result != noErr) {
355
SDL_SetError("ListTrackFiles: FSGetVolumeInfo returned %d", result);
356
return result;
357
358
}
359
result = FSOpenIterator(&rootDirectory, kFSIterateFlat, &iterator);
360
if (result == noErr) {
361
do {
362
363
364
result = FSGetCatalogInfoBulk(iterator, 1, &actualObjects,
NULL, kFSCatInfoNone, NULL,
&ref, NULL, &nameStr);
365
if (result == noErr) {
366
367
368
CFStringRef name;
name =
369
370
CFStringCreateWithCharacters(NULL, nameStr.unicode,
nameStr.length);
371
372
/* Look for .aiff extension */
373
374
if (CFStringHasSuffix(name, CFSTR(".aiff")) ||
CFStringHasSuffix(name, CFSTR(".cdda"))) {
375
376
/* Extract the track id from the filename */
377
int trackID = 0, i = 0;
378
while (i < nameStr.length && !isdigit(nameStr.unicode[i])) {
379
380
++i;
}
381
while (i < nameStr.length && isdigit(nameStr.unicode[i])) {
382
trackID = 10 * trackID + (nameStr.unicode[i] - '0');
383
++i;
384
}
385
386
#if DEBUG_CDROM
387
388
389
390
printf("Found AIFF for track %d: '%s'\n",
trackID, CFStringGetCStringPtr(name,
CFStringGetSystemEncoding
()));
391
392
#endif
393
/* Track ID's start at 1, but we want to start at 0 */
394
trackID--;
395
396
assert(0 <= trackID && trackID <= SDL_MAX_TRACKS);
397
398
if (trackID < numTracks)
399
memcpy(&trackFiles[trackID], &ref, sizeof(FSRef));
400
}
401
CFRelease(name);
402
}
403
404
}
while (noErr == result);
405
FSCloseIterator(iterator);
406
}
407
408
return 0;
409
410
}
411
int
412
LoadFile(const FSRef * ref, int startFrame, int stopFrame)
413
414
{
int error = -1;
415
416
if (CheckInit() < 0)
417
goto bail;
418
419
/* release any currently playing file */
420
if (ReleaseFile() < 0)
421
goto bail;
422
423
#if DEBUG_CDROM
424
printf("LoadFile: %d %d\n", startFrame, stopFrame);
425
426
427
428
429
430
#endif
/*try { */
/* create a new player, and attach to the audio unit */
431
thePlayer = new_AudioFilePlayer(ref);
432
if (thePlayer == NULL) {
433
SDL_SetError("LoadFile: Could not create player");
434
435
436
return -3; /*throw (-3); */
}
437
if (!thePlayer->SetDestination(thePlayer, &theUnit))
438
439
440
goto bail;
if (startFrame >= 0)
441
thePlayer->SetStartFrame(thePlayer, startFrame);
442
443
if (stopFrame >= 0 && stopFrame > startFrame)
444
thePlayer->SetStopFrame(thePlayer, stopFrame);
445
446
447
448
/* we set the notifier later */
/*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL); */
449
if (!thePlayer->Connect(thePlayer))
450
451
452
goto bail;
#if DEBUG_CDROM
453
454
thePlayer->Print(thePlayer);
fflush(stdout);
455
#endif
456
/*}
457
458
459
460
461
catch (...)
{
goto bail;
} */
462
463
error = 0;
464
bail:
465
466
467
return error;
}
468
int
469
ReleaseFile()
470
471
{
int error = -1;
472
473
/* (Don't see any way that the original C++ code could throw here.) --ryan. */
474
475
476
/*try { */
if (thePlayer != NULL) {
477
thePlayer->Disconnect(thePlayer);
478
479
delete_AudioFilePlayer(thePlayer);
480
481
482
thePlayer = NULL;
}
483
/*}
484
485
486
487
488
catch (...)
{
goto bail;
} */
489
error = 0;
490
491
/* bail: */
492
493
494
return error;
}
495
int
496
PlayFile()
497
498
{
OSStatus result = -1;
499
500
if (CheckInit() < 0)
501
goto bail;
502
503
504
505
/*try { */
// start processing of the audio unit
506
result = AudioOutputUnitStart(theUnit);
507
508
509
if (result)
goto bail; //THROW_RESULT("PlayFile: AudioOutputUnitStart")
510
/*}
511
512
513
514
515
catch (...)
{
goto bail;
} */
516
result = 0;
517
518
bail:
519
520
521
return result;
}
522
int
523
PauseFile()
524
525
{
OSStatus result = -1;
526
527
if (CheckInit() < 0)
528
goto bail;
529
530
531
532
/*try { */
/* stop processing the audio unit */
533
result = AudioOutputUnitStop(theUnit);
534
535
if (result)
goto bail; /*THROW_RESULT("PauseFile: AudioOutputUnitStop") */
536
/*}
537
538
539
540
541
catch (...)
{
goto bail;
} */
542
result = 0;
543
bail:
544
545
546
return result;
}
547
void
548
SetCompletionProc(CDPlayerCompletionProc proc, SDL_CD * cdrom)
549
{
550
assert(thePlayer != NULL);
551
552
553
theCDROM = cdrom;
completionProc = proc;
554
thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, cdrom);
555
556
}
557
int
558
GetCurrentFrame()
559
{
560
int frame;
561
562
563
564
if (thePlayer == NULL)
frame = 0;
else
565
frame = thePlayer->GetCurrentFrame(thePlayer);
566
567
return frame;
568
569
570
571
572
}
#pragma mark -- Private Functions --
573
static OSStatus
574
CheckInit()
575
{
576
577
if (playBackWasInit)
return 0;
578
579
OSStatus result = noErr;
580
581
/* Create the callback semaphore */
582
callbackSem = SDL_CreateSemaphore(0);
583
584
/* Start callback thread */
585
SDL_CreateThread(RunCallBackThread, NULL);
586
587
{ /*try { */
588
ComponentDescription desc;
589
590
591
592
593
594
desc.componentType = kAudioUnitComponentType;
desc.componentSubType = kAudioUnitSubType_Output;
desc.componentManufacturer = kAudioUnitID_DefaultOutput;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
595
596
Component comp = FindNextComponent(NULL, &desc);
597
if (comp == NULL) {
598
SDL_SetError("CheckInit: FindNextComponent returned NULL");
599
600
if (result)
return -1; //throw(internalComponentErr);
601
}
602
603
result = OpenAComponent(comp, &theUnit);
604
605
606
if (result)
return -1; //THROW_RESULT("CheckInit: OpenAComponent")
607
// you need to initialize the output unit before you set it as a destination
608
result = AudioUnitInitialize(theUnit);
609
610
611
612
if (result)
return -1; //THROW_RESULT("CheckInit: AudioUnitInitialize")
613
614
playBackWasInit = true;
}
615
/*catch (...)
616
617
618
619
{
return -1;
} */
620
621
622
return 0;
}
623
static void
624
FilePlayNotificationHandler(void *inRefCon, OSStatus inStatus)
625
626
{
if (inStatus == kAudioFilePlay_FileIsFinished) {
627
628
/* notify non-CA thread to perform the callback */
629
SDL_SemPost(callbackSem);
630
631
} else if (inStatus == kAudioFilePlayErr_FilePlayUnderrun) {
632
633
SDL_SetError("CDPlayer Notification: buffer underrun");
634
} else if (inStatus == kAudioFilePlay_PlayerIsUninitialized) {
635
636
SDL_SetError("CDPlayer Notification: player is uninitialized");
637
} else {
638
639
SDL_SetError("CDPlayer Notification: unknown error %ld", inStatus);
640
641
642
}
}
643
static int
644
RunCallBackThread(void *param)
645
{
646
for (;;) {
647
648
SDL_SemWait(callbackSem);
649
650
if (completionProc && theCDROM) {
651
#if DEBUG_CDROM
652
printf("callback!\n");
653
654
#endif
(*completionProc) (theCDROM);
655
} else {
656
#if DEBUG_CDROM
657
printf("callback?\n");
658
#endif
659
660
}
}
661
662
#if DEBUG_CDROM
663
printf("thread dying now...\n");
664
665
#endif
666
return 0;
667
668
}
669
/*}; // extern "C" */
670
/* vi: set ts=4 sw=4 expandtab: */