Debian Codegraph @

runtime/application/external/win32/decodercomponentstdio.cpp

raw symbols SCIP
1 /* BoCA - BonkEnc Component Architecture
2 * Copyright (C) 2007-2024 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 <boca/application/external/decodercomponentstdio.h>
14 #include <boca/application/external/utilities.h>
15 #include <boca/application/taggercomponent.h>
16 #include <boca/application/registry.h>
17 #include <boca/common/utilities.h>
18
19 #include <smooth/io/drivers/driver_win32.h>
20
21 #include <windows.h>
22 #include <mmreg.h>
23
24 using namespace smooth::IO;
25
26 BoCA::AS::DecoderComponentExternalStdIO::DecoderComponentExternalStdIO(ComponentSpecs *specs) : DecoderComponentExternal(specs)
27 {
28 rPipe = NIL;
29 wPipe = NIL;
30
31 hProcess = NIL;
32
33 samplesRead = 0;
34 }
35
36 BoCA::AS::DecoderComponentExternalStdIO::~DecoderComponentExternalStdIO()
37 {
38 }
39
40 String BoCA::AS::DecoderComponentExternalStdIO::GetMD5(const String &encFileName)
41 {
42 return ExternalUtilities::GetMD5(specs, encFileName);
43 }
44
45 Float BoCA::AS::DecoderComponentExternalStdIO::GetApproximateDuration(const String &encFileName)
46 {
47 if (!specs->external_command.EndsWith("ffmpeg.exe") && !specs->external_command.EndsWith("avconv.exe")) return -1;
48
49 /* Set up security attributes.
50 */
51 SECURITY_ATTRIBUTES secAttr;
52
53 ZeroMemory(&secAttr, sizeof(secAttr));
54
55 secAttr.nLength = sizeof(secAttr);
56 secAttr.bInheritHandle = True;
57
58 HANDLE rPipe = NIL;
59 HANDLE wPipe = NIL;
60
61 CreatePipe(&rPipe, &wPipe, &secAttr, 131072);
62 SetHandleInformation(rPipe, HANDLE_FLAG_INHERIT, 0);
63
64 /* Start 3rd party command line decoder.
65 */
66 String command = String("\"").Append(specs->external_command).Append("\"").Replace("/", Directory::GetDirectoryDelimiter());
67 String arguments = String("-i \"").Append(encFileName).Append("\"");
68
69 STARTUPINFOA startupInfo;
70
71 ZeroMemory(&startupInfo, sizeof(startupInfo));
72
73 startupInfo.cb = sizeof(startupInfo);
74 startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
75 startupInfo.wShowWindow = SW_HIDE;
76 startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
77 startupInfo.hStdOutput = NIL;
78 startupInfo.hStdError = wPipe;
79
80 PROCESS_INFORMATION processInfo;
81
82 ZeroMemory(&processInfo, sizeof(processInfo));
83
84 CreateProcessA(NIL, String(command).Append(" ").Append(arguments), NIL, NIL, True, 0, NIL, NIL, &startupInfo, &processInfo);
85
86 /* Close stdio pipe write handle.
87 */
88 CloseHandle(wPipe);
89
90 /* Check process handle.
91 */
92 if (processInfo.hProcess == NIL)
93 {
94 CloseHandle(rPipe);
95
96 return -1;
97 }
98
99 /* Read output into buffer.
100 */
101 String output;
102 Buffer<char> buffer(4096);
103 DWORD bytesRead = 0;
104
105 while (True)
106 {
107 if (!ReadFile(rPipe, buffer, 4096, &bytesRead, NIL) || bytesRead == 0) break;
108
109 output.Append((char *) buffer);
110 }
111
112 CloseHandle(rPipe);
113
114 TerminateProcess(processInfo.hProcess, 0);
115
116 /* Wait until the decoder exits.
117 */
118 while (WaitForSingleObject(processInfo.hProcess, 0) == WAIT_TIMEOUT) S::System::System::Sleep(10);
119
120 /* Extract duration from output.
121 */
122 if (output.Find("Duration: ") >= 0)
123 {
124 String duration = output.SubString(output.Find("Duration: ") + 10, 11);
125 const Array<String> &parts = duration.Explode(":");
126
127 if (parts.Length() == 3) return parts.GetNth(0).ToInt() * 60 * 60 +
128 parts.GetNth(1).ToInt() * 60 +
129 parts.GetNth(2).ToFloat();
130 }
131
132 return -1;
133 }
134
135 Error BoCA::AS::DecoderComponentExternalStdIO::GetStreamInfo(const String &streamURI, Track &track)
136 {
137 /* Return cached track from previous call.
138 */
139 if (this->track.fileName == streamURI)
140 {
141 track = this->track;
142
143 return Success();
144 }
145
146 String encFileName = streamURI;
147
148 /* Copy the file and decode the temporary copy
149 * if the file name contains Unicode characters.
150 */
151 if (String::IsUnicode(streamURI))
152 {
153 encFileName = Utilities::GetNonUnicodeTempFileName(streamURI).Append(".").Append(specs->formats.GetFirst()->GetExtensions().GetFirst());
154
155 File(streamURI).Copy(encFileName);
156 }
157
158 /* Get approximate duration (FFmpeg decoder only).
159 */
160 Float approximateDuration = GetApproximateDuration(encFileName);
161
162 /* Set up security attributes.
163 */
164 SECURITY_ATTRIBUTES secAttr;
165
166 ZeroMemory(&secAttr, sizeof(secAttr));
167
168 secAttr.nLength = sizeof(secAttr);
169 secAttr.bInheritHandle = True;
170
171 HANDLE rPipe = NIL;
172 HANDLE wPipe = NIL;
173
174 CreatePipe(&rPipe, &wPipe, &secAttr, 131072);
175 SetHandleInformation(rPipe, HANDLE_FLAG_INHERIT, 0);
176
177 /* Start 3rd party command line decoder.
178 */
179 String command = String("\"").Append(specs->external_command).Append("\"").Replace("/", Directory::GetDirectoryDelimiter());
180 String arguments = String(specs->external_arguments).Replace("%OPTIONS", specs->GetExternalArgumentsString(GetConfiguration()))
181 .Replace("%INFILE", String("\"").Append(encFileName).Append("\""));
182
183 if (specs->debug) AllocConsole();
184
185 STARTUPINFOA startupInfo;
186
187 ZeroMemory(&startupInfo, sizeof(startupInfo));
188
189 startupInfo.cb = sizeof(startupInfo);
190 startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
191 startupInfo.wShowWindow = specs->debug ? SW_SHOW : SW_HIDE;
192 startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
193 startupInfo.hStdOutput = wPipe;
194 startupInfo.hStdError = specs->debug ? GetStdHandle(STD_ERROR_HANDLE) : NIL;
195
196 PROCESS_INFORMATION processInfo;
197
198 ZeroMemory(&processInfo, sizeof(processInfo));
199
200 CreateProcessA(NIL, String(command).Append(" ").Append(arguments), NIL, NIL, True, 0, NIL, NIL, &startupInfo, &processInfo);
201
202 /* Close stdio pipe write handle.
203 */
204 CloseHandle(wPipe);
205
206 /* Check process handle.
207 */
208 if (processInfo.hProcess == NIL)
209 {
210 CloseHandle(rPipe);
211
212 errorState = True;
213 errorString = String("Unable to run decoder ").Append(command).Append(".");
214
215 /* Remove temporary file if necessary.
216 */
217 if (String::IsUnicode(streamURI)) File(encFileName).Delete();
218
219 return Error();
220 }
221
222 /* Read WAVE header into buffer.
223 */
224 Buffer<UnsignedByte> buffer(4096);
225 Int64 bytesReadTotal = 0;
226 DWORD bytesRead = 0;
227
228 do
229 {
230 if (!ReadFile(rPipe, buffer + bytesReadTotal, 4096 - bytesReadTotal, &bytesRead, NIL) || bytesRead == 0) break;
231
232 bytesReadTotal += bytesRead;
233 }
234 while (bytesReadTotal < 4096);
235
236 if (bytesReadTotal >= 44)
237 {
238 InStream *in = new InStream(STREAM_BUFFER, buffer, bytesReadTotal);
239
240 /* Read decoded WAVE file header.
241 */
242 track.fileName = streamURI;
243 track.fileSize = File(streamURI).GetFileSize();
244
245 /* Read RIFF chunk.
246 */
247 if (in->InputString(4) != "RIFF") { errorState = True; errorString = "Unknown file type"; }
248
249 in->RelSeek(4);
250
251 if (in->InputString(4) != "WAVE") { errorState = True; errorString = "Unknown file type"; }
252
253 String chunk;
254
255 do
256 {
257 /* Read next chunk.
258 */
259 chunk = in->InputString(4);
260
261 UnsignedInt32 cSize = in->InputNumber(4);
262
263 if (chunk == "fmt ")
264 {
265 Int waveFormat = in->InputNumber(2);
266
267 if (waveFormat != WAVE_FORMAT_PCM &&
268 waveFormat != WAVE_FORMAT_IEEE_FLOAT &&
269 waveFormat != WAVE_FORMAT_EXTENSIBLE) { errorState = True; errorString = "Unsupported audio format"; }
270
271 Format format = track.GetFormat();
272
273 format.channels = (unsigned short) in->InputNumber(2);
274 format.rate = (unsigned long) in->InputNumber(4);
275
276 in->RelSeek(6);
277
278 format.fp = (waveFormat == WAVE_FORMAT_IEEE_FLOAT);
279 format.bits = (unsigned short) in->InputNumber(2);
280 format.order = BYTE_INTEL;
281
282 if (format.bits == 8) format.sign = False;
283
284 track.SetFormat(format);
285
286 if (approximateDuration >= 0) track.approxLength = approximateDuration * format.rate;
287
288 /* Skip rest of chunk.
289 */
290 in->RelSeek(cSize - 16 + cSize % 2);
291 }
292 else if (chunk == "LIST")
293 {
294 /* Copy chunk to separate buffer.
295 */
296 Buffer<UnsignedByte> info(8 + cSize + cSize % 2);
297
298 in->RelSeek(-8);
299 in->InputData(info, info.Size());
300
301 /* Parse LIST INFO chunk.
302 */
303 AS::Registry &boca = AS::Registry::Get();
304 AS::TaggerComponent *riffTagger = (AS::TaggerComponent *) boca.CreateComponentByID("riff-tag");
305
306 if (riffTagger != NIL)
307 {
308 riffTagger->SetConfiguration(GetConfiguration());
309 riffTagger->ParseBuffer(info, track);
310
311 boca.DeleteComponent(riffTagger);
312 }
313 }
314 else if (chunk == "data")
315 {
316 if (cSize == 0xffffffff || cSize == 0) track.length = -1;
317 else track.length = cSize / track.GetFormat().channels / (track.GetFormat().bits / 8);
318
319 /* Read the rest of the file to find actual size.
320 */
321 if (track.length == -1 && track.approxLength == -1)
322 {
323 Buffer<UnsignedByte> data(12288);
324
325 while (True)
326 {
327 Int size = 0;
328
329 if (!ReadFile(rPipe, data, data.Size(), (DWORD *) &size, NIL) || size == 0) break;
330
331 bytesReadTotal += size;
332 }
333
334 track.length = (bytesReadTotal - in->GetPos()) / track.GetFormat().channels / (track.GetFormat().bits / 8);
335 }
336 }
337 else
338 {
339 /* Skip chunk.
340 */
341 in->RelSeek(cSize + cSize % 2);
342 }
343 }
344 while (!errorState && chunk != "data");
345
346 /* Close stdio pipe.
347 */
348 delete in;
349 }
350
351 CloseHandle(rPipe);
352
353 TerminateProcess(processInfo.hProcess, 0);
354
355 /* Wait until the decoder exits.
356 */
357 while (WaitForSingleObject(processInfo.hProcess, 0) == WAIT_TIMEOUT) S::System::System::Sleep(10);
358
359 if (specs->debug)
360 {
361 BoCA::Utilities::InfoMessage("Click OK to close console window.");
362
363 FreeConsole();
364 }
365
366 /* Query MD5.
367 */
368 track.md5 = GetMD5(encFileName);
369
370 /* Remove temporary copy if necessary.
371 */
372 if (String::IsUnicode(streamURI)) File(encFileName).Delete();
373
374 /* Check if anything went wrong.
375 */
376 unsigned long exitCode = 0;
377
378 GetExitCodeProcess(processInfo.hProcess, &exitCode);
379
380 if (track.length == -1 && track.approxLength == -1 && !specs->external_ignoreExitCode && exitCode != 0)
381 {
382 errorState = True;
383 errorString = String("Decoder returned exit code ").Append(String::FromInt((signed) exitCode)).Append(".");
384 }
385
386 if (errorState) return Error();
387
388 /* Query tags and update track.
389 */
390 QueryTags(streamURI, track);
391
392 return Success();
393 }
394
395 Bool BoCA::AS::DecoderComponentExternalStdIO::Activate()
396 {
397 encFileName = track.fileName;
398
399 /* Copy the file and decode the temporary copy
400 * if the file name contains Unicode characters.
401 */
402 if (String::IsUnicode(track.fileName))
403 {
404 encFileName = Utilities::GetNonUnicodeTempFileName(track.fileName).Append(".").Append(specs->formats.GetFirst()->GetExtensions().GetFirst());
405
406 File(track.fileName).Copy(encFileName);
407
408 /* Look for a companion file.
409 */
410 File companionFile = GetCompanionFile(track.fileName);
411
412 if (companionFile.Exists()) companionFile.Copy(GetCompanionFile(encFileName));
413 }
414
415 const Format &format = track.GetFormat();
416
417 /* Set up security attributes.
418 */
419 SECURITY_ATTRIBUTES secAttr;
420
421 ZeroMemory(&secAttr, sizeof(secAttr));
422
423 secAttr.nLength = sizeof(secAttr);
424 secAttr.bInheritHandle = True;
425
426 CreatePipe(&rPipe, &wPipe, &secAttr, 32768 * format.channels * (format.bits / 8));
427 SetHandleInformation(rPipe, HANDLE_FLAG_INHERIT, 0);
428
429 /* Start 3rd party command line decoder.
430 */
431 String command = String("\"").Append(specs->external_command).Append("\"").Replace("/", Directory::GetDirectoryDelimiter());
432 String arguments = String(specs->external_arguments).Replace("%OPTIONS", specs->GetExternalArgumentsString(GetConfiguration()))
433 .Replace("%INFILE", String("\"").Append(encFileName).Append("\""));
434
435 if (specs->debug) AllocConsole();
436
437 STARTUPINFOA startupInfo;
438
439 ZeroMemory(&startupInfo, sizeof(startupInfo));
440
441 startupInfo.cb = sizeof(startupInfo);
442 startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
443 startupInfo.wShowWindow = specs->debug ? SW_SHOW : SW_HIDE;
444 startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
445 startupInfo.hStdOutput = wPipe;
446 startupInfo.hStdError = specs->debug ? GetStdHandle(STD_ERROR_HANDLE) : NIL;
447
448 PROCESS_INFORMATION processInfo;
449
450 ZeroMemory(&processInfo, sizeof(processInfo));
451
452 CreateProcessA(NIL, String(command).Append(" ").Append(arguments), NIL, NIL, True, 0, NIL, NIL, &startupInfo, &processInfo);
453
454 hProcess = processInfo.hProcess;
455
456 /* Close stdio pipe write handle.
457 */
458 CloseHandle(wPipe);
459
460 /* Check process handle.
461 */
462 if (processInfo.hProcess == NIL)
463 {
464 CloseHandle(rPipe);
465
466 errorState = True;
467 errorString = String("Unable to run decoder ").Append(command).Append(".");
468
469 /* Remove temporary file if necessary.
470 */
471 if (String::IsUnicode(track.fileName)) File(encFileName).Delete();
472
473 return False;
474 }
475
476 /* Skip the WAVE header.
477 */
478 Buffer<UnsignedByte> buffer(8);
479 DWORD bytesRead = 0;
480 DWORD chunkSize = 0;
481
482 ReadFile(rPipe, buffer, 8, &bytesRead, NIL); // RIFF chunk
483 ReadFile(rPipe, buffer, 4, &bytesRead, NIL); // WAVE ID
484 ReadFile(rPipe, buffer, 4, &bytesRead, NIL); // fmt FOURCC
485 ReadFile(rPipe, buffer, 4, &bytesRead, NIL); // fmt chunk size
486
487 chunkSize = buffer[0] | buffer[1] << 8 | buffer[2] << 16 | buffer[3] << 24;
488
489 buffer.Resize(Math::Max(8, chunkSize));
490
491 ReadFile(rPipe, buffer, chunkSize, &bytesRead, NIL); // rest of fmt chunk
492
493 do
494 {
495 ReadFile(rPipe, buffer, 8, &bytesRead, NIL); // chunk header
496
497 if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't' && buffer[3] == 'a') break;
498
499 chunkSize = buffer[4] | buffer[5] << 8 | buffer[6] << 16 | buffer[7] << 24;
500
501 buffer.Resize(Math::Max(8, chunkSize));
502
503 ReadFile(rPipe, buffer, chunkSize, &bytesRead, NIL); // rest of chunk
504 }
505 while (True);
506
507 return True;
508 }
509
510 Bool BoCA::AS::DecoderComponentExternalStdIO::Deactivate()
511 {
512 /* Close stdio pipe read handle.
513 */
514 CloseHandle(rPipe);
515
516 TerminateProcess(hProcess, 0);
517
518 /* Wait until the decoder exits.
519 */
520 while (WaitForSingleObject(hProcess, 0) == WAIT_TIMEOUT) S::System::System::Sleep(10);
521
522 if (specs->debug)
523 {
524 BoCA::Utilities::InfoMessage("Click OK to close console window.");
525
526 FreeConsole();
527 }
528
529 /* Remove temporary copy if necessary.
530 */
531 if (String::IsUnicode(track.fileName))
532 {
533 File(encFileName).Delete();
534
535 /* Delete companion file too.
536 */
537 File companionFile = GetCompanionFile(encFileName);
538
539 if (companionFile.Exists()) companionFile.Delete();
540 }
541
542 /* Check if anything went wrong.
543 */
544 unsigned long exitCode = 0;
545
546 GetExitCodeProcess(hProcess, &exitCode);
547
548 if (!specs->external_ignoreExitCode && exitCode != 0)
549 {
550 errorState = True;
551 errorString = String("Decoder returned exit code ").Append(String::FromInt((signed) exitCode)).Append(".");
552
553 return False;
554 }
555
556 return True;
557 }
558
559 Bool BoCA::AS::DecoderComponentExternalStdIO::Seek(Int64 samplePosition)
560 {
561 const Format &format = track.GetFormat();
562 Buffer<UnsignedByte> buffer(12288);
563 Int64 bytesLeft = (samplePosition - samplesRead) * format.channels * (format.bits / 8) - preBuffer.Size();
564
565 while (bytesLeft > 0)
566 {
567 Int size = Math::Min(bytesLeft, (Int64) buffer.Size());
568
569 if (!ReadFile(rPipe, buffer, size, (DWORD *) &size, NIL) || size == 0)
570 {
571 errorState = True;
572 errorString = "Decoder quit prematurely.";
573
574 return False;
575 }
576
577 bytesLeft -= size;
578 }
579
580 samplesRead = samplePosition;
581
582 preBuffer.Resize(0);
583
584 return True;
585 }
586
587 Int BoCA::AS::DecoderComponentExternalStdIO::ReadData(Buffer<UnsignedByte> &data)
588 {
589 /* Hand data over from the input file.
590 */
591 Int preread = preBuffer.Size();
592 Int size = 12288 - preread;
593
594 data.Resize(preread + size);
595
596 memcpy(data, preBuffer, preread);
597
598 if (!ReadFile(rPipe, data + preread, size, (DWORD *) &size, NIL) || size == 0)
599 {
600 if (track.length != -1)
601 {
602 errorState = True;
603 errorString = "Decoder quit prematurely.";
604 }
605
606 return -1;
607 }
608
609 /* Make sure to read whole samples.
610 */
611 const Format &format = track.GetFormat();
612 Int overread = (preread + size) % (format.channels * (format.bits / 8));
613
614 preBuffer.Resize(overread);
615
616 memcpy(preBuffer, data + preread + size - overread, overread);
617
618 data.Resize(preread + size - overread);
619
620 /* Adjust byte order and calculate MD5.
621 */
622 ProcessData(data);
623
624 /* Increment number of samples read.
625 */
626 samplesRead += data.Size() / format.channels / (format.bits / 8);
627
628 if (track.length == -1 && track.approxLength > 0) inBytes = track.fileSize / Math::Max(1.f, Float(track.approxLength) / samplesRead);
629
630 return data.Size();
631 }