The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

413 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. namespace CDBurnerHelpers
  21. {
  22. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  23. {
  24. CoInitialize (0);
  25. IDiscMaster* dm;
  26. IDiscRecorder* result = nullptr;
  27. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  28. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  29. IID_IDiscMaster,
  30. (void**) &dm)))
  31. {
  32. if (SUCCEEDED (dm->Open()))
  33. {
  34. IEnumDiscRecorders* drEnum = nullptr;
  35. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  36. {
  37. IDiscRecorder* dr = nullptr;
  38. DWORD dummy;
  39. int index = 0;
  40. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  41. {
  42. if (indexToOpen == index)
  43. {
  44. result = dr;
  45. break;
  46. }
  47. else if (list != nullptr)
  48. {
  49. BSTR path;
  50. if (SUCCEEDED (dr->GetPath (&path)))
  51. list->add ((const WCHAR*) path);
  52. }
  53. ++index;
  54. dr->Release();
  55. }
  56. drEnum->Release();
  57. }
  58. if (master == 0)
  59. dm->Close();
  60. }
  61. if (master != nullptr)
  62. *master = dm;
  63. else
  64. dm->Release();
  65. }
  66. return result;
  67. }
  68. }
  69. //==============================================================================
  70. class AudioCDBurner::Pimpl : public ComBaseClassHelper<IDiscMasterProgressEvents>,
  71. public Timer
  72. {
  73. public:
  74. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  75. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  76. listener (0), progress (0), shouldCancel (false)
  77. {
  78. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  79. jassert (SUCCEEDED (hr));
  80. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  81. //jassert (SUCCEEDED (hr));
  82. lastState = getDiskState();
  83. startTimer (2000);
  84. }
  85. void releaseObjects()
  86. {
  87. discRecorder->Close();
  88. if (redbook != nullptr)
  89. redbook->Release();
  90. discRecorder->Release();
  91. discMaster->Release();
  92. Release();
  93. }
  94. JUCE_COMRESULT QueryCancel (boolean* pbCancel) override
  95. {
  96. if (listener != nullptr && ! shouldCancel)
  97. shouldCancel = listener->audioCDBurnProgress (progress);
  98. *pbCancel = shouldCancel;
  99. return S_OK;
  100. }
  101. JUCE_COMRESULT NotifyBlockProgress (long nCompleted, long nTotal) override
  102. {
  103. progress = nCompleted / (float) nTotal;
  104. shouldCancel = listener != nullptr && listener->audioCDBurnProgress (progress);
  105. return E_NOTIMPL;
  106. }
  107. JUCE_COMRESULT NotifyPnPActivity (void) override { return E_NOTIMPL; }
  108. JUCE_COMRESULT NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) override { return E_NOTIMPL; }
  109. JUCE_COMRESULT NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) override { return E_NOTIMPL; }
  110. JUCE_COMRESULT NotifyPreparingBurn (long /*nEstimatedSeconds*/) override { return E_NOTIMPL; }
  111. JUCE_COMRESULT NotifyClosingDisc (long /*nEstimatedSeconds*/) override { return E_NOTIMPL; }
  112. JUCE_COMRESULT NotifyBurnComplete (HRESULT /*status*/) override { return E_NOTIMPL; }
  113. JUCE_COMRESULT NotifyEraseComplete (HRESULT /*status*/) override { return E_NOTIMPL; }
  114. class ScopedDiscOpener
  115. {
  116. public:
  117. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  118. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  119. private:
  120. Pimpl& pimpl;
  121. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener)
  122. };
  123. DiskState getDiskState()
  124. {
  125. const ScopedDiscOpener opener (*this);
  126. long type, flags;
  127. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  128. if (FAILED (hr))
  129. return unknown;
  130. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  131. return writableDiskPresent;
  132. if (type == 0)
  133. return noDisc;
  134. return readOnlyDiskPresent;
  135. }
  136. int getIntProperty (const wchar_t* name, const int defaultReturn) const
  137. {
  138. std::wstring copy { name };
  139. ComSmartPtr<IPropertyStorage> prop;
  140. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  141. return defaultReturn;
  142. PROPSPEC iPropSpec;
  143. iPropSpec.ulKind = PRSPEC_LPWSTR;
  144. iPropSpec.lpwstr = copy.data();
  145. PROPVARIANT iPropVariant;
  146. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  147. ? defaultReturn : (int) iPropVariant.lVal;
  148. }
  149. bool setIntProperty (const wchar_t* name, const int value) const
  150. {
  151. std::wstring copy { name };
  152. ComSmartPtr<IPropertyStorage> prop;
  153. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  154. return false;
  155. PROPSPEC iPropSpec;
  156. iPropSpec.ulKind = PRSPEC_LPWSTR;
  157. iPropSpec.lpwstr = copy.data();
  158. PROPVARIANT iPropVariant;
  159. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  160. return false;
  161. iPropVariant.lVal = (long) value;
  162. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  163. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  164. }
  165. void timerCallback() override
  166. {
  167. const DiskState state = getDiskState();
  168. if (state != lastState)
  169. {
  170. lastState = state;
  171. owner.sendChangeMessage();
  172. }
  173. }
  174. AudioCDBurner& owner;
  175. DiskState lastState;
  176. IDiscMaster* discMaster;
  177. IDiscRecorder* discRecorder;
  178. IRedbookDiscMaster* redbook;
  179. AudioCDBurner::BurnProgressListener* listener;
  180. float progress;
  181. bool shouldCancel;
  182. };
  183. //==============================================================================
  184. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  185. {
  186. IDiscMaster* discMaster = nullptr;
  187. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  188. if (discRecorder != nullptr)
  189. pimpl.reset (new Pimpl (*this, discMaster, discRecorder));
  190. }
  191. AudioCDBurner::~AudioCDBurner()
  192. {
  193. if (pimpl != nullptr)
  194. pimpl.release()->releaseObjects();
  195. }
  196. StringArray AudioCDBurner::findAvailableDevices()
  197. {
  198. StringArray devs;
  199. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  200. return devs;
  201. }
  202. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  203. {
  204. std::unique_ptr<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  205. if (b->pimpl == 0)
  206. b = nullptr;
  207. return b.release();
  208. }
  209. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210. {
  211. return pimpl->getDiskState();
  212. }
  213. bool AudioCDBurner::isDiskPresent() const
  214. {
  215. return getDiskState() == writableDiskPresent;
  216. }
  217. bool AudioCDBurner::openTray()
  218. {
  219. const Pimpl::ScopedDiscOpener opener (*pimpl);
  220. return SUCCEEDED (pimpl->discRecorder->Eject());
  221. }
  222. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  223. {
  224. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  225. DiskState oldState = getDiskState();
  226. DiskState newState = oldState;
  227. while (newState == oldState && Time::currentTimeMillis() < timeout)
  228. {
  229. newState = getDiskState();
  230. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  231. }
  232. return newState;
  233. }
  234. Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  235. {
  236. Array<int> results;
  237. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  238. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  239. for (int i = 0; i < numElementsInArray (speeds); ++i)
  240. if (speeds[i] <= maxSpeed)
  241. results.add (speeds[i]);
  242. results.addIfNotAlreadyThere (maxSpeed);
  243. return results;
  244. }
  245. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  246. {
  247. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  248. return false;
  249. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  250. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  251. }
  252. int AudioCDBurner::getNumAvailableAudioBlocks() const
  253. {
  254. long blocksFree = 0;
  255. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  256. return blocksFree;
  257. }
  258. String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  259. bool performFakeBurnForTesting, int writeSpeed)
  260. {
  261. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  262. pimpl->listener = listener;
  263. pimpl->progress = 0;
  264. pimpl->shouldCancel = false;
  265. UINT_PTR cookie;
  266. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl.get(), &cookie);
  267. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  268. ejectDiscAfterwards);
  269. String error;
  270. if (hr != S_OK)
  271. {
  272. const char* e = "Couldn't open or write to the CD device";
  273. if (hr == IMAPI_E_USERABORT)
  274. e = "User cancelled the write operation";
  275. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  276. e = "No Disk present";
  277. error = e;
  278. }
  279. pimpl->discMaster->ProgressUnadvise (cookie);
  280. pimpl->listener = 0;
  281. return error;
  282. }
  283. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  284. {
  285. if (audioSource == 0)
  286. return false;
  287. std::unique_ptr<AudioSource> source (audioSource);
  288. long bytesPerBlock;
  289. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  290. const int samplesPerBlock = bytesPerBlock / 4;
  291. bool ok = true;
  292. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  293. HeapBlock<byte> buffer (bytesPerBlock);
  294. AudioBuffer<float> sourceBuffer (2, samplesPerBlock);
  295. int samplesDone = 0;
  296. source->prepareToPlay (samplesPerBlock, 44100.0);
  297. while (ok)
  298. {
  299. {
  300. AudioSourceChannelInfo info (&sourceBuffer, 0, samplesPerBlock);
  301. sourceBuffer.clear();
  302. source->getNextAudioBlock (info);
  303. }
  304. buffer.clear (bytesPerBlock);
  305. AudioData::interleaveSamples (AudioData::NonInterleavedSource<AudioData::Float32, AudioData::NativeEndian> { sourceBuffer.getArrayOfReadPointers(), 2 },
  306. AudioData::InterleavedDest<AudioData::Int16, AudioData::LittleEndian> { reinterpret_cast<uint16*> (buffer.get()), 2 },
  307. samplesPerBlock);
  308. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  309. if (FAILED (hr))
  310. ok = false;
  311. samplesDone += samplesPerBlock;
  312. if (samplesDone >= numSamples)
  313. break;
  314. }
  315. hr = pimpl->redbook->CloseAudioTrack();
  316. return ok && hr == S_OK;
  317. }
  318. } // namespace juce