Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

492 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. const int kilobytesPerSecond1x = 176;
  18. struct AudioTrackProducerClass : public ObjCClass <NSObject>
  19. {
  20. AudioTrackProducerClass() : ObjCClass <NSObject> ("JUCEAudioTrackProducer_")
  21. {
  22. addIvar<AudioSourceHolder*> ("source");
  23. addMethod (@selector (initWithAudioSourceHolder:), initWithAudioSourceHolder, "@@:^v");
  24. addMethod (@selector (cleanupTrackAfterBurn:), cleanupTrackAfterBurn, "v@:@");
  25. addMethod (@selector (cleanupTrackAfterVerification:), cleanupTrackAfterVerification, "c@:@");
  26. addMethod (@selector (estimateLengthOfTrack:), estimateLengthOfTrack, "Q@:@");
  27. addMethod (@selector (prepareTrack:forBurn:toMedia:), prepareTrack, "c@:@@@");
  28. addMethod (@selector (prepareTrackForVerification:), prepareTrackForVerification, "c@:@");
  29. addMethod (@selector (produceDataForTrack:intoBuffer:length:atAddress:blockSize:ioFlags:),
  30. produceDataForTrack, "I@:@^cIQI^I");
  31. addMethod (@selector (producePreGapForTrack:intoBuffer:length:atAddress:blockSize:ioFlags:),
  32. produceDataForTrack, "I@:@^cIQI^I");
  33. addMethod (@selector (verifyDataForTrack:intoBuffer:length:atAddress:blockSize:ioFlags:),
  34. produceDataForTrack, "I@:@^cIQI^I");
  35. registerClass();
  36. }
  37. struct AudioSourceHolder
  38. {
  39. AudioSourceHolder (AudioSource* source_, int numFrames)
  40. : source (source_), readPosition (0), lengthInFrames (numFrames)
  41. {
  42. }
  43. ~AudioSourceHolder()
  44. {
  45. if (source != nullptr)
  46. source->releaseResources();
  47. }
  48. ScopedPointer<AudioSource> source;
  49. int readPosition, lengthInFrames;
  50. };
  51. private:
  52. static id initWithAudioSourceHolder (id self, SEL, AudioSourceHolder* source)
  53. {
  54. self = sendSuperclassMessage (self, @selector (init));
  55. object_setInstanceVariable (self, "source", source);
  56. return self;
  57. }
  58. static AudioSourceHolder* getSource (id self)
  59. {
  60. return getIvar<AudioSourceHolder*> (self, "source");
  61. }
  62. static void dealloc (id self, SEL)
  63. {
  64. delete getSource (self);
  65. sendSuperclassMessage (self, @selector (dealloc));
  66. }
  67. static void cleanupTrackAfterBurn (id self, SEL, DRTrack*) {}
  68. static BOOL cleanupTrackAfterVerification (id self, SEL, DRTrack*) { return true; }
  69. static uint64_t estimateLengthOfTrack (id self, SEL, DRTrack*)
  70. {
  71. return getSource (self)->lengthInFrames;
  72. }
  73. static BOOL prepareTrack (id self, SEL, DRTrack*, DRBurn*, NSDictionary*)
  74. {
  75. if (AudioSourceHolder* const source = getSource (self))
  76. {
  77. source->source->prepareToPlay (44100 / 75, 44100);
  78. source->readPosition = 0;
  79. }
  80. return true;
  81. }
  82. static BOOL prepareTrackForVerification (id self, SEL, DRTrack*)
  83. {
  84. if (AudioSourceHolder* const source = getSource (self))
  85. source->source->prepareToPlay (44100 / 75, 44100);
  86. return true;
  87. }
  88. static uint32_t produceDataForTrack (id self, SEL, DRTrack*, char* buffer,
  89. uint32_t bufferLength, uint64_t /*address*/,
  90. uint32_t /*blockSize*/, uint32_t* /*flags*/)
  91. {
  92. if (AudioSourceHolder* const source = getSource (self))
  93. {
  94. const int numSamples = jmin ((int) bufferLength / 4,
  95. (source->lengthInFrames * (44100 / 75)) - source->readPosition);
  96. if (numSamples > 0)
  97. {
  98. AudioSampleBuffer tempBuffer (2, numSamples);
  99. AudioSourceChannelInfo info (tempBuffer);
  100. source->source->getNextAudioBlock (info);
  101. typedef AudioData::Pointer <AudioData::Int16,
  102. AudioData::LittleEndian,
  103. AudioData::Interleaved,
  104. AudioData::NonConst> CDSampleFormat;
  105. typedef AudioData::Pointer <AudioData::Float32,
  106. AudioData::NativeEndian,
  107. AudioData::NonInterleaved,
  108. AudioData::Const> SourceSampleFormat;
  109. CDSampleFormat left (buffer, 2);
  110. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  111. CDSampleFormat right (buffer + 2, 2);
  112. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  113. source->readPosition += numSamples;
  114. }
  115. return numSamples * 4;
  116. }
  117. return 0;
  118. }
  119. static uint32_t producePreGapForTrack (id self, SEL, DRTrack*, char* buffer,
  120. uint32_t bufferLength, uint64_t /*address*/,
  121. uint32_t /*blockSize*/, uint32_t* /*flags*/)
  122. {
  123. zeromem (buffer, bufferLength);
  124. return bufferLength;
  125. }
  126. static BOOL verifyDataForTrack (id self, SEL, DRTrack*, const char*,
  127. uint32_t /*bufferLength*/, uint64_t /*address*/,
  128. uint32_t /*blockSize*/, uint32_t* /*flags*/)
  129. {
  130. return true;
  131. }
  132. };
  133. struct OpenDiskDevice
  134. {
  135. OpenDiskDevice (DRDevice* device_)
  136. : device (device_),
  137. tracks ([[NSMutableArray alloc] init]),
  138. underrunProtection (true)
  139. {
  140. }
  141. ~OpenDiskDevice()
  142. {
  143. [tracks release];
  144. }
  145. void addSourceTrack (AudioSource* source, int numSamples)
  146. {
  147. if (source != nullptr)
  148. {
  149. const int numFrames = (numSamples + 587) / 588;
  150. static AudioTrackProducerClass cls;
  151. NSObject* producer = [cls.createInstance() performSelector: @selector (initWithAudioSourceHolder:)
  152. withObject: (id) new AudioTrackProducerClass::AudioSourceHolder (source, numFrames)];
  153. DRTrack* track = [[DRTrack alloc] initWithProducer: producer];
  154. {
  155. NSMutableDictionary* p = [[track properties] mutableCopy];
  156. [p setObject: [DRMSF msfWithFrames: numFrames] forKey: DRTrackLengthKey];
  157. [p setObject: [NSNumber numberWithUnsignedShort: 2352] forKey: DRBlockSizeKey];
  158. [p setObject: [NSNumber numberWithInt: 0] forKey: DRDataFormKey];
  159. [p setObject: [NSNumber numberWithInt: 0] forKey: DRBlockTypeKey];
  160. [p setObject: [NSNumber numberWithInt: 0] forKey: DRTrackModeKey];
  161. [p setObject: [NSNumber numberWithInt: 0] forKey: DRSessionFormatKey];
  162. [track setProperties: p];
  163. [p release];
  164. }
  165. [tracks addObject: track];
  166. [track release];
  167. [producer release];
  168. }
  169. }
  170. String burn (AudioCDBurner::BurnProgressListener* listener,
  171. bool shouldEject, bool peformFakeBurnForTesting, int burnSpeed)
  172. {
  173. DRBurn* burn = [DRBurn burnForDevice: device];
  174. if (! [device acquireExclusiveAccess])
  175. return "Couldn't open or write to the CD device";
  176. [device acquireMediaReservation];
  177. NSMutableDictionary* d = [[burn properties] mutableCopy];
  178. [d autorelease];
  179. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  180. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  181. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  182. if (burnSpeed > 0)
  183. [d setObject: [NSNumber numberWithFloat: burnSpeed * kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  184. if (! underrunProtection)
  185. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  186. [burn setProperties: d];
  187. [burn writeLayout: tracks];
  188. for (;;)
  189. {
  190. Thread::sleep (300);
  191. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  192. if (listener != nullptr && listener->audioCDBurnProgress (progress))
  193. {
  194. [burn abort];
  195. return "User cancelled the write operation";
  196. }
  197. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  198. return "Write operation failed";
  199. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  200. break;
  201. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  202. objectForKey: DRErrorStatusErrorStringKey];
  203. if ([err length] > 0)
  204. return CharPointer_UTF8 ([err UTF8String]);
  205. }
  206. [device releaseMediaReservation];
  207. [device releaseExclusiveAccess];
  208. return String::empty;
  209. }
  210. DRDevice* device;
  211. NSMutableArray* tracks;
  212. bool underrunProtection;
  213. };
  214. //==============================================================================
  215. class AudioCDBurner::Pimpl : public Timer
  216. {
  217. public:
  218. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  219. : device (0), owner (owner_)
  220. {
  221. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  222. if (dev != nil)
  223. {
  224. device = new OpenDiskDevice (dev);
  225. lastState = getDiskState();
  226. startTimer (1000);
  227. }
  228. }
  229. ~Pimpl()
  230. {
  231. stopTimer();
  232. }
  233. void timerCallback() override
  234. {
  235. const DiskState state = getDiskState();
  236. if (state != lastState)
  237. {
  238. lastState = state;
  239. owner.sendChangeMessage();
  240. }
  241. }
  242. DiskState getDiskState() const
  243. {
  244. if ([device->device isValid])
  245. {
  246. NSDictionary* status = [device->device status];
  247. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  248. if ([state isEqualTo: DRDeviceMediaStateNone])
  249. {
  250. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  251. return trayOpen;
  252. return noDisc;
  253. }
  254. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  255. {
  256. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  257. return writableDiskPresent;
  258. else
  259. return readOnlyDiskPresent;
  260. }
  261. }
  262. return unknown;
  263. }
  264. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  265. Array<int> getAvailableWriteSpeeds() const
  266. {
  267. Array<int> results;
  268. if ([device->device isValid])
  269. {
  270. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  271. for (unsigned int i = 0; i < [speeds count]; ++i)
  272. {
  273. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  274. results.add (kbPerSec / kilobytesPerSecond1x);
  275. }
  276. }
  277. return results;
  278. }
  279. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  280. {
  281. if ([device->device isValid])
  282. {
  283. device->underrunProtection = shouldBeEnabled;
  284. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  285. }
  286. return false;
  287. }
  288. int getNumAvailableAudioBlocks() const
  289. {
  290. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  291. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  292. }
  293. ScopedPointer<OpenDiskDevice> device;
  294. private:
  295. DiskState lastState;
  296. AudioCDBurner& owner;
  297. };
  298. //==============================================================================
  299. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  300. {
  301. pimpl = new Pimpl (*this, deviceIndex);
  302. }
  303. AudioCDBurner::~AudioCDBurner()
  304. {
  305. }
  306. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  307. {
  308. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  309. if (b->pimpl->device == nil)
  310. b = 0;
  311. return b.release();
  312. }
  313. namespace
  314. {
  315. NSArray* findDiskBurnerDevices()
  316. {
  317. NSMutableArray* results = [NSMutableArray array];
  318. NSArray* devs = [DRDevice devices];
  319. for (int i = 0; i < [devs count]; ++i)
  320. {
  321. NSDictionary* dic = [[devs objectAtIndex: i] info];
  322. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  323. if (name != nil)
  324. [results addObject: name];
  325. }
  326. return results;
  327. }
  328. }
  329. StringArray AudioCDBurner::findAvailableDevices()
  330. {
  331. NSArray* names = findDiskBurnerDevices();
  332. StringArray s;
  333. for (unsigned int i = 0; i < [names count]; ++i)
  334. s.add (CharPointer_UTF8 ([[names objectAtIndex: i] UTF8String]));
  335. return s;
  336. }
  337. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  338. {
  339. return pimpl->getDiskState();
  340. }
  341. bool AudioCDBurner::isDiskPresent() const
  342. {
  343. return getDiskState() == writableDiskPresent;
  344. }
  345. bool AudioCDBurner::openTray()
  346. {
  347. return pimpl->openTray();
  348. }
  349. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  350. {
  351. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  352. DiskState oldState = getDiskState();
  353. DiskState newState = oldState;
  354. while (newState == oldState && Time::currentTimeMillis() < timeout)
  355. {
  356. newState = getDiskState();
  357. Thread::sleep (100);
  358. }
  359. return newState;
  360. }
  361. Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  362. {
  363. return pimpl->getAvailableWriteSpeeds();
  364. }
  365. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  366. {
  367. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  368. }
  369. int AudioCDBurner::getNumAvailableAudioBlocks() const
  370. {
  371. return pimpl->getNumAvailableAudioBlocks();
  372. }
  373. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  374. {
  375. if ([pimpl->device->device isValid])
  376. {
  377. pimpl->device->addSourceTrack (source, numSamps);
  378. return true;
  379. }
  380. return false;
  381. }
  382. String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  383. bool ejectDiscAfterwards,
  384. bool performFakeBurnForTesting,
  385. int writeSpeed)
  386. {
  387. if ([pimpl->device->device isValid])
  388. return pimpl->device->burn (listener, ejectDiscAfterwards, performFakeBurnForTesting, writeSpeed);
  389. return "Couldn't open or write to the CD device";
  390. }