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.

456 lines
15KB

  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* s, int numFrames)
  40. : source (s), 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, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  102. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  103. CDSampleFormat left (buffer, 2);
  104. left.convertSamples (SourceSampleFormat (tempBuffer.getReadPointer (0)), numSamples);
  105. CDSampleFormat right (buffer + 2, 2);
  106. right.convertSamples (SourceSampleFormat (tempBuffer.getReadPointer (1)), numSamples);
  107. source->readPosition += numSamples;
  108. }
  109. return numSamples * 4;
  110. }
  111. return 0;
  112. }
  113. static uint32_t producePreGapForTrack (id self, SEL, DRTrack*, char* buffer,
  114. uint32_t bufferLength, uint64_t /*address*/,
  115. uint32_t /*blockSize*/, uint32_t* /*flags*/)
  116. {
  117. zeromem (buffer, bufferLength);
  118. return bufferLength;
  119. }
  120. static BOOL verifyDataForTrack (id self, SEL, DRTrack*, const char*,
  121. uint32_t /*bufferLength*/, uint64_t /*address*/,
  122. uint32_t /*blockSize*/, uint32_t* /*flags*/)
  123. {
  124. return true;
  125. }
  126. };
  127. struct OpenDiskDevice
  128. {
  129. OpenDiskDevice (DRDevice* d)
  130. : device (d),
  131. tracks ([[NSMutableArray alloc] init]),
  132. underrunProtection (true)
  133. {
  134. }
  135. ~OpenDiskDevice()
  136. {
  137. [tracks release];
  138. }
  139. void addSourceTrack (AudioSource* source, int numSamples)
  140. {
  141. if (source != nullptr)
  142. {
  143. const int numFrames = (numSamples + 587) / 588;
  144. static AudioTrackProducerClass cls;
  145. NSObject* producer = [cls.createInstance() performSelector: @selector (initWithAudioSourceHolder:)
  146. withObject: (id) new AudioTrackProducerClass::AudioSourceHolder (source, numFrames)];
  147. DRTrack* track = [[DRTrack alloc] initWithProducer: producer];
  148. {
  149. NSMutableDictionary* p = [[track properties] mutableCopy];
  150. [p setObject: [DRMSF msfWithFrames: numFrames] forKey: DRTrackLengthKey];
  151. [p setObject: [NSNumber numberWithUnsignedShort: 2352] forKey: DRBlockSizeKey];
  152. [p setObject: [NSNumber numberWithInt: 0] forKey: DRDataFormKey];
  153. [p setObject: [NSNumber numberWithInt: 0] forKey: DRBlockTypeKey];
  154. [p setObject: [NSNumber numberWithInt: 0] forKey: DRTrackModeKey];
  155. [p setObject: [NSNumber numberWithInt: 0] forKey: DRSessionFormatKey];
  156. [track setProperties: p];
  157. [p release];
  158. }
  159. [tracks addObject: track];
  160. [track release];
  161. [producer release];
  162. }
  163. }
  164. String burn (AudioCDBurner::BurnProgressListener* listener,
  165. bool shouldEject, bool peformFakeBurnForTesting, int burnSpeed)
  166. {
  167. DRBurn* burn = [DRBurn burnForDevice: device];
  168. if (! [device acquireExclusiveAccess])
  169. return "Couldn't open or write to the CD device";
  170. [device acquireMediaReservation];
  171. NSMutableDictionary* d = [[burn properties] mutableCopy];
  172. [d autorelease];
  173. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  174. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  175. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  176. if (burnSpeed > 0)
  177. [d setObject: [NSNumber numberWithFloat: burnSpeed * kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  178. if (! underrunProtection)
  179. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  180. [burn setProperties: d];
  181. [burn writeLayout: tracks];
  182. for (;;)
  183. {
  184. Thread::sleep (300);
  185. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  186. if (listener != nullptr && listener->audioCDBurnProgress (progress))
  187. {
  188. [burn abort];
  189. return "User cancelled the write operation";
  190. }
  191. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  192. return "Write operation failed";
  193. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  194. break;
  195. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  196. objectForKey: DRErrorStatusErrorStringKey];
  197. if ([err length] > 0)
  198. return nsStringToJuce (err);
  199. }
  200. [device releaseMediaReservation];
  201. [device releaseExclusiveAccess];
  202. return String::empty;
  203. }
  204. DRDevice* device;
  205. NSMutableArray* tracks;
  206. bool underrunProtection;
  207. };
  208. //==============================================================================
  209. class AudioCDBurner::Pimpl : public Timer
  210. {
  211. public:
  212. Pimpl (AudioCDBurner& b, int deviceIndex) : owner (b)
  213. {
  214. if (DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex])
  215. {
  216. device = new OpenDiskDevice (dev);
  217. lastState = getDiskState();
  218. startTimer (1000);
  219. }
  220. }
  221. ~Pimpl()
  222. {
  223. stopTimer();
  224. }
  225. void timerCallback() override
  226. {
  227. const DiskState state = getDiskState();
  228. if (state != lastState)
  229. {
  230. lastState = state;
  231. owner.sendChangeMessage();
  232. }
  233. }
  234. DiskState getDiskState() const
  235. {
  236. if ([device->device isValid])
  237. {
  238. NSDictionary* status = [device->device status];
  239. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  240. if ([state isEqualTo: DRDeviceMediaStateNone])
  241. {
  242. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  243. return trayOpen;
  244. return noDisc;
  245. }
  246. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  247. {
  248. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  249. return writableDiskPresent;
  250. return readOnlyDiskPresent;
  251. }
  252. }
  253. return unknown;
  254. }
  255. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  256. Array<int> getAvailableWriteSpeeds() const
  257. {
  258. Array<int> results;
  259. if ([device->device isValid])
  260. for (id kbPerSec in [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey])
  261. results.add ([kbPerSec intValue] / kilobytesPerSecond1x);
  262. return results;
  263. }
  264. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  265. {
  266. if ([device->device isValid])
  267. {
  268. device->underrunProtection = shouldBeEnabled;
  269. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  270. }
  271. return false;
  272. }
  273. int getNumAvailableAudioBlocks() const
  274. {
  275. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  276. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  277. }
  278. ScopedPointer<OpenDiskDevice> device;
  279. private:
  280. DiskState lastState;
  281. AudioCDBurner& owner;
  282. };
  283. //==============================================================================
  284. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  285. {
  286. pimpl = new Pimpl (*this, deviceIndex);
  287. }
  288. AudioCDBurner::~AudioCDBurner()
  289. {
  290. }
  291. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  292. {
  293. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  294. if (b->pimpl->device == nil)
  295. b = nullptr;
  296. return b.release();
  297. }
  298. StringArray AudioCDBurner::findAvailableDevices()
  299. {
  300. StringArray s;
  301. for (NSDictionary* dic in [DRDevice devices])
  302. if (NSString* name = [dic valueForKey: DRDeviceProductNameKey])
  303. s.add (nsStringToJuce (name));
  304. return s;
  305. }
  306. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  307. {
  308. return pimpl->getDiskState();
  309. }
  310. bool AudioCDBurner::isDiskPresent() const
  311. {
  312. return getDiskState() == writableDiskPresent;
  313. }
  314. bool AudioCDBurner::openTray()
  315. {
  316. return pimpl->openTray();
  317. }
  318. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  319. {
  320. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  321. DiskState oldState = getDiskState();
  322. DiskState newState = oldState;
  323. while (newState == oldState && Time::currentTimeMillis() < timeout)
  324. {
  325. newState = getDiskState();
  326. Thread::sleep (100);
  327. }
  328. return newState;
  329. }
  330. Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  331. {
  332. return pimpl->getAvailableWriteSpeeds();
  333. }
  334. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  335. {
  336. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  337. }
  338. int AudioCDBurner::getNumAvailableAudioBlocks() const
  339. {
  340. return pimpl->getNumAvailableAudioBlocks();
  341. }
  342. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  343. {
  344. if ([pimpl->device->device isValid])
  345. {
  346. pimpl->device->addSourceTrack (source, numSamps);
  347. return true;
  348. }
  349. return false;
  350. }
  351. String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  352. bool ejectDiscAfterwards,
  353. bool performFakeBurnForTesting,
  354. int writeSpeed)
  355. {
  356. if ([pimpl->device->device isValid])
  357. return pimpl->device->burn (listener, ejectDiscAfterwards, performFakeBurnForTesting, writeSpeed);
  358. return "Couldn't open or write to the CD device";
  359. }