Debian Codegraph @

components/decoder/wma/wma.cpp

raw symbols SCIP
1 /* BoCA - BonkEnc Component Architecture
2 * Copyright (C) 2007-2025 Robert Kausch <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation, either version 2 of
7 * the License, or (at your option) any later version.
8 *
9 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
10 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
11 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
12
13 #include <smooth.h>
14 #include <smooth/dll.h>
15
16 #include <dsound.h>
17
18 #include "wmsdk/asferr.h"
19
20 #include "wma.h"
21
22 using namespace smooth::IO;
23
24 const String &BoCA::DecoderWMA::GetComponentSpecs()
25 {
26 static String componentSpecs;
27
28 if (wmvcoredll != NIL)
29 {
30 componentSpecs = " \
31 \
32 <?xml version=\"1.0\" encoding=\"UTF-8\"?> \
33 <component> \
34 <name>Windows Media Audio Decoder</name> \
35 <version>1.0</version> \
36 <id>wma-dec</id> \
37 <type>decoder</type> \
38 <format> \
39 <name>Windows Media Audio Files</name> \
40 <extension>wma</extension> \
41 <tag id=\"wma-tag\" mode=\"other\">WMA Metadata</tag> \
42 </format> \
43 </component> \
44 \
45 ";
46 }
47
48 return componentSpecs;
49 }
50
51 Void smooth::AttachDLL(Void *instance)
52 {
53 LoadWMVCoreDLL();
54
55 /* Register initialization and cleanup handlers.
56 */
57 if (wmvcoredll != NIL)
58 {
59 BoCA::Engine *engine = BoCA::Engine::Get();
60
61 engine->onInitialize.Connect(&BoCA::DecoderWMA::Initialize);
62 engine->onCleanup.Connect(&BoCA::DecoderWMA::Cleanup);
63 }
64 }
65
66 Void smooth::DetachDLL()
67 {
68 /* Unregister initialization and cleanup handlers.
69 */
70 if (wmvcoredll != NIL)
71 {
72 BoCA::Engine *engine = BoCA::Engine::Get();
73
74 engine->onInitialize.Disconnect(&BoCA::DecoderWMA::Initialize);
75 engine->onCleanup.Disconnect(&BoCA::DecoderWMA::Cleanup);
76 }
77
78 FreeWMVCoreDLL();
79 }
80
81 Void BoCA::DecoderWMA::Initialize()
82 {
83 /* Init the Microsoft COM library.
84 */
85 CoInitialize(NIL);
86 }
87
88 Void BoCA::DecoderWMA::Cleanup()
89 {
90 /* Uninit the Microsoft COM library.
91 */
92 CoUninitialize();
93 }
94
95 Bool BoCA::DecoderWMA::CanOpenStream(const String &streamURI)
96 {
97 InStream in(STREAM_FILE, streamURI, IS_READ);
98 UnsignedInt64 magic = in.InputNumber(8);
99
100 return (magic == 0x11CF668E75B22630);
101 }
102
103 Error BoCA::DecoderWMA::GetStreamInfo(const String &streamURI, Track &track)
104 {
105 /* Get file size.
106 */
107 InStream in(STREAM_FILE, streamURI, IS_READ);
108
109 track.fileSize = in.Size();
110
111 /* Create WMA reader object.
112 */
113 HRESULT hr = ex_WMCreateReader(NIL, WMT_RIGHT_PLAYBACK, &reader);
114
115 if (FAILED(hr)) return Error();
116
117 hr = reader->QueryInterface(IID_IWMReaderAdvanced2, (void **) &readerAdvanced);
118
119 if (FAILED(hr))
120 {
121 reader->Release();
122
123 return Error();
124 }
125
126 /* Initialize reader callback.
127 */
128 readerCallback = new WMAReader();
129
130 asyncEvent = readerCallback->GetAsyncEventHandle();
131
132 /* Open file.
133 */
134 hr = reader->Open(Directory::MakeExtendedPath(File(streamURI)), readerCallback, NIL);
135
136 /* Wait for the Open call to complete. The event is set in the
137 * OnStatus callback when the reader reports completion.
138 */
139 if (!FAILED(hr)) WaitForEvent(asyncEvent);
140
141 if (!errorState)
142 {
143 DWORD cOutputs = 0;
144 WAVEFORMATEX *pWfx = NIL;
145
146 /* Find out the output count
147 */
148 reader->GetOutputCount(&cOutputs);
149
150 /* Find the first audio output.
151 */
152 for (DWORD i = 0; i < cOutputs; i++)
153 {
154 /* Enable high definition output.
155 */
156 BOOL enableDiscreteOutput = TRUE;
157 DWORD speakerConfig = DSSPEAKER_DIRECTOUT;
158
159 readerAdvanced->SetOutputSetting(i, g_wszEnableDiscreteOutput, WMT_TYPE_BOOL, (BYTE *) &enableDiscreteOutput, sizeof(WMT_TYPE_BOOL));
160 readerAdvanced->SetOutputSetting(i, g_wszSpeakerConfig, WMT_TYPE_DWORD, (BYTE *) &speakerConfig, sizeof(WMT_TYPE_DWORD));
161
162 /* Set the first output format as it is
163 * the one with the highest quality.
164 */
165 IWMOutputMediaProps *pProps = NIL;
166
167 if (!FAILED(reader->GetOutputFormat(i, 0, &pProps)))
168 {
169 if (!FAILED(reader->SetOutputProps(i, pProps)))
170 {
171 /* Find out the space needed for pMediaType
172 */
173 ULONG cbType = 0;
174
175 if (!FAILED(pProps->GetMediaType(NIL, &cbType)))
176 {
177 WM_MEDIA_TYPE *pMediaType = (WM_MEDIA_TYPE *) new BYTE[cbType];
178
179 /* Get the value for MediaType
180 */
181 if (!FAILED(pProps->GetMediaType(pMediaType, &cbType)) && pMediaType->majortype == WMMEDIATYPE_Audio)
182 {
183 /* Store the wave format for this output
184 */
185 pWfx = (WAVEFORMATEX *) new BYTE[pMediaType->cbFormat];
186
187 CopyMemory(pWfx, pMediaType->pbFormat, pMediaType->cbFormat);
188 }
189
190 delete [] pMediaType;
191 }
192 }
193
194 pProps->Release();
195 }
196
197 if (pWfx != NIL) break;
198 }
199
200 if (pWfx != NIL)
201 {
202 Format format = track.GetFormat();
203
204 format.bits = pWfx->wBitsPerSample;
205 format.rate = pWfx->nSamplesPerSec;
206 format.channels = pWfx->nChannels;
207
208 track.SetFormat(format);
209
210 delete [] pWfx;
211 }
212
213 if (pWfx == NIL) { errorState = True; errorString = "Unknown file type"; }
214 }
215
216 if (!errorState)
217 {
218 IWMHeaderInfo2 *pHeaderInfo = NIL;
219 BYTE *pbValue = NIL;
220
221 hr = reader->QueryInterface(IID_IWMHeaderInfo2, (void **) &pHeaderInfo);
222
223 /* Get attribute "Duration".
224 */
225 if (!FAILED(hr)) hr = GetHeaderAttribute(pHeaderInfo, g_wszWMDuration, &pbValue);
226
227 if (!FAILED(hr) && pbValue != NIL && *(QWORD *) pbValue != 0)
228 {
229 /* Set approxLength, because WMA duration is not always 100% accurate.
230 */
231 Format format = track.GetFormat();
232
233 track.length = -1;
234 track.approxLength = *(QWORD *) pbValue / 1e7 * format.rate;
235
236 delete [] pbValue;
237 }
238
239 /* Get codec infos.
240 */
241 DWORD nCodecInfos;
242
243 if (!FAILED(hr)) hr = pHeaderInfo->GetCodecInfoCount(&nCodecInfos);
244
245 if (!FAILED(hr))
246 {
247 /* See if this is a lossless file.
248 */
249 for (UnsignedInt i = 0; i < nCodecInfos; i++)
250 {
251 WORD wNameSize = 0;
252 WORD wDescSize = 0;
253 WORD wCodecInfoSize = sizeof(WORD);
254 WORD wCodecInfo = 0;
255 WMT_CODEC_INFO_TYPE codecType = WMT_CODECINFO_UNKNOWN;
256
257 hr = pHeaderInfo->GetCodecInfo(i, &wNameSize, NIL, &wDescSize, NIL, &codecType, &wCodecInfoSize, (BYTE *) &wCodecInfo);
258
259 if (!FAILED(hr) && codecType == WMT_CODECINFO_AUDIO && wCodecInfoSize == sizeof(WORD))
260 {
261 if (wCodecInfo == WAVE_FORMAT_PCM ||
262 wCodecInfo == WAVE_FORMAT_IEEE_FLOAT ||
263 wCodecInfo == WAVE_FORMAT_WMAUDIO_LOSSLESS) track.lossless = True;
264 else track.lossless = False;
265
266 break;
267 }
268 }
269 }
270
271 pHeaderInfo->Release();
272 }
273
274 hr = reader->Close();
275
276 /* Wait for the reader to deliver a WMT_CLOSED event to the
277 * OnStatus callback.
278 */
279 if (!FAILED(hr)) WaitForEvent(asyncEvent);
280
281 readerAdvanced->Release();
282 reader->Release();
283 readerCallback->Release();
284
285 if (!errorState)
286 {
287 AS::Registry &boca = AS::Registry::Get();
288 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("wma-tag");
289
290 if (tagger != NIL)
291 {
292 tagger->SetConfiguration(GetConfiguration());
293 tagger->ParseStreamInfo(streamURI, track);
294
295 boca.DeleteComponent(tagger);
296 }
297 }
298
299 if (errorState) return Error();
300 else return Success();
301 }
302
303 BoCA::DecoderWMA::DecoderWMA()
304 {
305 reader = NIL;
306 readerAdvanced = NIL;
307
308 asyncEvent = NIL;
309
310 readerCallback = NIL;
311
312 userProvidedClock = True;
313 }
314
315 BoCA::DecoderWMA::~DecoderWMA()
316 {
317 }
318
319 Bool BoCA::DecoderWMA::Activate()
320 {
321 /* Create WMA reader object.
322 */
323 HRESULT hr = ex_WMCreateReader(NIL, WMT_RIGHT_PLAYBACK, &reader);
324
325 if (FAILED(hr)) return False;
326
327 hr = reader->QueryInterface(IID_IWMReaderAdvanced2, (void **) &readerAdvanced);
328
329 if (FAILED(hr))
330 {
331 reader->Release();
332
333 return False;
334 }
335
336 /* Initialize reader callback.
337 */
338 readerCallback = new WMAReader();
339 readerCallback->SetReaderAdvanced(readerAdvanced);
340 readerCallback->SetSamplesBuffer(&samplesBuffer, &samplesBufferMutex);
341
342 asyncEvent = readerCallback->GetAsyncEventHandle();
343
344 /* Open file.
345 */
346 hr = reader->Open(Directory::MakeExtendedPath(File(track.fileName)), readerCallback, NIL);
347
348 /* Wait for the Open call to complete. The event is set in the
349 * OnStatus callback when the reader reports completion.
350 */
351 if (!FAILED(hr)) WaitForEvent(asyncEvent);
352
353 readerAdvanced->SetUserProvidedClock(userProvidedClock);
354
355 DWORD cOutputs = 0;
356
357 /* Find out the output count
358 */
359 reader->GetOutputCount(&cOutputs);
360
361 /* Find the first audio output.
362 */
363 for (DWORD i = 0; i < cOutputs; i++)
364 {
365 /* Enable high definition output.
366 */
367 BOOL enableDiscreteOutput = TRUE;
368 DWORD speakerConfig = 0;
369
370 readerAdvanced->SetOutputSetting(i, g_wszEnableDiscreteOutput, WMT_TYPE_BOOL, (BYTE *) &enableDiscreteOutput, sizeof(WMT_TYPE_BOOL));
371 readerAdvanced->SetOutputSetting(i, g_wszSpeakerConfig, WMT_TYPE_DWORD, (BYTE *) &speakerConfig, sizeof(WMT_TYPE_DWORD));
372
373 /* Set the first output format as it is
374 * the one with the highest quality.
375 */
376 IWMOutputMediaProps *pProps = NIL;
377
378 if (!FAILED(reader->GetOutputFormat(i, 0, &pProps)))
379 {
380 if (!FAILED(reader->SetOutputProps(i, pProps)))
381 {
382 /* Find out the space needed for pMediaType
383 */
384 ULONG cbType = 0;
385
386 if (!FAILED(pProps->GetMediaType(NIL, &cbType)))
387 {
388 WM_MEDIA_TYPE *pMediaType = (WM_MEDIA_TYPE *) new BYTE[cbType];
389
390 /* Get the value for MediaType
391 */
392 if (!FAILED(pProps->GetMediaType(pMediaType, &cbType)) && pMediaType->majortype == WMMEDIATYPE_Audio)
393 {
394 readerCallback->SetAudioOutputNum(i);
395
396 hr = reader->Start(0, 0, 1.0, NIL);
397
398 /* Wait for the Start call to complete.
399 */
400 if (!FAILED(hr)) WaitForEvent(asyncEvent);
401 }
402
403 delete [] pMediaType;
404 }
405 }
406
407 pProps->Release();
408 }
409 }
410
411 /* Some streams do not work with a user provided clock.
412 * Detect this here and try without it in case of an error.
413 */
414 while (readerCallback->IsActive() && samplesBuffer.Size() <= 0) S::System::System::Sleep(1);
415
416 if (!readerCallback->IsActive() && samplesBuffer.Size() <= 0)
417 {
418 if (!userProvidedClock) return False;
419
420 Deactivate();
421
422 userProvidedClock = False;
423 errorState = False;
424
425 return Activate();
426 }
427
428 return True;
429 }
430
431 Bool BoCA::DecoderWMA::Deactivate()
432 {
433 readerCallback->SetActive(False);
434
435 HRESULT hr = reader->Stop();
436
437 /* Wait for the reader to stop.
438 */
439 if (!FAILED(hr)) WaitForEvent(asyncEvent);
440
441 hr = reader->Close();
442
443 /* Wait for the reader to deliver a WMT_CLOSED event to the
444 * OnStatus callback.
445 */
446 if (!FAILED(hr)) WaitForEvent(asyncEvent);
447
448 readerAdvanced->Release();
449 reader->Release();
450 readerCallback->Release();
451
452 return True;
453 }
454
455 Bool BoCA::DecoderWMA::Seek(Int64 samplePosition)
456 {
457 /* Stop reader before seeking.
458 */
459 readerCallback->SetActive(False);
460
461 HRESULT hr = reader->Stop();
462
463 /* Wait for the reader to stop.
464 */
465 if (!FAILED(hr)) WaitForEvent(asyncEvent);
466
467 /* Clear samples buffer.
468 */
469 samplesBuffer.Resize(0);
470
471 /* Restart reader at new position.
472 */
473 QWORD position = samplePosition * 1e7 / track.GetFormat().rate;
474
475 hr = reader->Start(position, 0, 1.0, &position);
476
477 /* Wait for the Start call to complete.
478 */
479 if (!FAILED(hr)) WaitForEvent(asyncEvent);
480
481 return True;
482 }
483
484 Int BoCA::DecoderWMA::ReadData(Buffer<UnsignedByte> &data)
485 {
486 if (!readerCallback->IsActive() && samplesBuffer.Size() <= 0) return -1;
487
488 while (readerCallback->IsActive() && samplesBuffer.Size() <= 0) S::System::System::Sleep(1);
489
490 /* Copy any data from the sample buffer.
491 */
492 samplesBufferMutex.Lock();
493
494 data.Resize(samplesBuffer.Size());
495
496 memcpy(data, samplesBuffer, samplesBuffer.Size());
497
498 samplesBuffer.Resize(0);
499
500 samplesBufferMutex.Release();
501
502 /* Update inBytes to indicate progress.
503 */
504 if (track.approxLength > 0) inBytes += track.fileSize * data.Size() / (track.approxLength * track.GetFormat().channels * (track.GetFormat().bits / 8));
505
506 return data.Size();
507 }
508
509 HRESULT BoCA::DecoderWMA::GetHeaderAttribute(IWMHeaderInfo *pHeaderInfo, LPCWSTR pwszName, BYTE **ppbValue)
510 {
511 WMT_ATTR_DATATYPE wmtType;
512 WORD wStreamNum = 0;
513 WORD cbLength = 0;
514
515 *ppbValue = NIL;
516
517 /* Get the number of bytes to be allocated for pbValue
518 */
519 HRESULT hr = pHeaderInfo->GetAttributeByName(&wStreamNum, pwszName, &wmtType, NIL, &cbLength);
520
521 /* No such an attribute, so return
522 */
523 if (hr == ASF_E_NOTFOUND) return S_OK;
524
525 if (FAILED(hr)) return hr;
526
527 /* Allocate space and get the actual value
528 */
529 *ppbValue = new BYTE[cbLength];
530
531 pHeaderInfo->GetAttributeByName(&wStreamNum, pwszName, &wmtType, *ppbValue, &cbLength);
532
533 return S_OK;
534 }
535
536 Void BoCA::DecoderWMA::WaitForEvent(HANDLE hEvent, DWORD msMaxWaitTime)
537 {
538 for (DWORD i = 0; i < msMaxWaitTime; i += 10)
539 {
540 MSG msg;
541
542 if (PeekMessage(&msg, (HWND) NIL, 0, 0, PM_REMOVE))
543 {
544 TranslateMessage(&msg);
545 DispatchMessage(&msg);
546 }
547
548 if (WaitForSingleObject(hEvent, 10) != WAIT_TIMEOUT) break;
549 }
550
551 if (readerCallback->IsError())
552 {
553 errorState = True;
554 errorString = readerCallback->GetErrorString();
555 }
556 }