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.

355 lines
12KB

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