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.

354 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. namespace WindowsMediaCodec
  16. {
  17. class JuceIStream : public ComBaseClassHelper<IStream>
  18. {
  19. public:
  20. JuceIStream (InputStream& in) noexcept
  21. : ComBaseClassHelper<IStream> (0), source (in)
  22. {
  23. }
  24. JUCE_COMRESULT Commit (DWORD) { return S_OK; }
  25. JUCE_COMRESULT Write (const void*, ULONG, ULONG*) { return E_NOTIMPL; }
  26. JUCE_COMRESULT Clone (IStream**) { return E_NOTIMPL; }
  27. JUCE_COMRESULT SetSize (ULARGE_INTEGER) { return E_NOTIMPL; }
  28. JUCE_COMRESULT Revert() { return E_NOTIMPL; }
  29. JUCE_COMRESULT LockRegion (ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; }
  30. JUCE_COMRESULT UnlockRegion (ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; }
  31. JUCE_COMRESULT Read (void* dest, ULONG numBytes, ULONG* bytesRead)
  32. {
  33. auto numRead = source.read (dest, (size_t) numBytes);
  34. if (bytesRead != nullptr)
  35. *bytesRead = (ULONG) numRead;
  36. return (numRead == (int) numBytes) ? S_OK : S_FALSE;
  37. }
  38. JUCE_COMRESULT Seek (LARGE_INTEGER position, DWORD origin, ULARGE_INTEGER* resultPosition)
  39. {
  40. auto newPos = (int64) position.QuadPart;
  41. if (origin == STREAM_SEEK_CUR)
  42. {
  43. newPos += source.getPosition();
  44. }
  45. else if (origin == STREAM_SEEK_END)
  46. {
  47. auto len = source.getTotalLength();
  48. if (len < 0)
  49. return E_NOTIMPL;
  50. newPos += len;
  51. }
  52. if (resultPosition != nullptr)
  53. resultPosition->QuadPart = newPos;
  54. return source.setPosition (newPos) ? S_OK : E_NOTIMPL;
  55. }
  56. JUCE_COMRESULT CopyTo (IStream* destStream, ULARGE_INTEGER numBytesToDo,
  57. ULARGE_INTEGER* bytesRead, ULARGE_INTEGER* bytesWritten)
  58. {
  59. uint64 totalCopied = 0;
  60. int64 numBytes = numBytesToDo.QuadPart;
  61. while (numBytes > 0 && ! source.isExhausted())
  62. {
  63. char buffer [1024];
  64. auto numToCopy = (int) jmin ((int64) sizeof (buffer), (int64) numBytes);
  65. auto numRead = source.read (buffer, numToCopy);
  66. if (numRead <= 0)
  67. break;
  68. destStream->Write (buffer, numRead, nullptr);
  69. totalCopied += numRead;
  70. }
  71. if (bytesRead != nullptr) bytesRead->QuadPart = totalCopied;
  72. if (bytesWritten != nullptr) bytesWritten->QuadPart = totalCopied;
  73. return S_OK;
  74. }
  75. JUCE_COMRESULT Stat (STATSTG* stat, DWORD)
  76. {
  77. if (stat == nullptr)
  78. return STG_E_INVALIDPOINTER;
  79. zerostruct (*stat);
  80. stat->type = STGTY_STREAM;
  81. stat->cbSize.QuadPart = jmax ((int64) 0, source.getTotalLength());
  82. return S_OK;
  83. }
  84. private:
  85. InputStream& source;
  86. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceIStream)
  87. };
  88. //==============================================================================
  89. static const char* wmFormatName = "Windows Media";
  90. static const char* const extensions[] = { ".mp3", ".wmv", ".asf", ".wm", ".wma", 0 };
  91. //==============================================================================
  92. class WMAudioReader : public AudioFormatReader
  93. {
  94. public:
  95. WMAudioReader (InputStream* const input_)
  96. : AudioFormatReader (input_, TRANS (wmFormatName)),
  97. wmvCoreLib ("Wmvcore.dll")
  98. {
  99. JUCE_LOAD_WINAPI_FUNCTION (wmvCoreLib, WMCreateSyncReader, wmCreateSyncReader,
  100. HRESULT, (IUnknown*, DWORD, IWMSyncReader**))
  101. if (wmCreateSyncReader != nullptr)
  102. {
  103. checkCoInitialiseCalled();
  104. HRESULT hr = wmCreateSyncReader (nullptr, WMT_RIGHT_PLAYBACK, wmSyncReader.resetAndGetPointerAddress());
  105. if (SUCCEEDED (hr))
  106. hr = wmSyncReader->OpenStream (new JuceIStream (*input));
  107. if (SUCCEEDED (hr))
  108. {
  109. WORD streamNum = 1;
  110. hr = wmSyncReader->GetStreamNumberForOutput (0, &streamNum);
  111. hr = wmSyncReader->SetReadStreamSamples (streamNum, false);
  112. scanFileForDetails();
  113. }
  114. }
  115. }
  116. ~WMAudioReader()
  117. {
  118. if (wmSyncReader != nullptr)
  119. wmSyncReader->Close();
  120. }
  121. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  122. int64 startSampleInFile, int numSamples) override
  123. {
  124. if (sampleRate <= 0)
  125. return false;
  126. checkCoInitialiseCalled();
  127. clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
  128. startSampleInFile, numSamples, lengthInSamples);
  129. const int stride = numChannels * sizeof (int16);
  130. while (numSamples > 0)
  131. {
  132. if (! bufferedRange.contains (startSampleInFile))
  133. {
  134. const bool hasJumped = (startSampleInFile != bufferedRange.getEnd());
  135. if (hasJumped)
  136. wmSyncReader->SetRange ((QWORD) (startSampleInFile * 10000000 / (int64) sampleRate), 0);
  137. ComSmartPtr<INSSBuffer> sampleBuffer;
  138. QWORD sampleTime, duration;
  139. DWORD flags, outputNum;
  140. WORD streamNum;
  141. HRESULT hr = wmSyncReader->GetNextSample (1, sampleBuffer.resetAndGetPointerAddress(),
  142. &sampleTime, &duration, &flags, &outputNum, &streamNum);
  143. if (sampleBuffer != nullptr)
  144. {
  145. BYTE* rawData = nullptr;
  146. DWORD dataLength = 0;
  147. hr = sampleBuffer->GetBufferAndLength (&rawData, &dataLength);
  148. if (dataLength == 0)
  149. return false;
  150. if (hasJumped)
  151. bufferedRange.setStart ((int64) ((sampleTime * (int64) sampleRate) / 10000000));
  152. else
  153. bufferedRange.setStart (bufferedRange.getEnd()); // (because the positions returned often aren't contiguous)
  154. bufferedRange.setLength ((int64) (dataLength / stride));
  155. buffer.ensureSize ((int) dataLength);
  156. memcpy (buffer.getData(), rawData, (size_t) dataLength);
  157. }
  158. else if (hr == NS_E_NO_MORE_SAMPLES)
  159. {
  160. bufferedRange.setStart (startSampleInFile);
  161. bufferedRange.setLength (256);
  162. buffer.ensureSize (256 * stride);
  163. buffer.fillWith (0);
  164. }
  165. else
  166. {
  167. return false;
  168. }
  169. }
  170. auto offsetInBuffer = (int) (startSampleInFile - bufferedRange.getStart());
  171. auto* rawData = static_cast<const int16*> (addBytesToPointer (buffer.getData(), offsetInBuffer * stride));
  172. auto numToDo = jmin (numSamples, (int) (bufferedRange.getLength() - offsetInBuffer));
  173. for (int i = 0; i < numDestChannels; ++i)
  174. {
  175. jassert (destSamples[i] != nullptr);
  176. auto srcChan = jmin (i, (int) numChannels - 1);
  177. const int16* src = rawData + srcChan;
  178. int* const dst = destSamples[i] + startOffsetInDestBuffer;
  179. for (int j = 0; j < numToDo; ++j)
  180. {
  181. dst[j] = ((uint32) *src) << 16;
  182. src += numChannels;
  183. }
  184. }
  185. startSampleInFile += numToDo;
  186. startOffsetInDestBuffer += numToDo;
  187. numSamples -= numToDo;
  188. }
  189. return true;
  190. }
  191. private:
  192. DynamicLibrary wmvCoreLib;
  193. ComSmartPtr<IWMSyncReader> wmSyncReader;
  194. MemoryBlock buffer;
  195. Range<int64> bufferedRange;
  196. void checkCoInitialiseCalled()
  197. {
  198. CoInitialize (0);
  199. }
  200. void scanFileForDetails()
  201. {
  202. ComSmartPtr<IWMHeaderInfo> wmHeaderInfo;
  203. HRESULT hr = wmSyncReader.QueryInterface (wmHeaderInfo);
  204. if (SUCCEEDED (hr))
  205. {
  206. QWORD lengthInNanoseconds = 0;
  207. WORD lengthOfLength = sizeof (lengthInNanoseconds);
  208. WORD streamNum = 0;
  209. WMT_ATTR_DATATYPE wmAttrDataType;
  210. hr = wmHeaderInfo->GetAttributeByName (&streamNum, L"Duration", &wmAttrDataType,
  211. (BYTE*) &lengthInNanoseconds, &lengthOfLength);
  212. ComSmartPtr<IWMProfile> wmProfile;
  213. hr = wmSyncReader.QueryInterface (wmProfile);
  214. if (SUCCEEDED (hr))
  215. {
  216. ComSmartPtr<IWMStreamConfig> wmStreamConfig;
  217. hr = wmProfile->GetStream (0, wmStreamConfig.resetAndGetPointerAddress());
  218. if (SUCCEEDED (hr))
  219. {
  220. ComSmartPtr<IWMMediaProps> wmMediaProperties;
  221. hr = wmStreamConfig.QueryInterface (wmMediaProperties);
  222. if (SUCCEEDED (hr))
  223. {
  224. DWORD sizeMediaType;
  225. hr = wmMediaProperties->GetMediaType (0, &sizeMediaType);
  226. HeapBlock<WM_MEDIA_TYPE> mediaType;
  227. mediaType.malloc (sizeMediaType, 1);
  228. hr = wmMediaProperties->GetMediaType (mediaType, &sizeMediaType);
  229. if (mediaType->majortype == WMMEDIATYPE_Audio)
  230. {
  231. auto* inputFormat = reinterpret_cast<WAVEFORMATEX*> (mediaType->pbFormat);
  232. sampleRate = inputFormat->nSamplesPerSec;
  233. numChannels = inputFormat->nChannels;
  234. bitsPerSample = inputFormat->wBitsPerSample != 0 ? inputFormat->wBitsPerSample : 16;
  235. lengthInSamples = (lengthInNanoseconds * (int) sampleRate) / 10000000;
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WMAudioReader)
  243. };
  244. }
  245. //==============================================================================
  246. WindowsMediaAudioFormat::WindowsMediaAudioFormat()
  247. : AudioFormat (TRANS (WindowsMediaCodec::wmFormatName),
  248. StringArray (WindowsMediaCodec::extensions))
  249. {
  250. }
  251. WindowsMediaAudioFormat::~WindowsMediaAudioFormat() {}
  252. Array<int> WindowsMediaAudioFormat::getPossibleSampleRates() { return {}; }
  253. Array<int> WindowsMediaAudioFormat::getPossibleBitDepths() { return {}; }
  254. bool WindowsMediaAudioFormat::canDoStereo() { return true; }
  255. bool WindowsMediaAudioFormat::canDoMono() { return true; }
  256. bool WindowsMediaAudioFormat::isCompressed() { return true; }
  257. //==============================================================================
  258. AudioFormatReader* WindowsMediaAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails)
  259. {
  260. std::unique_ptr<WindowsMediaCodec::WMAudioReader> r (new WindowsMediaCodec::WMAudioReader (sourceStream));
  261. if (r->sampleRate > 0)
  262. return r.release();
  263. if (! deleteStreamIfOpeningFails)
  264. r->input = nullptr;
  265. return nullptr;
  266. }
  267. AudioFormatWriter* WindowsMediaAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/, double /*sampleRateToUse*/,
  268. unsigned int /*numberOfChannels*/, int /*bitsPerSample*/,
  269. const StringPairArray& /*metadataValues*/, int /*qualityOptionIndex*/)
  270. {
  271. jassertfalse; // not yet implemented!
  272. return nullptr;
  273. }
  274. } // namespace juce