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.

371 lines
13KB

  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. wmSyncReader->Close();
  126. }
  127. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  128. int64 startSampleInFile, int numSamples)
  129. {
  130. if (sampleRate <= 0)
  131. return false;
  132. checkCoInitialiseCalled();
  133. if (startSampleInFile != currentPosition)
  134. {
  135. currentPosition = startSampleInFile;
  136. wmSyncReader->SetRange (((QWORD) startSampleInFile * 10000000) / (int) sampleRate, 0);
  137. bufferStart = bufferEnd = 0;
  138. }
  139. const int stride = numChannels * sizeof (int16);
  140. bool firstLoop = true;
  141. while (numSamples > 0)
  142. {
  143. if (bufferEnd <= bufferStart)
  144. {
  145. ComSmartPtr<INSSBuffer> sampleBuffer;
  146. QWORD sampleTime, duration;
  147. DWORD flags, outputNum;
  148. WORD streamNum;
  149. int64 readBufferStart;
  150. HRESULT hr = wmSyncReader->GetNextSample (1, sampleBuffer.resetAndGetPointerAddress(), &sampleTime,
  151. &duration, &flags, &outputNum, &streamNum);
  152. readBufferStart = (int64)floor((sampleTime * sampleRate) * 0.0000001);
  153. if (sampleBuffer != nullptr)
  154. {
  155. BYTE* rawData = nullptr;
  156. DWORD dataLength = 0;
  157. hr = sampleBuffer->GetBufferAndLength (&rawData, &dataLength);
  158. bufferStart = 0;
  159. bufferEnd = (int) dataLength;
  160. if (bufferEnd <= 0)
  161. {
  162. sampleBuffer->Release();
  163. return false;
  164. }
  165. buffer.ensureSize (bufferEnd);
  166. memcpy (buffer.getData(), rawData, bufferEnd);
  167. if (firstLoop && readBufferStart < startSampleInFile)
  168. {
  169. bufferStart += stride * (int) (startSampleInFile - readBufferStart);
  170. if (bufferStart > bufferEnd)
  171. bufferStart = bufferEnd;
  172. }
  173. }
  174. else
  175. {
  176. bufferStart = 0;
  177. bufferEnd = 512;
  178. buffer.ensureSize (bufferEnd);
  179. buffer.fillWith (0);
  180. }
  181. firstLoop = false;
  182. }
  183. const int16* const rawData = static_cast <const int16*> (addBytesToPointer (buffer.getData(), bufferStart));
  184. const int numToDo = jmin (numSamples, (bufferEnd - bufferStart) / stride);
  185. for (int i = 0; i < numDestChannels; ++i)
  186. {
  187. jassert (destSamples[i] != nullptr);
  188. const int srcChan = jmin (i, (int) numChannels - 1);
  189. const int16* src = rawData + srcChan;
  190. int* const dst = destSamples[i] + startOffsetInDestBuffer;
  191. for (int j = 0; j < numToDo; ++j)
  192. {
  193. dst[j] = ((uint32) *src) << 16;
  194. src += numChannels;
  195. }
  196. }
  197. bufferStart += numToDo * stride;
  198. if (bufferEnd - bufferStart < stride)
  199. bufferStart = bufferEnd;
  200. startOffsetInDestBuffer += numToDo;
  201. numSamples -= numToDo;
  202. currentPosition += numToDo;
  203. }
  204. return true;
  205. }
  206. private:
  207. DynamicLibrary wmvCoreLib;
  208. ComSmartPtr<IWMSyncReader> wmSyncReader;
  209. int64 currentPosition;
  210. MemoryBlock buffer;
  211. int bufferStart, bufferEnd;
  212. void checkCoInitialiseCalled()
  213. {
  214. CoInitialize (0);
  215. }
  216. void scanFileForDetails()
  217. {
  218. ComSmartPtr<IWMHeaderInfo> wmHeaderInfo;
  219. HRESULT hr = wmSyncReader.QueryInterface (wmHeaderInfo);
  220. if (SUCCEEDED (hr))
  221. {
  222. QWORD lengthInNanoseconds = 0;
  223. WORD lengthOfLength = sizeof (lengthInNanoseconds);
  224. WORD streamNum = 0;
  225. WMT_ATTR_DATATYPE wmAttrDataType;
  226. hr = wmHeaderInfo->GetAttributeByName (&streamNum, L"Duration", &wmAttrDataType,
  227. (BYTE*) &lengthInNanoseconds, &lengthOfLength);
  228. ComSmartPtr<IWMProfile> wmProfile;
  229. hr = wmSyncReader.QueryInterface (wmProfile);
  230. if (SUCCEEDED (hr))
  231. {
  232. ComSmartPtr<IWMStreamConfig> wmStreamConfig;
  233. hr = wmProfile->GetStream (0, wmStreamConfig.resetAndGetPointerAddress());
  234. if (SUCCEEDED (hr))
  235. {
  236. ComSmartPtr<IWMMediaProps> wmMediaProperties;
  237. hr = wmStreamConfig.QueryInterface (wmMediaProperties);
  238. if (SUCCEEDED (hr))
  239. {
  240. DWORD sizeMediaType;
  241. hr = wmMediaProperties->GetMediaType (0, &sizeMediaType);
  242. HeapBlock<WM_MEDIA_TYPE> mediaType;
  243. mediaType.malloc (sizeMediaType, 1);
  244. hr = wmMediaProperties->GetMediaType (mediaType, &sizeMediaType);
  245. if (mediaType->majortype == WMMEDIATYPE_Audio)
  246. {
  247. const WAVEFORMATEX* const inputFormat = reinterpret_cast<WAVEFORMATEX*> (mediaType->pbFormat);
  248. sampleRate = inputFormat->nSamplesPerSec;
  249. numChannels = inputFormat->nChannels;
  250. bitsPerSample = inputFormat->wBitsPerSample;
  251. lengthInSamples = (lengthInNanoseconds * (int) sampleRate) / 10000000;
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WMAudioReader);
  259. };
  260. }
  261. //==============================================================================
  262. WindowsMediaAudioFormat::WindowsMediaAudioFormat()
  263. : AudioFormat (TRANS (WindowsMediaCodec::wmFormatName),
  264. StringArray (WindowsMediaCodec::extensions))
  265. {
  266. }
  267. WindowsMediaAudioFormat::~WindowsMediaAudioFormat() {}
  268. Array<int> WindowsMediaAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  269. Array<int> WindowsMediaAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  270. bool WindowsMediaAudioFormat::canDoStereo() { return true; }
  271. bool WindowsMediaAudioFormat::canDoMono() { return true; }
  272. //==============================================================================
  273. AudioFormatReader* WindowsMediaAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails)
  274. {
  275. ScopedPointer<WindowsMediaCodec::WMAudioReader> r (new WindowsMediaCodec::WMAudioReader (sourceStream));
  276. if (r->sampleRate > 0)
  277. return r.release();
  278. if (! deleteStreamIfOpeningFails)
  279. r->input = nullptr;
  280. return nullptr;
  281. }
  282. AudioFormatWriter* WindowsMediaAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/, double /*sampleRateToUse*/,
  283. unsigned int /*numberOfChannels*/, int /*bitsPerSample*/,
  284. const StringPairArray& /*metadataValues*/, int /*qualityOptionIndex*/)
  285. {
  286. jassertfalse; // not yet implemented!
  287. return nullptr;
  288. }