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.

369 lines
13KB

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