| 1 | /* fre:ac - free audio converter |
| 2 | * Copyright (C) 2001-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 <engine/worker.h> |
| 14 | |
| 15 | #include <engine/decoder.h> |
| 16 | #include <engine/encoder.h> |
| 17 | #include <engine/processor.h> |
| 18 | #include <engine/verifier.h> |
| 19 | #include <engine/locking.h> |
| 20 | |
| 21 | #include <config.h> |
| 22 | #include <utilities.h> |
| 23 | |
| 24 | using namespace BoCA; |
| 25 | using namespace BoCA::AS; |
| 26 | |
| 27 | #ifdef __WIN32__ |
| 28 | # include <windows.h> |
| 29 | |
| 30 | /* ToDo: Move this to smooth::File with smooth 0.10. |
| 31 | */ |
| 32 | FILETIME DateTimeToFileTime(const DateTime &dateTime) |
| 33 | { |
| 34 | SYSTEMTIME time, utc; |
| 35 | |
| 36 | memset(&time, 0, sizeof(time)); |
| 37 | |
| 38 | time.wYear = dateTime.GetYear(); |
| 39 | time.wMonth = dateTime.GetMonth(); |
| 40 | time.wDay = dateTime.GetDay(); |
| 41 | |
| 42 | time.wHour = dateTime.GetHour(); |
| 43 | time.wMinute = dateTime.GetMinute(); |
| 44 | time.wSecond = dateTime.GetSecond(); |
| 45 | |
| 46 | FILETIME fileTime; |
| 47 | |
| 48 | TzSpecificLocalTimeToSystemTime(NIL, &time, &utc); |
| 49 | SystemTimeToFileTime(&utc, &fileTime); |
| 50 | |
| 51 | return fileTime; |
| 52 | } |
| 53 | |
| 54 | Bool SetFileCreateTime(const File &file, const FILETIME &createTime) |
| 55 | { |
| 56 | if (!file.Exists()) return False; |
| 57 | |
| 58 | HANDLE handle = CreateFile(Directory::MakeExtendedPath(file), GENERIC_WRITE, 0, NIL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NIL); |
| 59 | |
| 60 | SetFileTime(handle, &createTime, NIL, NIL); |
| 61 | CloseHandle(handle); |
| 62 | |
| 63 | return True; |
| 64 | } |
| 65 | #endif |
| 66 | |
| 67 | freac::ConvertWorker::ConvertWorker(const BoCA::Config *iConfiguration, Int iConversionID) : workSignal(1) |
| 68 | { |
| 69 | configuration = iConfiguration; |
| 70 | |
| 71 | conversionID = iConversionID; |
| 72 | |
| 73 | logName = "Converter log"; |
| 74 | |
| 75 | numThreads = 0; |
| 76 | |
| 77 | trackToConvert = NIL; |
| 78 | trackStartTicks = 0; |
| 79 | trackPosition = 0; |
| 80 | |
| 81 | conversionStep = ConversionStepNone; |
| 82 | |
| 83 | idle = True; |
| 84 | waiting = True; |
| 85 | error = False; |
| 86 | |
| 87 | pause = False; |
| 88 | cancel = False; |
| 89 | quit = False; |
| 90 | |
| 91 | workSignal.Wait(); |
| 92 | |
| 93 | threadMain.Connect(&ConvertWorker::Perform, this); |
| 94 | } |
| 95 | |
| 96 | freac::ConvertWorker::~ConvertWorker() |
| 97 | { |
| 98 | } |
| 99 | |
| 100 | Int freac::ConvertWorker::Perform() |
| 101 | { |
| 102 | Bool enableParallel = configuration->GetIntValue(Config::CategoryResourcesID, Config::ResourcesEnableParallelConversionsID, Config::ResourcesEnableParallelConversionsDefault); |
| 103 | Int numberOfThreads = configuration->GetIntValue(Config::CategoryResourcesID, Config::ResourcesNumberOfConversionThreadsID, Config::ResourcesNumberOfConversionThreadsDefault); |
| 104 | |
| 105 | while (!Threads::Access::Value(quit)) |
| 106 | { |
| 107 | workSignal.Wait(); |
| 108 | |
| 109 | if (Threads::Access::Value(quit)) break; |
| 110 | |
| 111 | /* Do not limit parallel CD ripping jobs in automatic mode. |
| 112 | */ |
| 113 | Bool allocateThread = !(enableParallel && numberOfThreads <= 1 && trackToConvert.fileName.StartsWith("device://")); |
| 114 | |
| 115 | /* Allocate thread and run conversion. |
| 116 | */ |
| 117 | if (allocateThread) Locking::AllocateThread(); |
| 118 | |
| 119 | if (Convert() != Success()) Threads::Access::Set(error, True); |
| 120 | |
| 121 | if (allocateThread) Locking::FreeThread(); |
| 122 | |
| 123 | /* Return to waiting state. |
| 124 | */ |
| 125 | Threads::Access::Set(idle, True); |
| 126 | Threads::Access::Set(waiting, True); |
| 127 | Threads::Access::Set(cancel, False); |
| 128 | } |
| 129 | |
| 130 | return Success(); |
| 131 | } |
| 132 | |
| 133 | Int freac::ConvertWorker::Convert() |
| 134 | { |
| 135 | Registry &boca = Registry::Get(); |
| 136 | |
| 137 | /* Get config values. |
| 138 | */ |
| 139 | Bool encodeOnTheFly = configuration->GetIntValue(Config::CategorySettingsID, Config::SettingsEncodeOnTheFlyID, Config::SettingsEncodeOnTheFlyDefault); |
| 140 | Bool keepWaveFiles = configuration->GetIntValue(Config::CategorySettingsID, Config::SettingsKeepWaveFilesID, Config::SettingsKeepWaveFilesDefault); |
| 141 | |
| 142 | Bool keepTimeStamps = configuration->GetIntValue(Config::CategorySettingsID, Config::SettingsFilenamesKeepTimeStampsID, Config::SettingsFilenamesKeepTimeStampsDefault); |
| 143 | |
| 144 | Bool verifyInput = configuration->GetIntValue(Config::CategoryVerificationID, Config::VerificationVerifyInputID, Config::VerificationVerifyInputDefault); |
| 145 | Bool verifyOutput = configuration->GetIntValue(Config::CategoryVerificationID, Config::VerificationVerifyOutputID, Config::VerificationVerifyOutputDefault); |
| 146 | |
| 147 | Bool writeToInputDirectory = configuration->GetIntValue(Config::CategorySettingsID, Config::SettingsWriteToInputDirectoryID, Config::SettingsWriteToInputDirectoryDefault); |
| 148 | Bool allowOverwriteSource = configuration->GetIntValue(Config::CategorySettingsID, Config::SettingsAllowOverwriteSourceID, Config::SettingsAllowOverwriteSourceDefault); |
| 149 | |
| 150 | Bool deleteAfterEncoding = configuration->GetIntValue(Config::CategoryInternalID, Config::InternalDeleteAfterEncodingID, False); |
| 151 | |
| 152 | /* Find encoder to use. |
| 153 | */ |
| 154 | String selectedEncoderID = configuration->GetStringValue(Config::CategorySettingsID, Config::SettingsEncoderID, Config::SettingsEncoderDefault); |
| 155 | String activeEncoderID = selectedEncoderID; |
| 156 | |
| 157 | /* Do not verify output if meh! encoder selected. |
| 158 | */ |
| 159 | if (selectedEncoderID == "meh-enc") verifyOutput = False; |
| 160 | |
| 161 | /* We always convert on the fly when outputting simple audio files. |
| 162 | */ |
| 163 | if (selectedEncoderID == "wave-enc" || |
| 164 | selectedEncoderID == "sndfile-enc") encodeOnTheFly = True; |
| 165 | |
| 166 | /* Set initial number of conversion passes. |
| 167 | */ |
| 168 | Int conversionSteps = encodeOnTheFly ? 1 : 2; |
| 169 | |
| 170 | /* Loop over conversion passes. |
| 171 | */ |
| 172 | Track trackToEncode = trackToConvert; |
| 173 | Bool error = False; |
| 174 | |
| 175 | DateTime createTime = File(trackToConvert.fileName).GetCreationTime(); |
| 176 | DateTime modifyTime = File(trackToConvert.fileName).GetWriteTime(); |
| 177 | Bool isFile = !trackToConvert.fileName.StartsWith("device://"); |
| 178 | |
| 179 | UnsignedInt32 rippingCRC = 0; |
| 180 | |
| 181 | String encodeChecksum; |
| 182 | String verifyChecksum; |
| 183 | |
| 184 | for (Int step = 0; step < conversionSteps && !Threads::Access::Value(cancel); step++) |
| 185 | { |
| 186 | /* Setup file names. |
| 187 | */ |
| 188 | File inFile = trackToConvert.fileName; |
| 189 | File outFile = trackToConvert.outputFile; |
| 190 | Bool replace = outFile.Exists(); |
| 191 | |
| 192 | String inFileName = trackToConvert.fileName; |
| 193 | |
| 194 | /* Set conversion step. |
| 195 | */ |
| 196 | if (encodeOnTheFly) |
| 197 | { |
| 198 | if (step == 0) conversionStep = ConversionStepOnTheFly; |
| 199 | else conversionStep = ConversionStepVerify; |
| 200 | } |
| 201 | else |
| 202 | { |
| 203 | if (step == 0) conversionStep = ConversionStepDecode; |
| 204 | else if (step == 1) conversionStep = ConversionStepEncode; |
| 205 | else conversionStep = ConversionStepVerify; |
| 206 | } |
| 207 | |
| 208 | /* Setup intermediate encoder in non-on-the-fly mode. |
| 209 | */ |
| 210 | BoCA::Config *encoderConfig = BoCA::Config::Copy(configuration); |
| 211 | |
| 212 | if (conversionStep == ConversionStepDecode) |
| 213 | { |
| 214 | activeEncoderID = "wave-enc"; |
| 215 | |
| 216 | if (!boca.ComponentExists("wave-enc")) |
| 217 | { |
| 218 | activeEncoderID = "sndfile-enc"; |
| 219 | |
| 220 | encoderConfig->SetIntValue("SndFile", "Format", 0x010000); |
| 221 | encoderConfig->SetIntValue("SndFile", "SubFormat", 0x000000); |
| 222 | } |
| 223 | |
| 224 | outFile = String(outFile).Append(".wav"); |
| 225 | } |
| 226 | else if (conversionStep == ConversionStepEncode) |
| 227 | { |
| 228 | activeEncoderID = selectedEncoderID; |
| 229 | |
| 230 | inFile = String(outFile).Append(".wav"); |
| 231 | inFileName = inFile; |
| 232 | } |
| 233 | |
| 234 | /* Create temporary output file when replacing input. |
| 235 | */ |
| 236 | if (String(outFile).ToLower() == String(inFile).ToLower()) outFile = String(outFile).Append(".temp"); |
| 237 | |
| 238 | /* Set number of threads to requested value. |
| 239 | */ |
| 240 | if (numThreads == 1) encoderConfig->SetIntValue(Config::CategoryResourcesID, Config::ResourcesEnableParallelConversionsID, False); |
| 241 | else if (numThreads >= 2) encoderConfig->SetIntValue(Config::CategoryResourcesID, Config::ResourcesNumberOfConversionThreadsID, numThreads); |
| 242 | |
| 243 | /* Setup input file name in verification step. |
| 244 | */ |
| 245 | if (conversionStep == ConversionStepVerify) |
| 246 | { |
| 247 | if (String(outFile).ToLower() != String(inFile).ToLower().Append(".temp")) inFile = outFile; |
| 248 | else if (writeToInputDirectory && !allowOverwriteSource && !deleteAfterEncoding) inFile = String(inFile).Append(".new"); |
| 249 | else inFile = String(outFile).Head(String(outFile).Length() - 5); |
| 250 | |
| 251 | inFileName = inFile; |
| 252 | |
| 253 | if (!inFile.Exists()) |
| 254 | { |
| 255 | BoCA::I18n *i18n = BoCA::I18n::Get(); |
| 256 | BoCA::Protocol *log = BoCA::Protocol::Get(logName); |
| 257 | |
| 258 | onReportWarning.Emit(i18n->TranslateString("Skipped verification due to non existing output file: %1", "Messages").Replace("%1", inFile.GetFileName())); |
| 259 | |
| 260 | String basePath = Utilities::GetOutputBasePath(configuration, trackToConvert, inFileName); |
| 261 | |
| 262 | log->Lock(); |
| 263 | log->Write(String(" Skipping verification due to non existing output file: ").Append(Utilities::FormatFileNameForLogging(inFileName, basePath)), MessageTypeWarning); |
| 264 | log->Write(NIL); |
| 265 | log->Release(); |
| 266 | |
| 267 | trackPosition = trackToConvert.length; |
| 268 | |
| 269 | onFinishTrack.Emit(trackToConvert, False); |
| 270 | |
| 271 | BoCA::Config::Free(encoderConfig); |
| 272 | |
| 273 | break; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /* Check format of output file in verification step. |
| 278 | */ |
| 279 | if (conversionStep == ConversionStepVerify) |
| 280 | { |
| 281 | DecoderComponent *decoder = boca.CreateDecoderForStream(inFileName, configuration); |
| 282 | |
| 283 | if (decoder != NIL) |
| 284 | { |
| 285 | Track outTrack; |
| 286 | |
| 287 | decoder->GetStreamInfo(inFileName, outTrack); |
| 288 | |
| 289 | boca.DeleteComponent(decoder); |
| 290 | |
| 291 | Format format = trackToEncode.GetFormat(); |
| 292 | const Format &outFormat = outTrack.GetFormat(); |
| 293 | |
| 294 | if (format != outFormat) |
| 295 | { |
| 296 | BoCA::I18n *i18n = BoCA::I18n::Get(); |
| 297 | BoCA::Protocol *log = BoCA::Protocol::Get(logName); |
| 298 | |
| 299 | onReportWarning.Emit(i18n->TranslateString(String("Skipped verification due to format mismatch: %1\n\n") |
| 300 | .Append("Original format: %2 Hz, %3 bit, %4 channels\n") |
| 301 | .Append("Output format: %5 Hz, %6 bit, %7 channels"), "Messages").Replace("%1", inFile.GetFileName()).Replace("%2", String::FromInt(format.rate)).Replace("%3", String::FromInt(format.bits)).Replace("%4", String::FromInt(format.channels)) |
| 302 | .Replace("%5", String::FromInt(outFormat.rate)).Replace("%6", String::FromInt(outFormat.bits)).Replace("%7", String::FromInt(outFormat.channels))); |
| 303 | |
| 304 | String basePath = Utilities::GetOutputBasePath(configuration, trackToConvert, inFileName); |
| 305 | |
| 306 | log->Lock(); |
| 307 | log->Write(String(" Skipping verification due to format mismatch: ").Append(Utilities::FormatFileNameForLogging(inFileName, basePath)), MessageTypeWarning); |
| 308 | log->Write(NIL); |
| 309 | log->Release(); |
| 310 | |
| 311 | trackPosition = trackToConvert.length; |
| 312 | |
| 313 | onFinishTrack.Emit(trackToConvert, False); |
| 314 | |
| 315 | BoCA::Config::Free(encoderConfig); |
| 316 | |
| 317 | break; |
| 318 | } |
| 319 | |
| 320 | /* Update track format with decoder format. |
| 321 | */ |
| 322 | trackToConvert.SetFormat(outFormat); |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /* Create decoder. |
| 327 | */ |
| 328 | Decoder *decoder = new Decoder(configuration); |
| 329 | |
| 330 | if (!decoder->Create(inFileName, trackToConvert)) |
| 331 | { |
| 332 | onReportError.Emit(decoder->GetErrorString()); |
| 333 | |
| 334 | delete decoder; |
| 335 | |
| 336 | BoCA::Config::Free(encoderConfig); |
| 337 | |
| 338 | return Error(); |
| 339 | } |
| 340 | |
| 341 | if (conversionStep != ConversionStepEncode && |
| 342 | conversionStep != ConversionStepVerify) decoderName = decoder->GetDecoderName(); |
| 343 | |
| 344 | /* Create verifier. |
| 345 | */ |
| 346 | Verifier *verifier = new Verifier(configuration); |
| 347 | Bool verify = False; |
| 348 | |
| 349 | if ((conversionStep == ConversionStepOnTheFly || |
| 350 | conversionStep == ConversionStepDecode) && verifyInput) verify = verifier->Create(trackToConvert); |
| 351 | |
| 352 | /* Create processor. |
| 353 | */ |
| 354 | Processor *processor = new Processor(configuration); |
| 355 | |
| 356 | if (conversionStep == ConversionStepOnTheFly || |
| 357 | conversionStep == ConversionStepDecode) |
| 358 | { |
| 359 | if (!processor->Create(trackToEncode)) |
| 360 | { |
| 361 | onReportError.Emit(processor->GetErrorString()); |
| 362 | |
| 363 | delete decoder; |
| 364 | delete verifier; |
| 365 | delete processor; |
| 366 | |
| 367 | BoCA::Config::Free(encoderConfig); |
| 368 | |
| 369 | return Error(); |
| 370 | } |
| 371 | |
| 372 | trackToEncode.SetFormat(processor->GetFormatInfo()); |
| 373 | } |
| 374 | |
| 375 | /* Create encoder. |
| 376 | */ |
| 377 | Encoder *encoder = new Encoder(encoderConfig); |
| 378 | |
| 379 | if (conversionStep != ConversionStepVerify && !encoder->Create(activeEncoderID, outFile, trackToEncode)) |
| 380 | { |
| 381 | onReportError.Emit(encoder->GetErrorString()); |
| 382 | |
| 383 | delete decoder; |
| 384 | delete verifier; |
| 385 | delete processor; |
| 386 | delete encoder; |
| 387 | |
| 388 | outFile.Delete(); |
| 389 | |
| 390 | BoCA::Config::Free(encoderConfig); |
| 391 | |
| 392 | return Error(); |
| 393 | } |
| 394 | |
| 395 | if (conversionStep == ConversionStepOnTheFly || |
| 396 | conversionStep == ConversionStepEncode) encoderName = encoder->GetEncoderName(); |
| 397 | |
| 398 | trackToEncode.SetFormat(encoder->GetTargetFormat()); |
| 399 | |
| 400 | /* Enable CRC calculation when ripping. |
| 401 | */ |
| 402 | if (inFileName.StartsWith("device://") && (conversionStep == ConversionStepOnTheFly || |
| 403 | conversionStep == ConversionStepDecode)) decoder->SetCalculateCRC(True); |
| 404 | |
| 405 | /* Enable MD5 and add a verification step if we are to verify the output. |
| 406 | */ |
| 407 | if (verifyOutput && (conversionStep == ConversionStepOnTheFly || |
| 408 | conversionStep == ConversionStepEncode) && encoder->IsLossless()) { encoder->SetCalculateMD5(True); conversionSteps += 1; } |
| 409 | else if (verifyOutput && conversionStep == ConversionStepVerify ) decoder->SetCalculateMD5(True); |
| 410 | |
| 411 | /* Output log messages. |
| 412 | */ |
| 413 | LogConversionStart(decoder, inFileName, outFile, replace); |
| 414 | |
| 415 | /* Run main conversion loop. |
| 416 | */ |
| 417 | Int64 trackLength = Loop(decoder, verifier, NIL, processor, encoder); |
| 418 | |
| 419 | /* Verify input. |
| 420 | */ |
| 421 | if (!Threads::Access::Value(cancel) && verify) VerifyInput(inFileName, verifier); |
| 422 | |
| 423 | /* Get CRC checksums when ripping. |
| 424 | */ |
| 425 | if (inFileName.StartsWith("device://") && (conversionStep == ConversionStepOnTheFly || |
| 426 | conversionStep == ConversionStepDecode)) rippingCRC = decoder->GetCRCChecksum(); |
| 427 | |
| 428 | /* Get MD5 checksums if we are to verify the output. |
| 429 | */ |
| 430 | if (verifyOutput && (conversionStep == ConversionStepOnTheFly || |
| 431 | conversionStep == ConversionStepEncode) && encoder->IsLossless()) encodeChecksum = encoder->GetMD5Checksum(); |
| 432 | else if (verifyOutput && conversionStep == ConversionStepVerify ) verifyChecksum = decoder->GetMD5Checksum(); |
| 433 | |
| 434 | /* Get output format info. |
| 435 | */ |
| 436 | Format format = trackToConvert.GetFormat(); |
| 437 | |
| 438 | if (processor->GetFormatInfo() != Format()) format = processor->GetFormatInfo(); |
| 439 | |
| 440 | /* Free decoder, verifier, processor and encoder. |
| 441 | */ |
| 442 | decoder->Destroy(); |
| 443 | verifier->Destroy(); |
| 444 | processor->Destroy(); |
| 445 | encoder->Destroy(); |
| 446 | |
| 447 | if (decoder->GetErrorState()) { error = True; onReportError.Emit(decoder->GetErrorString()); } |
| 448 | if (processor->GetErrorState()) { error = True; onReportError.Emit(processor->GetErrorString()); } |
| 449 | if (encoder->GetErrorState()) { error = True; onReportError.Emit(encoder->GetErrorString()); } |
| 450 | |
| 451 | delete decoder; |
| 452 | delete verifier; |
| 453 | delete processor; |
| 454 | delete encoder; |
| 455 | |
| 456 | BoCA::Config::Free(encoderConfig); |
| 457 | |
| 458 | /* Output log messages. |
| 459 | */ |
| 460 | LogConversionEnd(inFileName, trackLength, rippingCRC, encodeChecksum, verifyChecksum); |
| 461 | |
| 462 | /* Delete output file if it doesn't look sane. |
| 463 | */ |
| 464 | if (outFile.GetFileSize() <= 0 || Threads::Access::Value(cancel) || error) outFile.Delete(); |
| 465 | |
| 466 | /* Delete intermediate file in non-on-the-fly mode. |
| 467 | */ |
| 468 | if (conversionStep == ConversionStepEncode) |
| 469 | { |
| 470 | if (!keepWaveFiles || Threads::Access::Value(cancel) || error) inFile.Delete(); |
| 471 | |
| 472 | if (String(inFile).EndsWith(".temp.wav")) inFile = String(inFile).Head(String(inFile).Length() - 9); |
| 473 | } |
| 474 | |
| 475 | /* Move output file if temporary. |
| 476 | */ |
| 477 | if (String(outFile).ToLower() == String(inFile).ToLower().Append(".temp") && outFile.Exists()) |
| 478 | { |
| 479 | File targetOutFile = String(outFile).Head(String(outFile).Length() - 5); |
| 480 | |
| 481 | if (!writeToInputDirectory || allowOverwriteSource || deleteAfterEncoding || !targetOutFile.Exists()) |
| 482 | { |
| 483 | targetOutFile.Delete(); |
| 484 | outFile.Move(targetOutFile); |
| 485 | |
| 486 | outFile = targetOutFile; |
| 487 | } |
| 488 | else |
| 489 | { |
| 490 | File(String(targetOutFile).Append(".new")).Delete(); |
| 491 | outFile.Move(String(targetOutFile).Append(".new")); |
| 492 | |
| 493 | outFile = String(targetOutFile).Append(".new"); |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /* Set file time stamp to that of original file if requested. |
| 498 | */ |
| 499 | if ((conversionStep == ConversionStepOnTheFly || conversionStep == ConversionStepEncode) && keepTimeStamps && isFile && outFile.Exists()) |
| 500 | { |
| 501 | #ifdef __WIN32__ |
| 502 | SetFileCreateTime(outFile, DateTimeToFileTime(createTime)); |
| 503 | #endif |
| 504 | |
| 505 | outFile.SetWriteTime(modifyTime); |
| 506 | } |
| 507 | |
| 508 | /* Revert to waiting state when there are more steps left. |
| 509 | */ |
| 510 | if (step < conversionSteps - 1) Threads::Access::Set(waiting, True); |
| 511 | |
| 512 | /* Report finished conversion. |
| 513 | */ |
| 514 | onFinishTrack.Emit(trackToConvert, waiting); |
| 515 | |
| 516 | /* Update track length and offset. |
| 517 | */ |
| 518 | Track track = trackToConvert; |
| 519 | |
| 520 | trackToConvert.SetFormat(format); |
| 521 | |
| 522 | trackToConvert.sampleOffset = 0; |
| 523 | trackToConvert.length = trackLength; |
| 524 | |
| 525 | /* Fix total samples value in case we had |
| 526 | * a wrong or uncertain track length before. |
| 527 | */ |
| 528 | onFixTotalSamples.Emit(track, trackToConvert); |
| 529 | } |
| 530 | |
| 531 | if (error) return Error(); |
| 532 | else return Success(); |
| 533 | } |
| 534 | |
| 535 | Int64 freac::ConvertWorker::Loop(Decoder *decoder, Verifier *verifier, FormatConverter *converter, Processor *processor, Encoder *encoder) |
| 536 | { |
| 537 | /* Get config values. |
| 538 | */ |
| 539 | Int ripperTimeout = configuration->GetIntValue(Config::CategoryRipperID, Config::RipperTimeoutID, Config::RipperTimeoutDefault); |
| 540 | |
| 541 | /* Inform components about starting conversion. |
| 542 | */ |
| 543 | BoCA::Engine *engine = BoCA::Engine::Get(); |
| 544 | |
| 545 | engine->onStartTrackConversion.Emit(conversionID, trackToConvert); |
| 546 | |
| 547 | /* Enter conversion loop. |
| 548 | */ |
| 549 | Format format = trackToConvert.GetFormat(); |
| 550 | |
| 551 | Int64 trackOffset = encoder->GetEncodedSamples(); |
| 552 | UnsignedLong samplesSize = format.rate / 8; |
| 553 | |
| 554 | trackStartTicks = S::System::System::Clock(); |
| 555 | trackPosition = 0; |
| 556 | |
| 557 | Threads::Access::Set(waiting, False); |
| 558 | |
| 559 | Int bytesPerSample = format.bits / 8 * format.channels; |
| 560 | Buffer<UnsignedByte> buffer(samplesSize * bytesPerSample); |
| 561 | |
| 562 | while (!Threads::Access::Value(cancel)) |
| 563 | { |
| 564 | Int step = samplesSize; |
| 565 | |
| 566 | if (trackToConvert.length >= 0) |
| 567 | { |
| 568 | if (trackPosition >= trackToConvert.length) break; |
| 569 | |
| 570 | if (trackPosition + step > trackToConvert.length) step = trackToConvert.length - trackPosition; |
| 571 | } |
| 572 | |
| 573 | buffer.Resize(step * bytesPerSample); |
| 574 | |
| 575 | /* Read samples from decoder. |
| 576 | */ |
| 577 | Int bytes = decoder->Read(buffer); |
| 578 | |
| 579 | if (bytes == -1) { Threads::Access::Set(cancel, True); break; } |
| 580 | else if (bytes == 0) break; |
| 581 | |
| 582 | /* Pass samples to verifier. |
| 583 | */ |
| 584 | if (verifier != NIL) verifier->Process(buffer); |
| 585 | |
| 586 | /* Convert format and process samples. |
| 587 | */ |
| 588 | if (converter != NIL) converter->Transform(buffer); |
| 589 | if (processor != NIL) processor->Transform(buffer); |
| 590 | |
| 591 | /* Pass samples to encoder. |
| 592 | */ |
| 593 | if (encoder->Write(buffer) == -1) { Threads::Access::Set(cancel, True); break; } |
| 594 | |
| 595 | /* Update position info. |
| 596 | */ |
| 597 | if (trackToConvert.length >= 0) trackPosition += (bytes / bytesPerSample); |
| 598 | else trackPosition = decoder->GetInBytes(); |
| 599 | |
| 600 | /* Check for ripper timeout. |
| 601 | */ |
| 602 | if (trackToConvert.isCDTrack && ripperTimeout > 0 && S::System::System::Clock() - trackStartTicks > (UnsignedInt64) ripperTimeout * 1000) |
| 603 | { |
| 604 | BoCA::Utilities::WarningMessage("CD ripping timeout after %1 seconds. Skipping track.", String::FromInt(ripperTimeout)); |
| 605 | |
| 606 | Threads::Access::Set(cancel, True); |
| 607 | } |
| 608 | |
| 609 | /* Pause if requested. |
| 610 | */ |
| 611 | while (Threads::Access::Value(pause) && !Threads::Access::Value(cancel)) S::System::System::Sleep(50); |
| 612 | } |
| 613 | |
| 614 | /* Finish format conversion and processing. |
| 615 | */ |
| 616 | for (Int i = 0; i < 2 && !Threads::Access::Value(cancel); i++) |
| 617 | { |
| 618 | buffer.Resize(0); |
| 619 | |
| 620 | if (i == 0 && converter != NIL) converter->Finish(buffer); |
| 621 | if (i == 0 && processor != NIL) processor->Transform(buffer); |
| 622 | |
| 623 | if (i == 1 && processor != NIL) processor->Finish(buffer); |
| 624 | |
| 625 | if (encoder->Write(buffer) == -1) Threads::Access::Set(cancel, True); |
| 626 | } |
| 627 | |
| 628 | /* Inform components about finished/cancelled conversion. |
| 629 | */ |
| 630 | if (Threads::Access::Value(cancel)) engine->onCancelTrackConversion.Emit(conversionID, trackToConvert); |
| 631 | else engine->onFinishTrackConversion.Emit(conversionID, trackToConvert); |
| 632 | |
| 633 | /* Compute track length in target format. |
| 634 | */ |
| 635 | if (encoder->GetEncodedSamples() == 0) |
| 636 | { |
| 637 | Int64 trackLength = decoder->GetDecodedSamples(); |
| 638 | Format targetFormat = format; |
| 639 | |
| 640 | if (processor != NIL && processor->GetFormatInfo() != Format()) targetFormat = processor->GetFormatInfo(); |
| 641 | |
| 642 | return trackLength * targetFormat.rate / format.rate; |
| 643 | } |
| 644 | |
| 645 | return encoder->GetEncodedSamples() - trackOffset; |
| 646 | } |
| 647 | |
| 648 | Void freac::ConvertWorker::VerifyInput(const String &uri, Verifier *verifier) |
| 649 | { |
| 650 | BoCA::Protocol *log = BoCA::Protocol::Get(logName); |
| 651 | |
| 652 | log->Lock(); |
| 653 | |
| 654 | String errorMessage; |
| 655 | String uriType = uri.StartsWith("device://") ? "track" : "file"; |
| 656 | |
| 657 | if (verifier->Verify()) |
| 658 | { |
| 659 | log->Write(String(" Successfully verified input ").Append(uriType).Append(": ").Append(Utilities::FormatFileNameForLogging(uri))); |
| 660 | } |
| 661 | else if (!verifier->GetErrorState()) |
| 662 | { |
| 663 | log->Write(String(" Could not verify input ").Append(uriType).Append(": ").Append(Utilities::FormatFileNameForLogging(uri)), MessageTypeWarning); |
| 664 | } |
| 665 | else |
| 666 | { |
| 667 | BoCA::I18n *i18n = BoCA::I18n::Get(); |
| 668 | |
| 669 | errorMessage = i18n->TranslateString(String("Failed to verify input ").Append(uriType).Append(": %1"), "Errors").Replace("%1", uri.Contains("://") ? uri : File(uri).GetFileName()).Append("\n\n").Append(verifier->GetErrorString()); |
| 670 | |
| 671 | log->Write(String(" Failed to verify input ").Append(uriType).Append(": ").Append(Utilities::FormatFileNameForLogging(uri)), MessageTypeError); |
| 672 | } |
| 673 | |
| 674 | /* Print messages generated by verifier component. |
| 675 | */ |
| 676 | const Array<String> &messages = verifier->GetErrorString().Explode("\n"); |
| 677 | |
| 678 | foreach (const String &message, messages) log->Write(String(" ").Append(message)); |
| 679 | |
| 680 | log->Write(NIL); |
| 681 | log->Release(); |
| 682 | |
| 683 | /* Report error message if any. |
| 684 | */ |
| 685 | if (errorMessage != NIL) |
| 686 | { |
| 687 | onReportError.Emit(errorMessage); |
| 688 | |
| 689 | Threads::Access::Set(error, True); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | Void freac::ConvertWorker::LogConversionStart(Decoder *decoder, const String &uri, const String &outFile, Bool replace) const |
| 694 | { |
| 695 | String verb = "Converting"; |
| 696 | |
| 697 | if (uri.StartsWith("device://")) verb = "Ripping"; |
| 698 | else if (conversionStep == ConversionStepDecode) verb = "Decoding"; |
| 699 | else if (conversionStep == ConversionStepEncode) verb = "Encoding"; |
| 700 | else if (conversionStep == ConversionStepVerify) verb = "Verifying"; |
| 701 | |
| 702 | BoCA::Protocol *log = BoCA::Protocol::Get(logName); |
| 703 | |
| 704 | log->Lock(); |
| 705 | log->Write(String(" ").Append(verb).Append(": ").Append(Utilities::FormatFileNameForLogging(uri))); |
| 706 | |
| 707 | /* Log output file. |
| 708 | */ |
| 709 | String outputFile = outFile; |
| 710 | |
| 711 | if (String(outFile).ToLower() == String(uri).ToLower().Append(".temp")) outputFile = uri; |
| 712 | |
| 713 | if (outFile != NIL && conversionStep != ConversionStepVerify) |
| 714 | { |
| 715 | String basePath = Utilities::GetOutputBasePath(configuration, trackToConvert, outputFile); |
| 716 | |
| 717 | log->Write(String(" ").Append(String().FillN(' ', verb.Length() - 2)).Append("to: ").Append(Utilities::FormatFileNameForLogging(outputFile, basePath))); |
| 718 | } |
| 719 | |
| 720 | /* Log overwriting of files. |
| 721 | */ |
| 722 | if (outFile != NIL && (conversionStep == ConversionStepOnTheFly || conversionStep == ConversionStepEncode)) |
| 723 | { |
| 724 | if (outputFile == uri) log->Write(" Replacing input file with conversion result"); |
| 725 | else if (replace) log->Write(" Replacing existing file with conversion result"); |
| 726 | } |
| 727 | |
| 728 | /* Log used decoder. |
| 729 | */ |
| 730 | if (conversionStep == ConversionStepOnTheFly || conversionStep == ConversionStepDecode) |
| 731 | { |
| 732 | log->Write(String(" Decoder: ").Append(decoder->GetDecoderName())); |
| 733 | } |
| 734 | |
| 735 | log->Write(NIL); |
| 736 | log->Release(); |
| 737 | } |
| 738 | |
| 739 | Void freac::ConvertWorker::LogConversionEnd(const String &uri, Int64 trackLength, UnsignedInt32 rippingCRC, const String &encodeChecksum, const String &verifyChecksum) |
| 740 | { |
| 741 | String verb = "converting"; |
| 742 | |
| 743 | if (uri.StartsWith("device://")) verb = "ripping"; |
| 744 | else if (conversionStep == ConversionStepDecode) verb = "decoding"; |
| 745 | else if (conversionStep == ConversionStepEncode) verb = "encoding"; |
| 746 | |
| 747 | BoCA::Protocol *log = BoCA::Protocol::Get(logName); |
| 748 | |
| 749 | log->Lock(); |
| 750 | |
| 751 | String formattedURI = Utilities::FormatFileNameForLogging(uri); |
| 752 | String errorMessage; |
| 753 | |
| 754 | if (conversionStep != ConversionStepVerify) |
| 755 | { |
| 756 | /* Log conversion result. |
| 757 | */ |
| 758 | if (Threads::Access::Value(cancel)) |
| 759 | { |
| 760 | log->Write(String(" Cancelled ").Append(verb).Append(": ").Append(formattedURI), MessageTypeWarning); |
| 761 | } |
| 762 | else |
| 763 | { |
| 764 | log->Write(String(" Finished ").Append(verb).Append(": ").Append(formattedURI)); |
| 765 | |
| 766 | if (uri.StartsWith("device://") && (conversionStep == ConversionStepOnTheFly || |
| 767 | conversionStep == ConversionStepDecode)) log->Write(String(" CRC checksum: ").Append(Number(Int64(rippingCRC)).ToHexString(8))); |
| 768 | } |
| 769 | } |
| 770 | else |
| 771 | { |
| 772 | /* Log verification result. |
| 773 | */ |
| 774 | if (Threads::Access::Value(cancel)) |
| 775 | { |
| 776 | log->Write(String(" Cancelled verifying output file: %1").Replace("%1", formattedURI), MessageTypeWarning); |
| 777 | } |
| 778 | else if (encodeChecksum != verifyChecksum) |
| 779 | { |
| 780 | BoCA::I18n *i18n = BoCA::I18n::Get(); |
| 781 | |
| 782 | errorMessage = i18n->TranslateString("Checksum mismatch verifying output file: %1\n\nEncode checksum: %2\nVerify checksum: %3", "Errors").Replace("%1", File(uri).GetFileName()).Replace("%2", encodeChecksum).Replace("%3", verifyChecksum); |
| 783 | |
| 784 | log->Write(String(" Checksum mismatch verifying output file: %1").Replace("%1", formattedURI), MessageTypeError); |
| 785 | log->Write(String(" Encode MD5: %1").Replace("%1", encodeChecksum)); |
| 786 | log->Write(String(" Verify MD5: %1").Replace("%1", verifyChecksum)); |
| 787 | } |
| 788 | else |
| 789 | { |
| 790 | log->Write(String(" Successfully verified output file: %1").Replace("%1", formattedURI)); |
| 791 | log->Write(String(" MD5 hash: %1").Replace("%1", verifyChecksum)); |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | /* Log duration. |
| 796 | */ |
| 797 | if (!Threads::Access::Value(cancel)) |
| 798 | { |
| 799 | UnsignedInt64 ticks = S::System::System::Clock() - trackStartTicks; |
| 800 | String duration = BoCA::Utilities::ConvertTicksToTimestamp(ticks); |
| 801 | String speed = String::FromFloat(Math::Round(Float(trackLength) / trackToConvert.GetFormat().rate / (Float(ticks) / 1000.0) * 10.0) / 10.0); |
| 802 | |
| 803 | if (!speed.Contains(".")) speed.Append(".0"); |
| 804 | |
| 805 | log->Write(String(" Duration: ").Append(duration).Append(" (").Append(speed).Append("x speed)")); |
| 806 | } |
| 807 | |
| 808 | log->Write(NIL); |
| 809 | log->Release(); |
| 810 | |
| 811 | /* Report error message if any. |
| 812 | */ |
| 813 | if (errorMessage != NIL) |
| 814 | { |
| 815 | onReportError.Emit(errorMessage); |
| 816 | |
| 817 | Threads::Access::Set(error, True); |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | Void freac::ConvertWorker::SetTrackToConvert(const BoCA::Track &nTrack) |
| 822 | { |
| 823 | trackToConvert = nTrack; |
| 824 | trackStartTicks = 0; |
| 825 | trackPosition = 0; |
| 826 | |
| 827 | Threads::Access::Set(idle, False); |
| 828 | Threads::Access::Set(waiting, True); |
| 829 | Threads::Access::Set(error, False); |
| 830 | |
| 831 | workSignal.Release(); |
| 832 | } |
| 833 | |
| 834 | Int freac::ConvertWorker::Pause(Bool value) |
| 835 | { |
| 836 | Threads::Access::Set(pause, value); |
| 837 | |
| 838 | return Success(); |
| 839 | } |
| 840 | |
| 841 | Int freac::ConvertWorker::Cancel() |
| 842 | { |
| 843 | Threads::Access::Set(cancel, True); |
| 844 | |
| 845 | return Success(); |
| 846 | } |
| 847 | |
| 848 | Int freac::ConvertWorker::Quit() |
| 849 | { |
| 850 | Threads::Access::Set(cancel, True); |
| 851 | Threads::Access::Set(quit, True); |
| 852 | |
| 853 | workSignal.Release(); |
| 854 | |
| 855 | return Success(); |
| 856 | } |