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.

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