libgig 4.6.1
Akai.cpp
1/*
2 libakai - C++ cross-platform akai sample disk reader
3 Copyright (C) 2002-2003 Sébastien Métrot
4 Copyright (C) 2003-2026 Christian Schoenebeck <cuse@users.sourceforge.net>
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19*/
20// Akai.cpp
21
22#include "Akai.h"
23
24#include <stdio.h>
25#include <string.h>
26#ifndef _MSC_VER
27# include <unistd.h>
28# include <fcntl.h>
29#endif
30#if defined(_CARBON_) || defined(__APPLE__)
31# if defined (__GNUC__) && (__GNUC__ >= 4)
32# include <sys/disk.h>
33# else
34# include <dev/disk.h>
35# endif
36#endif
37#include <sys/types.h>
38#include <sys/stat.h>
39#include <errno.h>
40#if defined(_CARBON_) || defined(__APPLE__)
41#include <paths.h>
42#include <sys/ioctl.h>
43#include <sys/param.h>
44#include <IOKit/IOKitLib.h>
45#include <IOKit/IOBSD.h>
46#include <IOKit/storage/IOMediaBSDClient.h>
47#include <IOKit/storage/IOMedia.h>
48#include <IOKit/storage/IOCDMedia.h>
49#include <IOKit/storage/IOCDTypes.h>
50#include <CoreFoundation/CoreFoundation.h>
51#endif
52
53#if defined(_CARBON_) || defined(__APPLE__)
54
55// These definitions were taken from mount_cd9660.c
56// There are some similar definitions in IOCDTypes.h
57// however there seems to be some dissagreement in
58// the definition of CDTOC.length
59struct _CDMSF {
60 u_char minute;
61 u_char second;
62 u_char frame;
63};
64
65#define MSF_TO_LBA(msf) \
66 (((((msf).minute * 60UL) + (msf).second) * 75UL) + (msf).frame - 150)
67
68struct _CDTOC_Desc {
69 u_char session;
70 u_char ctrl_adr; /* typed to be machine and compiler independent */
71 u_char tno;
72 u_char point;
73 struct _CDMSF address;
74 u_char zero;
75 struct _CDMSF p;
76};
77
78struct _CDTOC {
79 u_short length; /* in native cpu endian */
80 u_char first_session;
81 u_char last_session;
82 struct _CDTOC_Desc trackdesc[1];
83};
84
85// Most of the following Mac CDROM IO functions were taken from Apple's IOKit
86// examples (BSD style license). ReadTOC() function was taken from the Bochs x86
87// Emulator (LGPL). Most probably they have taken it however also from some
88// other BSD style licensed example code as well ...
89
90// Returns an iterator across all CD media (class IOCDMedia). Caller is responsible for releasing
91// the iterator when iteration is complete.
92static kern_return_t FindEjectableCDMedia(io_iterator_t *mediaIterator) {
93 kern_return_t kernResult;
94 CFMutableDictionaryRef classesToMatch;
95
96 // CD media are instances of class kIOCDMediaClass
97 classesToMatch = IOServiceMatching(kIOCDMediaClass);
98 if (classesToMatch == NULL) {
99 printf("IOServiceMatching returned a NULL dictionary.\n");
100 } else {
101 CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey), kCFBooleanTrue);
102 // Each IOMedia object has a property with key kIOMediaEjectableKey which is true if the
103 // media is indeed ejectable. So add this property to the CFDictionary we're matching on.
104 }
105
106 kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, mediaIterator);
107
108 return kernResult;
109}
110
111// Given an iterator across a set of CD media, return the BSD path to the
112// next one. If no CD media was found the path name is set to an empty string.
113static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize) {
114 io_object_t nextMedia;
115 kern_return_t kernResult = KERN_FAILURE;
116
117 *bsdPath = '\0';
118
119 nextMedia = IOIteratorNext(mediaIterator);
120 if (nextMedia) {
121 CFTypeRef bsdPathAsCFString;
122
123 bsdPathAsCFString = IORegistryEntryCreateCFProperty(nextMedia,
124 CFSTR(kIOBSDNameKey),
125 kCFAllocatorDefault,
126 0);
127 if (bsdPathAsCFString) {
128 strlcpy(bsdPath, _PATH_DEV, maxPathSize);
129
130 // Add "r" before the BSD node name from the I/O Registry to specify the raw disk
131 // node. The raw disk nodes receive I/O requests directly and do not go through
132 // the buffer cache.
133
134 strlcat(bsdPath, "r", maxPathSize);
135
136 size_t devPathLength = strlen(bsdPath);
137
138 if (CFStringGetCString((CFStringRef)bsdPathAsCFString,
139 bsdPath + devPathLength,
140 maxPathSize - devPathLength,
141 kCFStringEncodingUTF8)) {
142 printf("BSD path: %s\n", bsdPath);
143 kernResult = KERN_SUCCESS;
144 }
145
146 CFRelease(bsdPathAsCFString);
147 }
148
149 IOObjectRelease(nextMedia);
150 }
151
152 return kernResult;
153}
154
155// Given the path to a CD drive, open the drive.
156// Return the file descriptor associated with the device.
157/*static int OpenDrive(const char *bsdPath) {
158 int fileDescriptor;
159
160 // This open() call will fail with a permissions error if the sample has been changed to
161 // look for non-removable media. This is because device nodes for fixed-media devices are
162 // owned by root instead of the current console user.
163
164 fileDescriptor = open(bsdPath, O_RDONLY);
165
166 if (fileDescriptor == -1) {
167 printf("Error opening device %s: ", bsdPath);
168 perror(NULL);
169 }
170
171 return fileDescriptor;
172}*/
173
174// Given the file descriptor for a whole-media CD device, read a sector from the drive.
175// Return true if successful, otherwise false.
176/*static Boolean ReadSector(int fileDescriptor) {
177 char *buffer;
178 ssize_t numBytes;
179 u_int32_t blockSize;
180
181 // This ioctl call retrieves the preferred block size for the media. It is functionally
182 // equivalent to getting the value of the whole media object's "Preferred Block Size"
183 // property from the IORegistry.
184 if (ioctl(fileDescriptor, DKIOCGETBLOCKSIZE, &blockSize)) {
185 perror("Error getting preferred block size");
186
187 // Set a reasonable default if we can't get the actual preferred block size. A real
188 // app would probably want to bail at this point.
189 blockSize = kCDSectorSizeCDDA;
190 }
191
192 printf("Media has block size of %d bytes.\n", blockSize);
193
194 // Allocate a buffer of the preferred block size. In a real application, performance
195 // can be improved by reading as many blocks at once as you can.
196 buffer = (char*) malloc(blockSize);
197
198 // Do the read. Note that we use read() here, not fread(), since this is a raw device
199 // node.
200 numBytes = read(fileDescriptor, buffer, blockSize);
201
202 // Free our buffer. Of course, a real app would do something useful with the data first.
203 free(buffer);
204
205 return numBytes == blockSize ? true : false;
206}*/
207
208// Given the file descriptor for a device, close that device.
209/*static void CloseDrive(int fileDescriptor) {
210 close(fileDescriptor);
211}*/
212
213// path is the BSD path to a raw device such as /dev/rdisk1
214static struct _CDTOC * ReadTOC(const char *devpath) {
215 struct _CDTOC * toc_p = NULL;
216 io_iterator_t iterator = 0;
217 io_registry_entry_t service = 0;
218 CFDictionaryRef properties = 0;
219 CFDataRef data = 0;
220 mach_port_t port = 0;
221 const char *devname;
222
223 if ((devname = strrchr(devpath, '/')) != NULL) {
224 ++devname;
225 } else {
226 devname = (char *) devpath;
227 }
228
229 if (IOMasterPort(bootstrap_port, &port) != KERN_SUCCESS) {
230 fprintf(stderr, "IOMasterPort failed\n");
231 goto Exit;
232 }
233
234 if (IOServiceGetMatchingServices(port, IOBSDNameMatching(port, 0, devname),
235 &iterator) != KERN_SUCCESS) {
236 fprintf(stderr, "IOServiceGetMatchingServices failed\n");
237 goto Exit;
238 }
239
240 service = IOIteratorNext(iterator);
241
242 IOObjectRelease(iterator);
243
244 iterator = 0;
245
246 while (service && !IOObjectConformsTo(service, "IOCDMedia")) {
247 if (IORegistryEntryGetParentIterator(service, kIOServicePlane,
248 &iterator) != KERN_SUCCESS)
249 {
250 fprintf(stderr, "IORegistryEntryGetParentIterator failed\n");
251 goto Exit;
252 }
253
254 IOObjectRelease(service);
255 service = IOIteratorNext(iterator);
256 IOObjectRelease(iterator);
257 }
258
259 if (!service) {
260 fprintf(stderr, "CD media not found\n");
261 goto Exit;
262 }
263
264 if (IORegistryEntryCreateCFProperties(service, (__CFDictionary **) &properties,
265 kCFAllocatorDefault,
266 kNilOptions) != KERN_SUCCESS)
267 {
268 fprintf(stderr, "IORegistryEntryGetParentIterator failed\n");
269 goto Exit;
270 }
271
272 data = (CFDataRef) CFDictionaryGetValue(properties, CFSTR(kIOCDMediaTOCKey));
273 if (data == NULL) {
274 fprintf(stderr, "CFDictionaryGetValue failed\n");
275 goto Exit;
276 } else {
277 CFRange range;
278 CFIndex buflen;
279
280 buflen = CFDataGetLength(data) + 1;
281 range = CFRangeMake(0, buflen);
282 toc_p = (struct _CDTOC *) malloc(buflen);
283 if (toc_p == NULL) {
284 fprintf(stderr, "Out of memory\n");
285 goto Exit;
286 } else {
287 CFDataGetBytes(data, range, (unsigned char *) toc_p);
288 }
289
290 /*
291 fprintf(stderr, "Table of contents\n length %d first %d last %d\n",
292 toc_p->length, toc_p->first_session, toc_p->last_session);
293 */
294
295 CFRelease(properties);
296 }
297
298 Exit:
299
300 if (service) {
301 IOObjectRelease(service);
302 }
303
304 return toc_p;
305}
306
307#endif // defined(_CARBON_) || defined(__APPLE__)
308
310// AkaiSample:
311AkaiSample::AkaiSample(DiskImage* pDisk, AkaiVolume* pParent, const AkaiDirEntry& DirEntry)
312 : AkaiDiskElement(pDisk->GetPos())
313{
314 mpParent = pParent;
315 mpDisk = pDisk;
316 mDirEntry = DirEntry;
317 mpSamples = NULL;
318 mHeaderOK = false;
319 mPos = 0;
320
321 //
322 LoadHeader();
323}
324
325AkaiSample::~AkaiSample()
326{
327 if (mpSamples)
328 free(mpSamples);
329}
330
331AkaiDirEntry AkaiSample::GetDirEntry()
332{
333 return mDirEntry;
334}
335
336bool AkaiSample::LoadSampleData()
337{
338 if (!LoadHeader())
339 return false;
340 if (mpSamples)
341 return true;
342
343 mpDisk->SetPos(mImageOffset);
344 mpSamples = (int16_t*) malloc(mNumberOfSamples * sizeof(int16_t));
345 if (!mpSamples)
346 return false;
347
348 mpDisk->ReadInt16((uint16_t*)mpSamples, mNumberOfSamples);
349 return true;
350}
351
352void AkaiSample::ReleaseSampleData()
353{
354 if (!mpSamples)
355 return;
356 free(mpSamples);
357 mpSamples = NULL;
358}
359
360int AkaiSample::SetPos(int Where, akai_stream_whence_t Whence)
361{
362 if (!mHeaderOK) return -1;
363 int w = Where;
364 switch (Whence)
365 {
366 case akai_stream_start:
367 mPos = w;
368 break;
369 /*case eStreamRewind:
370 w = -w;*/
371 case akai_stream_curpos:
372 mPos += w;
373 break;
374 case akai_stream_end:
375 mPos = mNumberOfSamples - w;
376 break;
377 }
378 if (mPos > mNumberOfSamples) mPos = mNumberOfSamples;
379 if (mPos < 0) mPos = 0;
380 return mPos;
381}
382
383int AkaiSample::Read(void* pBuffer, uint SampleCount)
384{
385 if (!mHeaderOK) return 0;
386
387 if (mPos + SampleCount > mNumberOfSamples) SampleCount = mNumberOfSamples - mPos;
388
389 mpDisk->SetPos(mImageOffset + mPos * 2); // FIXME: assumes 16 bit sample depth
390 mpDisk->ReadInt16((uint16_t*)pBuffer, SampleCount);
391 return SampleCount;
392}
393
394bool AkaiSample::LoadHeader()
395{
396 if (mHeaderOK)
397 return true;
398
399 mpDisk->SetPos(mpParent->GetParent()->GetOffset() + mDirEntry.mStart * AKAI_BLOCK_SIZE );
400
401 // Length Format Description
402 // --------------------------------------------------------------
403 // 1 3
404 if (mpDisk->ReadInt8() != AKAI_SAMPLE_ID)
405 return false;
406 // 1 Not important: 0 for 22050Hz, 1 for 44100Hz
407 mpDisk->ReadInt8();
408 // 1 unsigned MIDI root note (C3=60)
409 mMidiRootNote = mpDisk->ReadInt8();
410 // 12 AKAII Filename
411 char buffer[13];
412 mpDisk->Read(buffer, 12, 1);
413 AkaiToAscii(buffer, 12);
414 mName = buffer;
415
416 // 1 128
417 mpDisk->ReadInt8();
418 // 1 unsigned Number of active loops
419 mActiveLoops = mpDisk->ReadInt8();
420 // 1 unsigned char First active loop (0 for none)
421 mFirstActiveLoop = mpDisk->ReadInt8();
422 // 1 0
423 mpDisk->ReadInt8();
424 // 1 unsigned Loop mode: 0=in release 1=until release
425 // 2=none 3=play to end
426 mLoopMode = mpDisk->ReadInt8();
427 // 1 signed Cents tune -50...+50
428 mTuneCents = mpDisk->ReadInt8();
429 // 1 signed Semi tune -50...+50
430 mTuneSemitones = mpDisk->ReadInt8();
431 // 4 0,8,2,0
432 mpDisk->ReadInt8();
433 mpDisk->ReadInt8();
434 mpDisk->ReadInt8();
435 mpDisk->ReadInt8();
436 //
437 // 4 unsigned Number of sample words
438 mNumberOfSamples = mpDisk->ReadInt32();
439 // 4 unsigned Start marker
440 mStartMarker = mpDisk->ReadInt32();
441 // 4 unsigned End marker
442 mEndMarker = mpDisk->ReadInt32();
443 //
444 // 4 unsigned Loop 1 marker
445 // 2 unsigned Loop 1 fine length (65536ths)
446 // 4 unsigned Loop 1 coarse length (words)
447 // 2 unsigned Loop 1 time (msec. or 9999=infinite)
448 //
449 // 84 [as above] Loops 2 to 8
450 //
451 int i;
452 for (i=0; i<8; i++)
453 mLoops[i].Load(mpDisk);
454 // 4 0,0,255,255
455 mpDisk->ReadInt32();
456 // 2 unsigned Sampling frequency
457 mSamplingFrequency = mpDisk->ReadInt16();
458 // 1 signed char Loop tune offset -50...+50
459 mLoopTuneOffset = mpDisk->ReadInt8();
460
461 const int headerSize =
462 (mpParent->GetDirEntry().mType == AKAI_TYPE_DIR_S3000) ? 192 : 150;
463
464 mImageOffset = mpParent->GetParent()->GetOffset() + mDirEntry.mStart * AKAI_BLOCK_SIZE + headerSize;
465
466 //FIXME: no header validation yet implemented
467 return (mHeaderOK = true);
468}
469
470bool AkaiSampleLoop::Load(DiskImage* pDisk)
471{
472 // 4 unsigned Loop 1 marker
473 mMarker = pDisk->ReadInt32();
474 // 2 unsigned Loop 1 fine length (65536ths)
475 mFineLength = pDisk->ReadInt16();
476 // 4 unsigned Loop 1 coarse length (words)
477 mCoarseLength = pDisk->ReadInt32();
478 // 2 unsigned Loop 1 time (msec. or 9999=infinite)
479 mTime = pDisk->ReadInt16();
480 return true;
481}
482
484// AkaiProgram:
485AkaiProgram::AkaiProgram(DiskImage* pDisk, AkaiVolume* pParent, const AkaiDirEntry& DirEntry)
486 : AkaiDiskElement(pDisk->GetPos())
487{
488 mpParent = pParent;
489 mpDisk = pDisk;
490 mDirEntry = DirEntry;
491 mpKeygroups = NULL;
492 Load();
493}
494
495AkaiProgram::~AkaiProgram()
496{
497 if (mpKeygroups)
498 delete[] mpKeygroups;
499}
500
501AkaiDirEntry AkaiProgram::GetDirEntry()
502{
503 return mDirEntry;
504}
505
506bool AkaiProgram::Load()
507{
508 // Read each of the program parameters
509 uint temppos = mpDisk->GetPos();
510 mpDisk->SetPos(mpParent->GetParent()->GetOffset() + mDirEntry.mStart * AKAI_BLOCK_SIZE );
511 // byte description default range/comments
512 // ---------------------------------------------------------------------------
513 // 1 program ID 1
514 uint8_t ProgID = mpDisk->ReadInt8();
515 if (ProgID != AKAI_PROGRAM_ID)
516 {
517 mpDisk->SetPos(temppos);
518 return false;
519 }
520 // 2-3 first keygroup address 150,0
521 /*uint16_t KeygroupAddress =*/ mpDisk->ReadInt16();
522 // 4-15 program name 10,10,10... AKAII character set
523 char buffer[13];
524 mpDisk->Read(buffer, 12, 1);
525 AkaiToAscii(buffer, 12);
526 mName = buffer;
527 // 16 MIDI program number 0 0..127
528 mMidiProgramNumber = mpDisk->ReadInt8();
529 // 17 MIDI channel 0 0..15, 255=OMNI
530 mMidiChannel = mpDisk->ReadInt8();
531 // 18 polyphony 15 1..16
532 mPolyphony = mpDisk->ReadInt8();
533 // 19 priority 1 0=LOW 1=NORM 2=HIGH 3=HOLD
534 mPriority = mpDisk->ReadInt8();
535 // 20 low key 24 24..127
536 mLowKey = mpDisk->ReadInt8();
537 // 21 high key 127 24..127
538 mHighKey = mpDisk->ReadInt8();
539 // 22 octave shift 0 -2..2
540 mOctaveShift = mpDisk->ReadInt8();
541 // 23 aux output select 255 0..7, 255=OFF
542 mAuxOutputSelect = mpDisk->ReadInt8();
543 // 24 mix output level 99 0..99
544 mMixOutputSelect = mpDisk->ReadInt8();
545 // 25 mix output pan 0 -50..50
546 mMixPan = mpDisk->ReadInt8();
547 // 26 volume 80 0..99
548 mVolume = mpDisk->ReadInt8();
549 // 27 vel>volume 20 -50..50
550 mVelocityToVolume = mpDisk->ReadInt8();
551 // 28 key>volume 0 -50..50
552 mKeyToVolume = mpDisk->ReadInt8();
553 // 29 pres>volume 0 -50..50
554 mPressureToVolume = mpDisk->ReadInt8();
555 // 30 pan lfo rate 50 0..99
556 mPanLFORate = mpDisk->ReadInt8();
557 // 31 pan lfo depth 0 0..99
558 mPanLFODepth = mpDisk->ReadInt8();
559 // 32 pan lfo delay 0 0..99
560 mPanLFODelay = mpDisk->ReadInt8();
561 // 33 key>pan 0 -50..50
562 mKeyToPan = mpDisk->ReadInt8();
563 // 34 lfo rate 50 0..99
564 mLFORate = mpDisk->ReadInt8();
565 // 35 lfo depth 0 0..99
566 mLFODepth = mpDisk->ReadInt8();
567 // 36 lfo delay 0 0..99
568 mLFODelay = mpDisk->ReadInt8();
569 // 37 mod>lfo depth 30 0..99
570 mModulationToLFODepth = mpDisk->ReadInt8();
571 // 38 pres>lfo depth 0 0..99
572 mPressureToLFODepth = mpDisk->ReadInt8();
573 // 39 vel>lfo depth 0 0..99
574 mVelocityToLFODepth = mpDisk->ReadInt8();
575 // 40 bend>pitch 2 0..12 semitones
576 mBendToPitch = mpDisk->ReadInt8();
577 // 41 pres>pitch 0 -12..12 semitones
578 mPressureToPitch = mpDisk->ReadInt8();
579 // 42 keygroup crossfade 0 0=OFF 1=ON
580 mKeygroupCrossfade = mpDisk->ReadInt8()?true:false;
581 // 43 number of keygroups 1 1..99
582 mNumberOfKeygroups = mpDisk->ReadInt8();
583 // 44 (internal use) 0 program number
584 mpDisk->ReadInt8();
585 // 45-56 key temperament C,C#,D... 0 -25..25 cents
586 uint i;
587 for (i = 0; i<11; i++)
588 mKeyTemperament[i] = mpDisk->ReadInt8();
589 // 57 fx output 0 0=OFF 1=ON
590 mFXOutput = mpDisk->ReadInt8()?true:false;
591 // 58 mod>pan 0 -50..50
592 mModulationToPan = mpDisk->ReadInt8();
593 // 59 stereo coherence 0 0=OFF 1=ON
594 mStereoCoherence = mpDisk->ReadInt8()?true:false;
595 // 60 lfo desync 1 0=OFF 1=ON
596 mLFODesync = mpDisk->ReadInt8()?true:false;
597 // 61 pitch law 0 0=LINEAR
598 mPitchLaw = mpDisk->ReadInt8();
599 // 62 voice re-assign 0 0=OLDEST 1=QUIETEST
600 mVoiceReassign = mpDisk->ReadInt8();
601 // 63 softped>volume 10 0..99
602 mSoftpedToVolume = mpDisk->ReadInt8();
603 // 64 softped>attack 10 0..99
604 mSoftpedToAttack = mpDisk->ReadInt8();
605 // 65 softped>filt 10 0..99
606 mSoftpedToFilter = mpDisk->ReadInt8();
607 // 66 tune cents 0 -128..127 (-50..50 cents)
608 mSoftpedToTuneCents = mpDisk->ReadInt8();
609 // 67 tune semitones 0 -50..50
610 mSoftpedToTuneSemitones = mpDisk->ReadInt8();
611 // 68 key>lfo rate 0 -50..50
612 mKeyToLFORate = mpDisk->ReadInt8();
613 // 69 key>lfo depth 0 -50..50
614 mKeyToLFODepth = mpDisk->ReadInt8();
615 // 70 key>lfo delay 0 -50..50
616 mKeyToLFODelay = mpDisk->ReadInt8();
617 // 71 voice output scale 1 0=-6dB 1=0dB 2=+12dB
618 mVoiceOutputScale = mpDisk->ReadInt8();
619 // 72 stereo output scale 0 0=0dB 1=+6dB
620 mStereoOutputScale = mpDisk->ReadInt8();
621 // 73-150 (not used)
622
623 // Read the key groups:
624 if (mpKeygroups)
625 delete[] mpKeygroups;
626
627 const int entrySize =
628 (mpParent->GetDirEntry().mType == AKAI_TYPE_DIR_S3000) ? 192 : 150;
629
630 mpKeygroups = new AkaiKeygroup[mNumberOfKeygroups];
631 for (i = 0; i < mNumberOfKeygroups; i++)
632 {
633 // Go where the key group is on the disk:
634 mpDisk->SetPos(mpParent->GetParent()->GetOffset() + mDirEntry.mStart * AKAI_BLOCK_SIZE + entrySize * (i+1));
635 if (!mpKeygroups[i].Load(mpDisk))
636 {
637 mpDisk->SetPos(temppos);
638 return false;
639 }
640 }
641
642 mpDisk->SetPos(temppos);
643 return true;
644}
645
646uint AkaiProgram::ListSamples(std::list<String>& /*rSamples*/)
647{
648 return 0;
649}
650
651AkaiSample* AkaiProgram::GetSample(uint /*Index*/)
652{
653 return NULL;
654}
655
656AkaiSample* AkaiProgram::GetSample(const String& /*rName*/)
657{
658 return NULL;
659}
660
661// AkaiKeygroup:
662bool AkaiKeygroup::Load(DiskImage* pDisk)
663{
664 uint i;
665 // byte description default range/comments
666 // ---------------------------------------------------------------------------
667 // 1 keygroup ID 2
668 if (pDisk->ReadInt8() != AKAI_KEYGROUP_ID)
669 return false;
670 // 2-3 next keygroup address 44,1 300,450,600,750.. (16-bit)
671 /*uint16_t NextKeygroupAddress =*/ pDisk->ReadInt16();
672 // 4 low key 24 24..127
673 mLowKey = pDisk->ReadInt8();
674 // 5 high key 127 24..127
675 mHighKey = pDisk->ReadInt8();
676 // 6 tune cents 0 -128..127 (-50..50 cents)
677 mTuneCents = pDisk->ReadInt8();
678 // 7 tune semitones 0 -50..50
679 mTuneSemitones = pDisk->ReadInt8();
680 // 8 filter 99 0..99
681 mFilter = pDisk->ReadInt8();
682 // 9 key>filter 12 0..24 semitone/oct
683 mKeyToFilter = pDisk->ReadInt8();
684 // 10 vel>filt 0 -50..50
685 mVelocityToFilter = pDisk->ReadInt8();
686 // 11 pres>filt 0 -50..50
687 mPressureToFilter = pDisk->ReadInt8();
688 // 12 env2>filt 0 -50..50
689 mEnveloppe2ToFilter = pDisk->ReadInt8();
690
691 // 13 env1 attack 0 0..99
692 // 14 env1 decay 30 0..99
693 // 15 env1 sustain 99 0..99
694 // 16 env1 release 45 0..99
695 // 17 env1 vel>attack 0 -50..50
696 // 18 env1 vel>release 0 -50..50
697 // 19 env1 offvel>release 0 -50..50
698 // 20 env1 key>dec&rel 0 -50..50
699 // 21 env2 attack 0 0..99
700 // 22 env2 decay 50 0..99
701 // 23 env2 sustain 99 0..99
702 // 24 env2 release 45 0..99
703 // 25 env2 vel>attack 0 -50..50
704 // 26 env2 vel>release 0 -50..50
705 // 27 env2 offvel>release 0 -50..50
706 // 28 env2 key>dec&rel 0 -50..50
707 for (i=0; i<2; i++)
708 mEnveloppes[i].Load(pDisk);
709
710 // 29 vel>env2>filter 0 -50..50
711 mVelocityToEnveloppe2ToFilter = pDisk->ReadInt8();
712 // 30 env2>pitch 0 -50..50
713 mEnveloppe2ToPitch = pDisk->ReadInt8();
714 // 31 vel zone crossfade 1 0=OFF 1=ON
715 mVelocityZoneCrossfade = pDisk->ReadInt8()?true:false;
716 // 32 vel zones used 4
717 mVelocityZoneUsed = pDisk->ReadInt8();
718 // 33 (internal use) 255
719 pDisk->ReadInt8();
720 // 34 (internal use) 255
721 pDisk->ReadInt8();
722 //
723
724 // 35-46 sample 1 name 10,10,10... AKAII character set
725 // 47 low vel 0 0..127
726 // 48 high vel 127 0..127
727 // 49 tune cents 0 -128..127 (-50..50 cents)
728 // 50 tune semitones 0 -50..50
729 // 51 loudness 0 -50..+50
730 // 52 filter 0 -50..+50
731 // 53 pan 0 -50..+50
732 // 54 loop mode 0 0=AS_SAMPLE 1=LOOP_IN_REL
733 // 2=LOOP_UNTIL_REL 3=NO_LOOP
734 // 4=PLAY_TO_END
735 // 55 (internal use) 255
736 // 56 (internal use) 255
737 // 57-58 (internal use) 44,1
738 //
739 // 59-82 [repeat 35-58 for sample 2]
740 //
741 // 83-106 [repeat 35-58 for sample 3]
742 //
743 // 107-130 [repeat 35-58 for sample 4]
744 //
745 for (i=0; i<4; i++)
746 mSamples[i].Load(pDisk);
747
748 // 131 beat detune 0 -50..50
749 mBeatDetune = pDisk->ReadInt8();
750 // 132 hold attack until loop 0 0=OFF 1=ON
751 mHoldAttackUntilLoop = pDisk->ReadInt8()?true:false;
752 // 133-136 sample 1-4 key tracking 0 0=TRACK 1=FIXED
753 for (i=0; i<4; i++)
754 mSampleKeyTracking[i] = pDisk->ReadInt8()?true:false;
755 // 137-140 sample 1-4 aux out offset 0 0..7
756 for (i=0; i<4; i++)
757 mSampleAuxOutOffset[i] = pDisk->ReadInt8();
758 // 141-148 vel>sample start 0 -9999..9999 (16-bit signed)
759 for (i=0; i<4; i++)
760 mVelocityToSampleStart[i] = pDisk->ReadInt8();
761 // 149 vel>volume offset 0 -50..50
762 for (i=0; i<4; i++)
763 mVelocityToVolumeOffset[i] = pDisk->ReadInt8();
764 // 150 (not used)
765
766 return true;
767}
768
769bool AkaiEnveloppe::Load(DiskImage* pDisk)
770{
771 // 13 env1 attack 0 0..99
772 mAttack = pDisk->ReadInt8();
773 // 14 env1 decay 30 0..99
774 mDecay = pDisk->ReadInt8();
775 // 15 env1 sustain 99 0..99
776 mSustain = pDisk->ReadInt8();
777 // 16 env1 release 45 0..99
778 mRelease = pDisk->ReadInt8();
779 // 17 env1 vel>attack 0 -50..50
780 mVelocityToAttack = pDisk->ReadInt8();
781 // 18 env1 vel>release 0 -50..50
782 mVelocityToRelease = pDisk->ReadInt8();
783 // 19 env1 offvel>release 0 -50..50
784 mOffVelocityToRelease = pDisk->ReadInt8();
785 // 20 env1 key>dec&rel 0 -50..50
786 mKeyToDecayAndRelease = pDisk->ReadInt8();
787 return true;
788}
789
790bool AkaiKeygroupSample::Load(DiskImage* pDisk)
791{
792 // 35-46 sample 1 name 10,10,10... AKAII character set
793 char buffer[13];
794 pDisk->Read(buffer, 12, 1);
795 AkaiToAscii(buffer, 12);
796 mName = buffer;
797
798 // 47 low vel 0 0..127
799 mLowLevel = pDisk->ReadInt8();
800 // 48 high vel 127 0..127
801 /*uint8_t mHighLevel =*/ pDisk->ReadInt8();
802 // 49 tune cents 0 -128..127 (-50..50 cents)
803 /*int8_t mTuneCents =*/ pDisk->ReadInt8();
804 // 50 tune semitones 0 -50..50
805 /*int8_t mTuneSemitones =*/ pDisk->ReadInt8();
806 // 51 loudness 0 -50..+50
807 /*int8_t mLoudness =*/ pDisk->ReadInt8();
808 // 52 filter 0 -50..+50
809 /*int8_t mFilter =*/ pDisk->ReadInt8();
810 // 53 pan 0 -50..+50
811 /*int8_t mPan =*/ pDisk->ReadInt8();
812 // 54 loop mode 0 0=AS_SAMPLE 1=LOOP_IN_REL
813 // 2=LOOP_UNTIL_REL 3=NO_LOOP
814 // 4=PLAY_TO_END
815 /*uint8_t mLoopMode =*/ pDisk->ReadInt8();
816 // 55 (internal use) 255
817 pDisk->ReadInt8();
818 // 56 (internal use) 255
819 pDisk->ReadInt8();
820 // 57-58 (internal use) 44,1
821 pDisk->ReadInt16();
822 //
823
824 return true;
825}
826
828// AkaiVolume:
829AkaiVolume::AkaiVolume(DiskImage* pDisk, AkaiPartition* pParent, const AkaiDirEntry& DirEntry)
830 : AkaiDiskElement()
831{
832 mpDisk = pDisk;
833 mpParent = pParent;
834 mDirEntry = DirEntry;
835
836 if (mDirEntry.mType != AKAI_TYPE_DIR_S1000 && mDirEntry.mType != AKAI_TYPE_DIR_S3000)
837 {
838 printf("Creating Unknown Volume type! %d\n",mDirEntry.mType);
839#ifdef WIN32
840 OutputDebugString("Creating Unknown Volume type!\n");
841#endif
842 }
843}
844
845AkaiVolume::~AkaiVolume()
846{
847 {
848 std::list<AkaiProgram*>::iterator it;
849 std::list<AkaiProgram*>::iterator end = mpPrograms.end();
850 for (it = mpPrograms.begin(); it != end; it++)
851 if (*it)
852 (*it)->Release();
853 }
854
855 {
856 std::list<AkaiSample*>::iterator it;
857 std::list<AkaiSample*>::iterator end = mpSamples.end();
858 for (it = mpSamples.begin(); it != end; it++)
859 if (*it)
860 (*it)->Release();
861 }
862}
863
864uint AkaiVolume::ReadDir()
865{
866 uint i;
867 if (mpPrograms.empty())
868 {
869 uint maxfiles = (mDirEntry.mType == AKAI_TYPE_DIR_S3000) ? AKAI_MAX_FILE_ENTRIES_S3000 : AKAI_MAX_FILE_ENTRIES_S1000;
870 for (i = 0; i < maxfiles; i++)
871 {
872 AkaiDirEntry DirEntry;
873 ReadDirEntry(mpDisk, mpParent, DirEntry, mDirEntry.mStart, i);
874 DirEntry.mIndex = i;
875 if (DirEntry.mType == 'p')
876 {
877 AkaiProgram* pProgram = new AkaiProgram(mpDisk, this, DirEntry);
878 pProgram->Acquire();
879 mpPrograms.push_back(pProgram);
880 }
881 else if (DirEntry.mType == 's')
882 {
883 AkaiSample* pSample = new AkaiSample(mpDisk, this, DirEntry);
884 pSample->Acquire();
885 mpSamples.push_back(pSample);
886 }
887 }
888 }
889 return (uint)(mpPrograms.size() + mpSamples.size());
890}
891
892uint AkaiVolume::ListPrograms(std::list<AkaiDirEntry>& rPrograms)
893{
894 rPrograms.clear();
895 ReadDir();
896
897 std::list<AkaiProgram*>::iterator it;
898 std::list<AkaiProgram*>::iterator end = mpPrograms.end();
899 for (it = mpPrograms.begin(); it != end; it++)
900 if (*it)
901 rPrograms.push_back((*it)->GetDirEntry());
902 return (uint)rPrograms.size();
903}
904
905AkaiProgram* AkaiVolume::GetProgram(uint Index)
906{
907 uint i = 0;
908
909 if (mpPrograms.empty())
910 {
911 std::list<AkaiDirEntry> dummy;
912 ListPrograms(dummy);
913 }
914
915 std::list<AkaiProgram*>::iterator it;
916 std::list<AkaiProgram*>::iterator end = mpPrograms.end();
917 for (it = mpPrograms.begin(); it != end; it++)
918 {
919 if (*it && i == Index)
920 {
921 (*it)->Acquire();
922 return *it;
923 }
924 i++;
925 }
926 return NULL;
927}
928
929AkaiProgram* AkaiVolume::GetProgram(const String& rName)
930{
931 if (mpPrograms.empty())
932 {
933 std::list<AkaiDirEntry> dummy;
934 ListPrograms(dummy);
935 }
936
937 std::list<AkaiProgram*>::iterator it;
938 std::list<AkaiProgram*>::iterator end = mpPrograms.end();
939 for (it = mpPrograms.begin(); it != end; it++)
940 {
941 if (*it && rName == (*it)->GetDirEntry().mName)
942 {
943 (*it)->Acquire();
944 return *it;
945 }
946 }
947 return NULL;
948}
949
950uint AkaiVolume::ListSamples(std::list<AkaiDirEntry>& rSamples)
951{
952 rSamples.clear();
953 ReadDir();
954
955 std::list<AkaiSample*>::iterator it;
956 std::list<AkaiSample*>::iterator end = mpSamples.end();
957 for (it = mpSamples.begin(); it != end; it++)
958 if (*it)
959 rSamples.push_back((*it)->GetDirEntry());
960 return (uint)rSamples.size();
961}
962
963AkaiSample* AkaiVolume::GetSample(uint Index)
964{
965 uint i = 0;
966
967 if (mpSamples.empty())
968 {
969 std::list<AkaiDirEntry> dummy;
970 ListSamples(dummy);
971 }
972
973 std::list<AkaiSample*>::iterator it;
974 std::list<AkaiSample*>::iterator end = mpSamples.end();
975 for (it = mpSamples.begin(); it != end; it++)
976 {
977 if (*it && i == Index)
978 {
979 (*it)->Acquire();
980 return *it;
981 }
982 i++;
983 }
984 return NULL;
985}
986
987AkaiSample* AkaiVolume::GetSample(const String& rName)
988{
989 if (mpSamples.empty())
990 {
991 std::list<AkaiDirEntry> dummy;
992 ListSamples(dummy);
993 }
994
995 std::list<AkaiSample*>::iterator it;
996 std::list<AkaiSample*>::iterator end = mpSamples.end();
997 for (it = mpSamples.begin(); it != end; it++)
998 {
999 if (*it && rName == (*it)->GetDirEntry().mName)
1000 {
1001 (*it)->Acquire();
1002 return *it;
1003 }
1004 }
1005 return NULL;
1006}
1007
1008AkaiDirEntry AkaiVolume::GetDirEntry()
1009{
1010 return mDirEntry;
1011}
1012
1013bool AkaiVolume::IsEmpty()
1014{
1015 return ReadDir() == 0;
1016}
1017
1018
1020// AkaiPartition:
1021AkaiPartition::AkaiPartition(DiskImage* pDisk, AkaiDisk* pParent)
1022{
1023 mpDisk = pDisk;
1024 mpParent = pParent;
1025}
1026
1027AkaiPartition::~AkaiPartition()
1028{
1029 std::list<AkaiVolume*>::iterator it;
1030 std::list<AkaiVolume*>::iterator end = mpVolumes.end();
1031 for (it = mpVolumes.begin(); it != end; it++)
1032 if (*it)
1033 (*it)->Release();
1034}
1035
1036uint AkaiPartition::ListVolumes(std::list<AkaiDirEntry>& rVolumes)
1037{
1038 rVolumes.clear();
1039 uint i;
1040 if (mpVolumes.empty())
1041 {
1042 for (i = 0; i < AKAI_MAX_DIR_ENTRIES; i++)
1043 {
1044 AkaiDirEntry DirEntry;
1045 ReadDirEntry(mpDisk, this, DirEntry, AKAI_ROOT_ENTRY_OFFSET, i);
1046 DirEntry.mIndex = i;
1047 if (DirEntry.mType == AKAI_TYPE_DIR_S1000 || DirEntry.mType == AKAI_TYPE_DIR_S3000)
1048 {
1049 AkaiVolume* pVolume = new AkaiVolume(mpDisk, this, DirEntry);
1050 pVolume->Acquire();
1051 if (!pVolume->IsEmpty())
1052 {
1053 mpVolumes.push_back(pVolume);
1054 rVolumes.push_back(DirEntry);
1055 }
1056 else
1057 pVolume->Release();
1058 }
1059 }
1060 }
1061 else
1062 {
1063 std::list<AkaiVolume*>::iterator it;
1064 std::list<AkaiVolume*>::iterator end = mpVolumes.end();
1065 for (it = mpVolumes.begin(); it != end; it++)
1066 if (*it)
1067 rVolumes.push_back((*it)->GetDirEntry());
1068 }
1069 return (uint)rVolumes.size();
1070}
1071
1072AkaiVolume* AkaiPartition::GetVolume(uint Index)
1073{
1074 uint i = 0;
1075
1076 if (mpVolumes.empty())
1077 {
1078 std::list<AkaiDirEntry> dummy;
1079 ListVolumes(dummy);
1080 }
1081
1082 std::list<AkaiVolume*>::iterator it;
1083 std::list<AkaiVolume*>::iterator end = mpVolumes.end();
1084 for (it = mpVolumes.begin(); it != end; it++)
1085 {
1086 if (*it && i == Index)
1087 {
1088 (*it)->Acquire();
1089 return *it;
1090 }
1091 i++;
1092 }
1093 return NULL;
1094}
1095
1096AkaiVolume* AkaiPartition::GetVolume(const String& rName)
1097{
1098 if (mpVolumes.empty())
1099 {
1100 std::list<AkaiDirEntry> dummy;
1101 ListVolumes(dummy);
1102 }
1103
1104 std::list<AkaiVolume*>::iterator it;
1105 std::list<AkaiVolume*>::iterator end = mpVolumes.end();
1106 for (it = mpVolumes.begin(); it != end; it++)
1107 {
1108 if (*it && rName == (*it)->GetDirEntry().mName)
1109 {
1110 (*it)->Acquire();
1111 return *it;
1112 }
1113 }
1114 return NULL;
1115}
1116
1117bool AkaiPartition::IsEmpty()
1118{
1119 std::list<AkaiDirEntry> Volumes;
1120 return ListVolumes(Volumes) == 0;
1121}
1122
1123
1125// AkaiDisk:
1126AkaiDisk::AkaiDisk(DiskImage* pDisk)
1127{
1128 mpDisk = pDisk;
1129}
1130
1131AkaiDisk::~AkaiDisk()
1132{
1133 std::list<AkaiPartition*>::iterator it;
1134 std::list<AkaiPartition*>::iterator end = mpPartitions.end();
1135 for (it = mpPartitions.begin(); it != end ; it++)
1136 if (*it)
1137 (*it)->Release();
1138}
1139
1140uint AkaiDisk::GetPartitionCount()
1141{
1142 if (!mpPartitions.empty())
1143 return (uint)mpPartitions.size();
1144
1145 uint offset = 0;
1146 uint16_t size = 0;
1147 while (size != AKAI_PARTITION_END_MARK && size != 0x0fff && size != 0xffff
1148 && size<30720 && mpPartitions.size()<9)
1149 {
1150 // printf("size: %x\t",size);
1151 AkaiPartition* pPartition = new AkaiPartition(mpDisk,this);
1152 pPartition->Acquire();
1153 pPartition->SetOffset(offset);
1154
1155 if (!pPartition->IsEmpty())
1156 {
1157 mpPartitions.push_back(pPartition); // Add this partitions' offset to the list.
1158 }
1159
1160 mpDisk->SetPos(offset);
1161 if (!mpDisk->ReadInt16(&size))
1162 return (uint)mpPartitions.size();
1163 uint t = size;
1164 offset += AKAI_BLOCK_SIZE * t;
1165// printf("new offset %d / size %d\n",offset,size);
1166 }
1167
1168 return (uint)mpPartitions.size();
1169}
1170
1171AkaiPartition* AkaiDisk::GetPartition(uint count)
1172{
1173 std::list<AkaiPartition*>::iterator it;
1174 std::list<AkaiPartition*>::iterator end = mpPartitions.end();
1175 uint i = 0;
1176 for (i = 0, it = mpPartitions.begin(); it != end && i != count; i++) it++;
1177
1178 if (i != count || it == end)
1179 return NULL;
1180
1181 (*it)->Acquire();
1182 return *it;
1183}
1184
1186// AkaiDiskElement
1187
1188int AkaiDiskElement::ReadFAT(DiskImage* pDisk, AkaiPartition* pPartition, int block)
1189{
1190 uint16_t value = 0;
1191 pDisk->SetPos(pPartition->GetOffset()+AKAI_FAT_OFFSET + block*2);
1192 pDisk->ReadInt16(&value);
1193 return value;
1194}
1195
1196
1197bool AkaiDiskElement::ReadDirEntry(DiskImage* pDisk, AkaiPartition* pPartition, AkaiDirEntry& rEntry, int block, int pos)
1198{
1199 char buffer[13];
1200
1201 if (block == AKAI_ROOT_ENTRY_OFFSET)
1202 {
1203 pDisk->SetPos(pPartition->GetOffset()+AKAI_DIR_ENTRY_OFFSET + pos * AKAI_DIR_ENTRY_SIZE);
1204 pDisk->Read(buffer, 12, 1);
1205 AkaiToAscii(buffer, 12);
1206 rEntry.mName = buffer;
1207
1208 pDisk->ReadInt16(&rEntry.mType);
1209 pDisk->ReadInt16(&rEntry.mStart);
1210 rEntry.mSize = 0;
1211 return true;
1212 }
1213 else
1214 {
1215 if (pos < 341)
1216 {
1217 pDisk->SetPos(block * AKAI_BLOCK_SIZE + pos * AKAI_FILE_ENTRY_SIZE + pPartition->GetOffset());
1218 }
1219 else
1220 {
1221 int temp;
1222 temp = ReadFAT(pDisk, pPartition, block);
1223 pDisk->SetPos(pPartition->GetOffset()+temp * AKAI_BLOCK_SIZE + (pos - 341) * AKAI_FILE_ENTRY_SIZE);
1224 }
1225
1226 pDisk->Read(buffer, 12, 1);
1227 AkaiToAscii(buffer, 12);
1228 rEntry.mName = buffer;
1229
1230 uint8_t t1,t2,t3;
1231 pDisk->SetPos(4,akai_stream_curpos);
1232 pDisk->Read(&t1, 1,1);
1233 // S1000 disks store the entry type as plain ASCII character, whereas
1234 // S3000 disks do basically the same, but with a high bit set
1235 // (0x80 | 'p' / 0x80 | 's'); strip the high bit so we can use the same
1236 // type comparison for S1000 and S3000
1237 rEntry.mType = t1 & 0x7f;
1238
1239 pDisk->Read(&t1, 1,1);
1240 pDisk->Read(&t2, 1,1);
1241 pDisk->Read(&t3, 1,1);
1242 rEntry.mSize = (unsigned char)t1 | ((unsigned char)t2 <<8) | ((unsigned char)t3<<16);
1243
1244 pDisk->ReadInt16(&rEntry.mStart,1);
1245 return true;
1246 } // not root block
1247}
1248
1249void AkaiDiskElement::AkaiToAscii(char * buffer, int length)
1250{
1251 int i;
1252
1253 for (i = 0; i < length; i++)
1254 {
1255 if (buffer[i]>=0 && buffer[i]<=9)
1256 buffer[i] +=48;
1257 else if (buffer[i]==10)
1258 buffer[i] = 32;
1259 else if (buffer[i]>=11 && buffer[i]<=36)
1260 buffer[i] = 64+(buffer[i]-10);
1261 else
1262 buffer[i] = 32;
1263 }
1264 buffer[length] = '\0';
1265 while (length-- > 0 && buffer[length] == 32)
1266 {
1267 // This block intentionaly left blank :)
1268 }
1269 buffer[length+1] = '\0';
1270}
1271
1272
1274// DiskImage:
1275
1276DiskImage::DiskImage(const char* path)
1277{
1278 Init();
1279 OpenStream(path);
1280}
1281
1282#ifdef _CARBON_
1283kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1284{
1285 kern_return_t kernResult;
1286 mach_port_t masterPort;
1287 CFMutableDictionaryRef classesToMatch;
1288
1289 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1290 if ( KERN_SUCCESS != kernResult )
1291 {
1292 printf( "IOMasterPort returned %d\n", kernResult );
1293 }
1294
1295 classesToMatch = IOServiceMatching( kIOCDMediaClass );
1296 if ( classesToMatch == NULL )
1297 {
1298 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1299 }
1300 else
1301 {
1302 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1303 }
1304
1305 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1306 if ( KERN_SUCCESS != kernResult )
1307 {
1308 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1309 }
1310
1311 return kernResult;
1312}
1313
1314kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
1315{
1316 io_object_t nextMedia;
1317 kern_return_t kernResult = KERN_FAILURE;
1318
1319 *bsdPath = '\0';
1320
1321 nextMedia = IOIteratorNext( mediaIterator );
1322 if ( nextMedia )
1323 {
1324 CFTypeRef bsdPathAsCFString;
1325
1326 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia,
1327 CFSTR( kIOBSDNameKey ),
1328 kCFAllocatorDefault,
1329 0 );
1330 if ( bsdPathAsCFString )
1331 {
1332 size_t devPathLength;
1333
1334 strcpy( bsdPath, _PATH_DEV );
1335 strcat( bsdPath, "r" );
1336
1337 devPathLength = strlen( bsdPath );
1338
1339 if ( CFStringGetCString( (__CFString*)bsdPathAsCFString,
1340 bsdPath + devPathLength,
1341 maxPathSize - devPathLength,
1342 kCFStringEncodingASCII ) )
1343 {
1344 printf( "BSD path: %s\n", bsdPath );
1345 kernResult = KERN_SUCCESS;
1346 }
1347
1348 CFRelease( bsdPathAsCFString );
1349 }
1350 IOObjectRelease( nextMedia );
1351 }
1352
1353 return kernResult;
1354}
1355
1356struct _CDMSF
1357{
1358 u_char minute;
1359 u_char second;
1360 u_char frame;
1361};
1362
1363/* converting from minute-second to logical block entity */
1364#define MSF_TO_LBA(msf) (((((msf).minute * 60UL) + (msf).second) * 75UL) + (msf).frame - 150)
1365
1366struct _CDTOC_Desc
1367{
1368 u_char session;
1369 u_char ctrl_adr; /* typed to be machine and compiler independent */
1370 u_char tno;
1371 u_char point;
1372 struct _CDMSF address;
1373 u_char zero;
1374 struct _CDMSF p;
1375};
1376
1377struct _CDTOC
1378{
1379 u_short length; /* in native cpu endian */
1380 u_char first_session;
1381 u_char last_session;
1382 struct _CDTOC_Desc trackdesc[1];
1383};
1384
1385static struct _CDTOC * ReadTOC (const char * devpath )
1386{
1387 struct _CDTOC * toc_p = NULL;
1388 io_iterator_t iterator = 0;
1389 io_registry_entry_t service = 0;
1390 CFDictionaryRef properties = 0;
1391 CFDataRef data = 0;
1392 mach_port_t port = 0;
1393 char * devname;
1394 if (( devname = strrchr( devpath, '/' )) != NULL )
1395 {
1396 ++devname;
1397 }
1398 else
1399 {
1400 devname = ( char *) devpath;
1401 }
1402
1403 if ( IOMasterPort(bootstrap_port, &port ) != KERN_SUCCESS )
1404 {
1405 printf( "IOMasterPort failed\n" ); goto Exit ;
1406 }
1407 if ( IOServiceGetMatchingServices( port, IOBSDNameMatching( port, 0, devname ),
1408 &iterator ) != KERN_SUCCESS )
1409 {
1410 printf( "IOServiceGetMatchingServices failed\n" ); goto Exit ;
1411 }
1412
1413 char buffer[1024];
1414 IOObjectGetClass(iterator,buffer);
1415 printf("Service: %s\n",buffer);
1416
1417
1418 IOIteratorReset (iterator);
1419 service = IOIteratorNext( iterator );
1420
1421 IOObjectRelease( iterator );
1422
1423 iterator = 0;
1424 while ( service && !IOObjectConformsTo( service, "IOCDMedia" ))
1425 {
1426 char buffer[1024];
1427 IOObjectGetClass(service,buffer);
1428 printf("Service: %s\n",buffer);
1429
1430 if ( IORegistryEntryGetParentIterator( service, kIOServicePlane, &iterator ) != KERN_SUCCESS )
1431 {
1432 printf( "IORegistryEntryGetParentIterator failed\n" );
1433 goto Exit ;
1434 }
1435
1436 IOObjectRelease( service );
1437 service = IOIteratorNext( iterator );
1438 IOObjectRelease( iterator );
1439
1440 }
1441 if ( service == NULL )
1442 {
1443 printf( "CD media not found\n" ); goto Exit ;
1444 }
1445 if ( IORegistryEntryCreateCFProperties( service, (__CFDictionary **) &properties,
1446 kCFAllocatorDefault,
1447 kNilOptions ) != KERN_SUCCESS )
1448 {
1449 printf( "IORegistryEntryGetParentIterator failed\n" ); goto Exit ;
1450 }
1451
1452 data = (CFDataRef) CFDictionaryGetValue( properties, CFSTR( "TOC" ) );
1453 if ( data == NULL )
1454 {
1455 printf( "CFDictionaryGetValue failed\n" ); goto Exit ;
1456 }
1457 else
1458 {
1459
1460 CFRange range;
1461 CFIndex buflen;
1462
1463 buflen = CFDataGetLength( data ) + 1;
1464 range = CFRangeMake( 0, buflen );
1465 toc_p = ( struct _CDTOC *) malloc( buflen );
1466 if ( toc_p == NULL )
1467 {
1468 printf( "Out of memory\n" ); goto Exit ;
1469 }
1470 else
1471 {
1472 CFDataGetBytes( data, range, ( unsigned char *) toc_p );
1473 }
1474
1475 /*
1476 fprintf( stderr, "Table of contents\n length %d first %d last %d\n",
1477 toc_p->length, toc_p->first_session, toc_p->last_session );
1478 */
1479
1480 CFRelease( properties );
1481
1482 }
1483Exit :
1484 if ( service )
1485 {
1486 IOObjectRelease( service );
1487 }
1488
1489 return toc_p;
1490}
1491#endif // _CARBON_
1492
1494{
1495 Init();
1496#ifdef _WIN32_
1497 char buffer[1024];
1498 sprintf(buffer,"%c:\\",'A'+disk);
1499 mSize = GetFileSize(buffer,NULL);
1500
1501 sprintf(buffer,"\\\\.\\%c:",'a'+disk);
1502 mFile = CreateFile(buffer, GENERIC_READ,0,NULL,OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,NULL);
1503
1504 DWORD junk;
1505 DISK_GEOMETRY dg;
1506 DISK_GEOMETRY* pdg = &dg;
1507 BOOL res = DeviceIoControl(mFile,
1508 IOCTL_DISK_GET_DRIVE_GEOMETRY,
1509 NULL, 0,
1510 pdg, sizeof(*pdg),
1511 &junk,
1512 NULL);
1513
1514 if (res)
1515 {
1516 mSize = dg.BytesPerSector * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.Cylinders.LowPart;
1517 mClusterSize = dg.BytesPerSector;
1518 }
1519#elif defined(_CARBON_) || defined(__APPLE__)
1520 kern_return_t kernResult;
1521 io_iterator_t mediaIterator;
1522 char bsdPath[ MAXPATHLEN ];
1523 kernResult = FindEjectableCDMedia( &mediaIterator );
1524 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
1525 if ( bsdPath[ 0 ] != '\0' )
1526 {
1527 strcpy(bsdPath,"/dev/rdisk1s0");
1528
1529 struct _CDTOC * toc = ReadTOC( bsdPath );
1530 if ( toc )
1531 {
1532 size_t toc_entries = ( toc->length - 2 ) / sizeof (struct _CDTOC_Desc );
1533
1534 int start_sector = -1;
1535 int data_track = -1;
1536 // Iterate through the list backward. Pick the first data track and
1537 // get the address of the immediately previous (or following depending
1538 // on how you look at it). The difference in the sector numbers
1539 // is returned as the sized of the data track.
1540 for (ssize_t i=toc_entries - 1; i>=0; i-- )
1541 {
1542 if ( start_sector != -1 )
1543 {
1544 start_sector = MSF_TO_LBA(toc->trackdesc[i].p) - start_sector;
1545 break ;
1546
1547 }
1548 if (( toc->trackdesc[i].ctrl_adr >> 4) != 1 )
1549 continue ;
1550 if ( toc->trackdesc[i].ctrl_adr & 0x04 )
1551 {
1552 data_track = toc->trackdesc[i].point;
1553 start_sector = MSF_TO_LBA(toc->trackdesc[i].p);
1554 }
1555 }
1556
1557 free( toc );
1558 if ( start_sector == -1 )
1559 {
1560 start_sector = 0;
1561 }
1562 }
1563// mSize = start_sector;
1564// printf("size %d\n",mSize);
1565
1566
1567 mFile = open(bsdPath,O_RDONLY);
1568 if (!mFile)
1569 printf("Error while opening file: %s\n",bsdPath);
1570 else
1571 {
1572 printf("opened file: %s\n",bsdPath);
1573
1574 mSize = (int) lseek(mFile,1000000000,SEEK_SET);
1575 printf("size %d\n",mSize);
1576 lseek(mFile,0,SEEK_SET);
1577
1578 mSize = 700 * 1024 * 1024;
1579
1580 }
1581 }
1582 if ( mediaIterator )
1583 {
1584 IOObjectRelease( mediaIterator );
1585 }
1586#elif LINUX
1587 OpenStream("/dev/cdrom");
1588#endif
1589}
1590
1591void DiskImage::Init()
1592{
1593 mFile = 0;
1594 mPos = 0;
1595 mCluster = (uint)-1;
1596 mStartFrame = -1;
1597 mEndFrame = -1;
1598#ifdef WIN32
1599 mpCache = (char*) VirtualAlloc(NULL,mClusterSize,MEM_COMMIT,PAGE_READWRITE);
1600#else
1601 mpCache = NULL; // we allocate the cache later when we know what type of media we access
1602#endif
1603}
1604
1605DiskImage::~DiskImage()
1606{
1607#ifdef WIN32
1608 if (mFile != INVALID_HANDLE_VALUE)
1609 {
1610 CloseHandle(mFile);
1611 }
1612#elif defined _CARBON_ || defined(__APPLE__) || LINUX
1613 if (mFile)
1614 {
1615 close(mFile);
1616 }
1617#endif
1618 if (mpCache)
1619 {
1620#ifdef WIN32
1621 VirtualFree(mpCache, 0, MEM_RELEASE);
1622#elif defined(_CARBON_) || defined(__APPLE__) || LINUX
1623 free(mpCache);
1624#endif
1625 }
1626}
1627
1628akai_stream_state_t DiskImage::GetState() const
1629{
1630 if (!mFile) return akai_stream_closed;
1631 if (mPos > mSize) return akai_stream_end_reached;
1632 return akai_stream_ready;
1633}
1634
1635int DiskImage::GetPos() const
1636{
1637 return mPos;
1638}
1639
1640int DiskImage::SetPos(int Where, akai_stream_whence_t Whence)
1641{
1642// printf("setpos %d\n",Where);
1643 int w = Where;
1644 switch (Whence)
1645 {
1646 case akai_stream_start:
1647 mPos = w;
1648 break;
1649 /*case eStreamRewind:
1650 w = -w;*/
1651 case akai_stream_curpos:
1652 mPos += w;
1653 break;
1654 case akai_stream_end:
1655 mPos = mSize - w;
1656 break;
1657 }
1658// if (mPos > mSize)
1659// mPos = mSize;
1660 if (mPos < 0)
1661 mPos = 0;
1662 return mPos;
1663}
1664
1665int DiskImage::Available (uint WordSize)
1666{
1667 return (mSize-mPos)/WordSize;
1668}
1669
1670int DiskImage::Read(void* pData, uint WordCount, uint WordSize)
1671{
1672 int readbytes = 0;
1673 int sizetoread = WordCount * WordSize;
1674
1675 while (sizetoread > 0) {
1676 if (mSize <= mPos) return readbytes / WordSize;
1677 int requestedCluster = (mRegularFile) ? mPos / mClusterSize
1678 : mPos / mClusterSize + mStartFrame;
1679 if (mCluster != requestedCluster) { // read the requested cluster into cache
1680 mCluster = requestedCluster;
1681#ifdef WIN32
1682 if (mCluster * mClusterSize != SetFilePointer(mFile, mCluster * mClusterSize, NULL, FILE_BEGIN)) {
1683 printf("ERROR: couldn't seek device!\n");
1684#if 0 // FIXME: endian correction is missing correct detection
1685 if ((readbytes > 0) && (mEndian != eEndianNative)) {
1686 switch (WordSize) {
1687 case 2: bswap_16_s ((uint16*)pData, readbytes); break;
1688 case 4: bswap_32_s ((uint32*)pData, readbytes); break;
1689 case 8: bswap_64_s ((uint64*)pData, readbytes); break;
1690 }
1691 }
1692#endif
1693 return readbytes / WordSize;
1694 }
1695 DWORD size;
1696 ReadFile(mFile, mpCache, mClusterSize, &size, NULL);
1697#elif defined(_CARBON_) || defined(__APPLE__) || LINUX
1698 if (mCluster * mClusterSize != lseek(mFile, mCluster * mClusterSize, SEEK_SET))
1699 return readbytes / WordSize;
1700// printf("trying to read %d bytes from device!\n",mClusterSize);
1701 /*int size =*/ read(mFile, mpCache, mClusterSize);
1702// printf("read %d bytes from device!\n",size);
1703#endif
1704 }
1705// printf("read %d bytes at pos %d\n",WordCount*WordSize,mPos);
1706
1707 int currentReadSize = sizetoread;
1708 int posInCluster = mPos % mClusterSize;
1709 if (currentReadSize > mClusterSize - posInCluster) // restrict to this current cached cluster.
1710 currentReadSize = mClusterSize - posInCluster;
1711
1712 memcpy((uint8_t*)pData + readbytes, mpCache + posInCluster, currentReadSize);
1713
1714 mPos += currentReadSize;
1715 readbytes += currentReadSize;
1716 sizetoread -= currentReadSize;
1717// printf("new pos %d\n",mPos);
1718 }
1719
1720#if 0 // FIXME: endian correction is missing correct detection
1721 if ((readbytes > 0) && (mEndian != eEndianNative))
1722 switch (WordSize)
1723 {
1724 case 2: bswap_16_s ((uint16_t*)pData, readbytes); break;
1725 case 4: bswap_32_s ((uint32_t*)pData, readbytes); break;
1726 case 8: bswap_64_s ((uint64_t*)pData, readbytes); break;
1727 }
1728#endif
1729
1730 return readbytes / WordSize;
1731}
1732
1733void DiskImage::ReadInt8(uint8_t* pData, uint WordCount) {
1734 Read(pData, WordCount, 1);
1735}
1736
1737void DiskImage::ReadInt16(uint16_t* pData, uint WordCount) {
1738 int i;
1739 for (i = 0; i < WordCount; i++) {
1740 *(pData + i) = ReadInt16();
1741 }
1742}
1743
1744void DiskImage::ReadInt32(uint32_t* pData, uint WordCount) {
1745 int i;
1746 for (i = 0; i < WordCount; i++) {
1747 *(pData + i) = ReadInt32();
1748 }
1749}
1750
1751int DiskImage::ReadInt8(uint8_t* pData) {
1752 return Read(pData, 1, 1);
1753}
1754
1755int DiskImage::ReadInt16(uint16_t* pData) {
1756 int result = Read(pData, 1, 2);
1757#if WORDS_BIGENDIAN
1758 swapBytes_16(pData);
1759#endif
1760 return result;
1761}
1762
1763int DiskImage::ReadInt32(uint32_t* pData) {
1764 int result = Read(pData, 1, 4);
1765#if WORDS_BIGENDIAN
1766 swapBytes_32(pData);
1767#endif
1768 return result;
1769}
1770
1771uint8_t DiskImage::ReadInt8()
1772{
1773 uint8_t word;
1774 Read(&word,1,1);
1775 return word;
1776}
1777
1778uint16_t DiskImage::ReadInt16()
1779{
1780 uint16_t word;
1781 Read(&word,1,2);
1782#if WORDS_BIGENDIAN
1783 swapBytes_16(&word);
1784#endif
1785 return word;
1786}
1787
1788uint32_t DiskImage::ReadInt32()
1789{
1790 uint32_t word;
1791 Read(&word,1,4);
1792#if WORDS_BIGENDIAN
1793 swapBytes_32(&word);
1794#endif
1795 return word;
1796}
1797
1798void DiskImage::OpenStream(const char* path) {
1799#ifdef WIN32
1800 mFile = CreateFile(path, GENERIC_READ,0,NULL,OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,NULL);
1801 BY_HANDLE_FILE_INFORMATION FileInfo;
1802 GetFileInformationByHandle(mFile,&FileInfo);
1803 mSize = FileInfo.nFileSizeLow;
1804#elif defined(_CARBON_) || defined(__APPLE__) || LINUX
1805 struct stat filestat;
1806 stat(path,&filestat);
1807 mFile = open(path, O_RDONLY | O_NONBLOCK);
1808 if (mFile <= 0) {
1809 printf("Can't open %s\n", path);
1810 mFile = 0;
1811 return;
1812 }
1813 // TODO: we should also check here if 'path' is a link or something
1814 if (S_ISREG(filestat.st_mode)) { // regular file
1815 printf("Using regular Akai image file.\n");
1816 mRegularFile = true;
1817 mSize = (int) filestat.st_size;
1818 mClusterSize = DISK_CLUSTER_SIZE;
1819 mpCache = (char*) malloc(mClusterSize);
1820 } else { // CDROM
1821#if defined(_CARBON_) || defined(__APPLE__)
1822 printf("Can't open %s: not a regular file\n", path);
1823#elif HAVE_LINUX_CDROM
1824 mRegularFile = false;
1825 mClusterSize = CD_FRAMESIZE;
1826 mpCache = (char*) malloc(mClusterSize);
1827
1828 struct cdrom_tochdr tochdr;
1829 struct cdrom_tocentry tocentry;
1830 int prev_addr = 0;
1831 if (ioctl(mFile, CDROMREADTOCHDR, (unsigned long)&tochdr) < 0) {
1832 printf("Trying to read TOC of %s failed\n", path);
1833 close(mFile);
1834 mFile = 0;
1835 return;
1836 }
1837 printf("Total tracks: %d\n", tochdr.cdth_trk1);
1838
1839 /* we access the CD with logical blocks as entity */
1840 tocentry.cdte_format = CDROM_LBA;
1841
1842 int firstDataTrack = -1;
1843 int start, end, length;
1844
1845 /* we pick up the lowest data track by iterating backwards, starting with Lead Out */
1846 for (int t = tochdr.cdth_trk1; t >= 0; t--) {
1847 tocentry.cdte_track = (t == tochdr.cdth_trk1) ? CDROM_LEADOUT : t + 1;
1848 if (ioctl(mFile, CDROMREADTOCENTRY, (unsigned long)&tocentry) < 0){
1849 printf("Failed to read TOC entry for track %d\n", tocentry.cdte_track);
1850 close(mFile);
1851 mFile = 0;
1852 return;
1853 }
1854 if (tocentry.cdte_track == CDROM_LEADOUT) {
1855 printf("Lead Out: Start(LBA)=%d\n", tocentry.cdte_addr.lba);
1856 }
1857 else {
1858 printf("Track %d: Start(LBA)=%d End(LBA)=%d Length(Blocks)=%d ",
1859 tocentry.cdte_track, tocentry.cdte_addr.lba, prev_addr - 1, prev_addr - tocentry.cdte_addr.lba);
1860 if (tocentry.cdte_ctrl & CDROM_DATA_TRACK) {
1861 printf("Type: Data\n");
1862 firstDataTrack = tocentry.cdte_track;
1863 start = tocentry.cdte_addr.lba;
1864 end = prev_addr - 1;
1865 length = prev_addr - tocentry.cdte_addr.lba;
1866 }
1867 else printf("Type: Audio\n");
1868 }
1869 prev_addr = tocentry.cdte_addr.lba;
1870 }
1871
1872 if (firstDataTrack == -1) {
1873 printf("Sorry, no data track found on %s\n", path);
1874 close(mFile);
1875 mFile = 0;
1876 return;
1877 }
1878
1879 printf("Ok, I'll pick track %d\n", firstDataTrack);
1880 mStartFrame = start;
1881 mEndFrame = end;
1882 mSize = length * CD_FRAMESIZE;
1883#else
1884 printf("Can't open %s: raw CD-ROM access is not supported on this platform\n", path);
1885 close(mFile);
1886 mFile = 0;
1887#endif
1888 } // CDROM
1889#endif
1890}
1891
1892bool DiskImage::WriteImage(const char* path)
1893{
1894#if defined(_CARBON_) || defined(__APPLE__) || LINUX
1895 const uint bufferSize = 524288; // 512 kB
1896 int fOut = open(path, O_WRONLY | O_NONBLOCK | O_CREAT | O_TRUNC,
1897 S_IRUSR | S_IWUSR | S_IRGRP);
1898 if (mFile <= 0) {
1899 printf("Can't open output file %s\n", path);
1900 return false;
1901 }
1902 uint8_t* pBuffer = new uint8_t[bufferSize];
1903 SetPos(0);
1904 while (Available() > 0) {
1905 int readBytes = Read(pBuffer,bufferSize,1);
1906 if (readBytes > 0) write(fOut,pBuffer,readBytes);
1907 }
1908 delete[] pBuffer;
1909 close(fOut);
1910 return true;
1911#endif // _CARBON_ || LINUX
1912 return false;
1913}
1914
1915inline void DiskImage::swapBytes_16(void* Word) {
1916 uint8_t byteCache;
1917 byteCache = *((uint8_t*) Word);
1918 *((uint8_t*) Word) = *((uint8_t*) Word + 1);
1919 *((uint8_t*) Word + 1) = byteCache;
1920}
1921
1922inline void DiskImage::swapBytes_32(void* Word) {
1923 uint8_t byteCache;
1924 byteCache = *((uint8_t*) Word);
1925 *((uint8_t*) Word) = *((uint8_t*) Word + 3);
1926 *((uint8_t*) Word + 3) = byteCache;
1927 byteCache = *((uint8_t*) Word + 1);
1928 *((uint8_t*) Word + 1) = *((uint8_t*) Word + 2);
1929 *((uint8_t*) Word + 2) = byteCache;
1930}
Toplevel AKAI image interpreter.
Definition Akai.h:705
Encapsulates one disk partition of an AKAI disk.
Definition Akai.h:671
AKAI instrument definition.
Definition Akai.h:492
Subdivision of an AKAI disk partition.
Definition Akai.h:628
Accessing AKAI image either from file or a drive (i.e.
Definition Akai.h:119
bool WriteImage(const char *path)
Extract Akai data track and write it into a regular file.
Definition Akai.cpp:1892
virtual int Read(void *pData, uint WordCount, uint WordSize)
Returns number of successfully read words.
Definition Akai.cpp:1670
DiskImage(const char *path)
Open an image from a file.
Definition Akai.cpp:1276