Example #1
0
boolByte programOptionsParseConfigFile(ProgramOptions self, const CharString filename) {
  boolByte result = false;
  File configFile = NULL;
  LinkedList configFileLines = NULL;
  CharString* argvCharStrings;
  int argc;
  char** argv;
  int i;

  if(filename == NULL || charStringIsEmpty(filename)) {
    logCritical("Cannot read options from empty filename");
    return false;
  }

  configFile = newFileWithPath(filename);
  if(configFile == NULL || configFile->fileType != kFileTypeFile) {
    logCritical("Cannot read options from non-existent file '%s'", filename->data);
    freeFile(configFile);
    return false;
  }

  configFileLines = fileReadLines(configFile);
  if(configFileLines == NULL) {
    logInternalError("Could not split config file lines");
    return false;
  }
  else if(linkedListLength(configFileLines) == 0) {
    logInfo("Config file '%s' is empty", filename->data);
    freeLinkedList(configFileLines);
    freeFile(configFile);
    return true;
  }
  else {
    // Don't need the file anymore, it can be freed here
    freeFile(configFile);
  }

  argvCharStrings = (CharString*)linkedListToArray(configFileLines);
  argc = linkedListLength(configFileLines);
  argv = (char**)malloc(sizeof(char*) * (argc + 1));
  // Normally this would be the application name, don't care about it here
  argv[0] = NULL;
  for(i = 0; i < argc; i++) {
    argv[i + 1] = argvCharStrings[i]->data;
  }
  argc++;
  result = programOptionsParseArgs(self, argc, argv);

  freeLinkedListAndItems(configFileLines, (LinkedListFreeItemFunc)freeCharString);
  free(argvCharStrings);
  free(argv);
  return result;
}
Example #2
0
void setLogFile(const CharString logFileName) {
  EventLogger eventLogger = _getEventLoggerInstance();
  eventLogger->logFile = fopen(logFileName->data, "a");
  if(eventLogger->logFile == NULL) {
    logCritical("Could not open file '%s' for logging", logFileName->data);
  }
}
Example #3
0
size_t sampleSourcePcmWrite(SampleSourcePcmData self, const SampleBuffer sampleBuffer) {
    size_t pcmSamplesWritten = 0;
    size_t numSamplesToWrite = (size_t)(sampleBuffer->numChannels * sampleBuffer->blocksize);

    if(self == NULL || self->fileHandle == NULL) {
        logCritical("Corrupt PCM data structure");
        return false;
    }

    if(self->dataBufferNumItems < (size_t)(sampleBuffer->numChannels * sampleBuffer->blocksize)) {
        self->dataBufferNumItems = (size_t)(sampleBuffer->numChannels * sampleBuffer->blocksize);
        self->interlacedPcmDataBuffer = (short*)realloc(self->interlacedPcmDataBuffer, sizeof(short) * self->dataBufferNumItems);
    }

    // Clear the PCM data buffer just to be safe
    memset(self->interlacedPcmDataBuffer, 0, sizeof(short) * self->dataBufferNumItems);

    sampleBufferGetPcmSamples(sampleBuffer, self->interlacedPcmDataBuffer, self->isLittleEndian != isHostLittleEndian());
    pcmSamplesWritten = fwrite(self->interlacedPcmDataBuffer, sizeof(short), numSamplesToWrite, self->fileHandle);
    if(pcmSamplesWritten < numSamplesToWrite) {
        logWarn("Short write to PCM file");
        return pcmSamplesWritten;
    }

    logDebug("Wrote %d samples to PCM file", pcmSamplesWritten);
    return pcmSamplesWritten;
}
Example #4
0
static PluginPresetType _pluginPresetGuessType(const CharString presetName) {
  const char* fileExtension;
  size_t i;

  if(presetName == NULL || charStringIsEmpty(presetName)) {
    return PRESET_TYPE_INVALID;
  }

  fileExtension = getFileExtension(presetName->data);
  if(fileExtension == NULL) {
    for(i = 0; i < strlen(presetName->data); i++) {
      if(!charStringIsNumber(presetName, i)) {
        return PRESET_TYPE_INVALID;
      }
    }
    // If the preset name is all numeric, then it's an internal program number
    return PRESET_TYPE_INTERNAL_PROGRAM;
  }
  else if(!strcasecmp(fileExtension, "fxp")) {
    return PRESET_TYPE_FXP;
  }
  else {
    logCritical("Preset '%s' does not match any supported type", presetName->data);
    return PRESET_TYPE_INVALID;
  }
}
Example #5
0
size_t sampleSourcePcmRead(SampleSourcePcmData self, SampleBuffer sampleBuffer) {
    size_t pcmSamplesRead = 0;

    if(self == NULL || self->fileHandle == NULL) {
        logCritical("Corrupt PCM data structure");
        return 0;
    }

    if(self->dataBufferNumItems < (size_t)(sampleBuffer->numChannels * sampleBuffer->blocksize)) {
        self->dataBufferNumItems = (size_t)(sampleBuffer->numChannels * sampleBuffer->blocksize);
        self->interlacedPcmDataBuffer = (short*)realloc(self->interlacedPcmDataBuffer, sizeof(short) * self->dataBufferNumItems);
    }

    // Clear the PCM data buffer, or else the last block will have dirty samples in the end
    memset(self->interlacedPcmDataBuffer, 0, sizeof(short) * self->dataBufferNumItems);

    pcmSamplesRead = fread(self->interlacedPcmDataBuffer, sizeof(short), self->dataBufferNumItems, self->fileHandle);
    if(pcmSamplesRead < self->dataBufferNumItems) {
        logDebug("End of PCM file reached");
        // Set the blocksize of the sample buffer to be the number of frames read
        sampleBuffer->blocksize = pcmSamplesRead / sampleBuffer->numChannels;
    }
    logDebug("Read %d samples from PCM file", pcmSamplesRead);

    sampleBufferCopyPcmSamples(sampleBuffer, self->interlacedPcmDataBuffer);
    return pcmSamplesRead;
}
Example #6
0
void initLogging( const char *name )
{
    int i;

    gLogName = name;

    // initialize globals to something safe until startLogging has been invoked
    gLogDestination = kLogToUndefined;
    gLogLevel       = kLogDebug;
    gLogFile        = stderr;
    gLogString      = &_logToStderr;

    gDLhandle       = dlopen(NULL, RTLD_LAZY);

    // dynamically defined in logscopedefs.inc by Makefile
    logLogInit();

   	for ( i = 0; i < kMaxLogScope; ++i )
   	{
        gLog[i].level = kLogDebug;
        if ( gLog[i].site == NULL )
        {
            logCritical("### Failed to allocate memory for logging - exiting\n");
            exit(ENOMEM); // fatal
        }

        logDebug("%s scope has %u log statements", logScopeNames[i], gLog[i].max);
    }

    if (gDLhandle != NULL)
    {
        logFunctionTraceOn();
    }
}
Example #7
0
static boolByte _fillOptionArgument(ProgramOption self, int* currentArgc, int argc, char** argv) {
  if(self->argumentType == kProgramOptionArgumentTypeNone) {
    return true;
  }
  else if(self->argumentType == kProgramOptionArgumentTypeOptional) {
    int potentialNextArgc = *currentArgc + 1;
    if(potentialNextArgc >= argc) {
      return true;
    }
    else {
      char* potentialNextArg = argv[potentialNextArgc];
      // If the next string in the sequence is NOT an argument, we assume it is the optional argument
      if(!_isStringShortOption(potentialNextArg) && !_isStringLongOption(potentialNextArg)) {
        _programOptionSetData(self, potentialNextArg);
        (*currentArgc)++;
        return true;
      }
      else {
        // Otherwise, it is another option, but that's ok
        return true;
      }
    }
  }
  else if(self->argumentType == kProgramOptionArgumentTypeRequired) {
    int nextArgc = *currentArgc + 1;
    if(nextArgc >= argc) {
      logCritical("Option '%s' requires an argument, but none was given", self->name->data);
      return false;
    }
    else {
      char* nextArg = argv[nextArgc];
      if(_isStringShortOption(nextArg) || _isStringLongOption(nextArg)) {
        logCritical("Option '%s' requires an argument, but '%s' is not valid", self->name->data, nextArg);
        return false;
      }
      else {
        _programOptionSetData(self, nextArg);
        (*currentArgc)++;
        return true;
      }
    }
  }
  else {
    logInternalError("Unknown argument type '%d'", self->argumentType);
    return false;
  }
}
Example #8
0
static SampleSourceType _sampleSourceGuess(const CharString sampleSourceName)
{
    File sourceFile = NULL;
    CharString sourceFileExtension = NULL;
    SampleSourceType result = SAMPLE_SOURCE_TYPE_PCM;

    if (sampleSourceName == NULL || charStringIsEmpty(sampleSourceName)) {
        result = SAMPLE_SOURCE_TYPE_SILENCE;
    } else {
        // Look for stdin/stdout
        if (strlen(sampleSourceName->data) == 1 && sampleSourceName->data[0] == '-') {
            result = SAMPLE_SOURCE_TYPE_PCM;
        } else {
            sourceFile = newFileWithPath(sampleSourceName);
            sourceFileExtension = fileGetExtension(sourceFile);
            freeFile(sourceFile);

            // If there is no file extension, then automatically assume raw PCM data. Deal with it!
            if (charStringIsEmpty(sourceFileExtension)) {
                result = SAMPLE_SOURCE_TYPE_PCM;
            }
            // Possible file extensions for raw PCM data
            else if (charStringIsEqualToCString(sourceFileExtension, "pcm", true) ||
                     charStringIsEqualToCString(sourceFileExtension, "raw", true) ||
                     charStringIsEqualToCString(sourceFileExtension, "dat", true)) {
                result = SAMPLE_SOURCE_TYPE_PCM;
            }

#if USE_AUDIOFILE
            else if (charStringIsEqualToCString(sourceFileExtension, "aif", true) ||
                     charStringIsEqualToCString(sourceFileExtension, "aiff", true)) {
                result = SAMPLE_SOURCE_TYPE_AIFF;
            }

#endif

#if USE_FLAC
            else if (charStringIsEqualToCString(sourceFileExtension, "flac", true)) {
                result = SAMPLE_SOURCE_TYPE_FLAC;
            }

#endif

            else if (charStringIsEqualToCString(sourceFileExtension, "wav", true) ||
                     charStringIsEqualToCString(sourceFileExtension, "wave", true)) {
                result = SAMPLE_SOURCE_TYPE_WAVE;
            } else {
                logCritical("Sample source '%s' does not match any supported type", sampleSourceName->data);
                result = SAMPLE_SOURCE_TYPE_INVALID;
            }
        }
    }

    freeCharString(sourceFileExtension);
    return result;
}
Example #9
0
static void handleSignal(int signum) {
  logCritical("Sent signal %d, exiting", signum);
  if(gErrorReporter != NULL && gErrorReporter->started) {
    errorReporterClose(gErrorReporter);
  }
  else {
    logPossibleBug("MrsWatson (or one of its hosted plugins) has encountered a serious error and crashed.");
  }
  exit(RETURN_CODE_SIGNAL + signum);
}
Example #10
0
void setLogLevelFromString(const CharString logLevelString)
{
    if (charStringIsEqualToCString(logLevelString, "debug", true)) {
        setLogLevel(LOG_DEBUG);
    } else if (charStringIsEqualToCString(logLevelString, "info", true)) {
        setLogLevel(LOG_INFO);
    } else if (charStringIsEqualToCString(logLevelString, "warn", true)) {
        setLogLevel(LOG_WARN);
    } else if (charStringIsEqualToCString(logLevelString, "error", true)) {
        setLogLevel(LOG_ERROR);
    } else {
        logCritical("Invalid log level '%s', see '--help full' for valid arguments", logLevelString->data);
    }
}
Example #11
0
void setLoggingColorEnabledWithString(const CharString colorSchemeName)
{
    if (charStringIsEmpty(colorSchemeName)) {
        setLoggingColorEnabled(false);
    } else if (charStringIsEqualToCString(colorSchemeName, "none", false)) {
        setLoggingColorEnabled(false);
    } else if (charStringIsEqualToCString(colorSchemeName, "auto", false)) {
        setLoggingColorEnabled((boolByte)isatty(1));
    } else if (charStringIsEqualToCString(colorSchemeName, "force", false)) {
        setLoggingColorEnabled(true);
    } else {
        // Use critical log level to avoid colors
        logCritical("Unknown color scheme '%s'", colorSchemeName->data);
    }
}
Example #12
0
SampleSourceType sampleSourceGuess(const CharString sampleSourceTypeString) {
  if(!charStringIsEmpty(sampleSourceTypeString)) {
    // Look for stdin/stdout
    if(strlen(sampleSourceTypeString->data) == 1 && sampleSourceTypeString->data[0] == '-') {
      return SAMPLE_SOURCE_TYPE_PCM;
    }
    else {
      const char* fileExtension = getFileExtension(sampleSourceTypeString->data);
      // If there is no file extension, then automatically assume raw PCM data. Deal with it!
      if(fileExtension == NULL) {
        return SAMPLE_SOURCE_TYPE_PCM;
      }
      // Possible file extensions for raw PCM data
      else if(!strcasecmp(fileExtension, "pcm") || !strcasecmp(fileExtension, "raw") || !strcasecmp(fileExtension, "dat")) {
        return SAMPLE_SOURCE_TYPE_PCM;
      }
      else if(!strcasecmp(fileExtension, "aif") || !strcasecmp(fileExtension, "aiff")) {
        return SAMPLE_SOURCE_TYPE_AIFF;
      }
#if HAVE_LIBFLAC
      else if(!strcasecmp(fileExtension, "flac")) {
        return SAMPLE_SOURCE_TYPE_FLAC;
      }
#endif
#if HAVE_LIBLAME
      else if(!strcasecmp(fileExtension, "mp3")) {
        return SAMPLE_SOURCE_TYPE_MP3;
      }
#endif
#if HAVE_LIBVORBIS
      else if(!strcasecmp(fileExtension, "ogg")) {
        return SAMPLE_SOURCE_TYPE_OGG;
      }
#endif
      else if(!strcasecmp(fileExtension, "wav") || !strcasecmp(fileExtension, "wave")) {
        return SAMPLE_SOURCE_TYPE_WAVE;
      }
      else {
        logCritical("Sample source '%s' does not match any supported type", sampleSourceTypeString->data);
        return SAMPLE_SOURCE_TYPE_INVALID;
      }
    }
  }
  else {
    return SAMPLE_SOURCE_TYPE_INVALID;
  }
}
Example #13
0
void setLoggingColorSchemeWithString(const CharString colorSchemeName) {
  if(isCharStringEmpty(colorSchemeName)) {
    setLoggingColorScheme(COLOR_SCHEME_DEFAULT);
  }
  else if(isCharStringEqualToCString(colorSchemeName, "none", false)) {
    setLoggingColorScheme(COLOR_SCHEME_NONE);
  }
  else if(isCharStringEqualToCString(colorSchemeName, "dark", false)) {
    setLoggingColorScheme(COLOR_SCHEME_DARK);
  }
  else if(isCharStringEqualToCString(colorSchemeName, "light", false)) {
    setLoggingColorScheme(COLOR_SCHEME_LIGHT);
  }
  else {
    logCritical("Unknown color scheme '%s'", colorSchemeName->data);
    setLoggingColorScheme(COLOR_SCHEME_NONE);
  }
}
Example #14
0
boolByte programOptionsParseArgs(ProgramOptions self, int argc, char** argv) {
  int argumentIndex;
  for(argumentIndex = 1; argumentIndex < argc; argumentIndex++) {
    const ProgramOption option = _findProgramOption(self, argv[argumentIndex]);
    if(option == NULL) {
      logCritical("Invalid option '%s'", argv[argumentIndex]);
      return false;
    }
    else {
      if(_fillOptionArgument(option, &argumentIndex, argc, argv)) {
        option->enabled = true;
      }
      else {
        return false;
      }
    }
  }

  // If we make it to here, return true
  return true;
}
Example #15
0
void logFileError(const char* filename, const char* message) {
  logCritical("Could not parse file '%s'", filename);
  logCritical("Got error message message: %s", message);
  logPossibleBug("This file is either corrupt or was parsed incorrectly");
}
Example #16
0
int runIntegrationTest(const char *testName, CharString testArguments,
                       ReturnCode expectedResultCode,
                       const TestOutputType testOutputType,
                       const CharString mrsWatsonExePath,
                       const CharString resourcesPath) {
  int result = 0;
  int returnCode;
  ReturnCode resultCode;
  ChannelCount failedAnalysisChannel;
  SampleCount failedAnalysisFrame;

#if WINDOWS
  STARTUPINFOA startupInfo;
  PROCESS_INFORMATION processInfo;
#endif

  // Remove files from a previous test run
  File outputFolder = newFileWithPathCString(kApplicationRunnerOutputFolder);

  if (fileExists(outputFolder)) {
    _removeOutputFiles(testName);
  } else {
    fileCreate(outputFolder, kFileTypeDirectory);
  }

  freeFile(outputFolder);

  if (mrsWatsonExePath == NULL) {
    return -1;
  } else {
    File mrsWatsonExe = newFileWithPath(mrsWatsonExePath);
    boolByte mrsWatsonExeExists = fileExists(mrsWatsonExe);
    freeFile(mrsWatsonExe);

    if (!mrsWatsonExeExists) {
      freeCharString(testArguments);
      return -1;
    }
  }

  if (resourcesPath == NULL) {
    freeCharString(testArguments);
    return -1;
  } else {
    File resourcesFile = newFileWithPath(resourcesPath);
    boolByte resourcesExists = fileExists(resourcesFile);
    freeFile(resourcesFile);

    if (!resourcesExists) {
      freeCharString(testArguments);
      return -1;
    }
  }

  // Create the command line argument
  CharString arguments = newCharStringWithCapacity(kCharStringLengthLong);
  charStringAppendCString(arguments, "\"");
  charStringAppend(arguments, mrsWatsonExePath);
  charStringAppendCString(arguments, "\"");
  charStringAppendCString(arguments, " ");
  CharString defaultArguments;
  CharString outputFilename = getTestOutputFilename(testName, testOutputType);
  defaultArguments =
      _getDefaultArguments(testName, resourcesPath, outputFilename);
  charStringAppend(arguments, defaultArguments);
  freeCharString(defaultArguments);
  charStringAppendCString(arguments, " ");
  charStringAppend(arguments, testArguments);
  // Although testArguments is passed into this function (and hence, it would
  // generally not take ownership of it), in this case we free the arguments
  // here to make writing the test cases simpler and reduce the amount of
  // boilerplate code.
  freeCharString(testArguments);

#if WINDOWS
  memset(&startupInfo, 0, sizeof(startupInfo));
  memset(&processInfo, 0, sizeof(processInfo));
  startupInfo.cb = sizeof(startupInfo);
  returnCode = CreateProcessA(
      (LPCSTR)(mrsWatsonExePath->data), (LPSTR)(arguments->data), 0, 0, false,
      CREATE_DEFAULT_ERROR_MODE, 0, 0, &startupInfo, &processInfo);

  if (returnCode) {
    // TODO: Check return codes for these calls
    WaitForSingleObject(processInfo.hProcess,
                        kApplicationRunnerWaitTimeoutInMs);
    GetExitCodeProcess(processInfo.hProcess, (LPDWORD)&resultCode);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
  } else {
    logCritical("Could not launch process, got error %s",
                stringForLastError(GetLastError()));
    return 1;
  }

#else
  returnCode = system(arguments->data);
  resultCode = (ReturnCode)WEXITSTATUS(returnCode);
#endif
  freeCharString(arguments);

  if (resultCode == RETURN_CODE_FORK_FAILED ||
      resultCode == RETURN_CODE_SHELL_FAILED ||
      resultCode == RETURN_CODE_LAUNCH_FAILED_OTHER) {
    logCritical("Could not launch shell, got return code %d\n\
Please check the executable path specified in the --mrswatson-path argument.",
                resultCode);
    return 1;
  } else if (resultCode == expectedResultCode) {
    CharString failedAnalysisFunctionName = newCharString();
    if (testOutputType != kTestOutputNone) {
      if (analyzeFile(outputFilename->data, failedAnalysisFunctionName,
                      &failedAnalysisChannel, &failedAnalysisFrame)) {
        // TODO:
        //                if (!testEnvironment->results->keepFiles) {
        //                    _removeOutputFiles(testName);
        //                }
        result = 0;
      } else {
        fprintf(stderr,
                "Audio analysis check for %s failed at frame %lu, channel %d. ",
                failedAnalysisFunctionName->data, failedAnalysisFrame,
                failedAnalysisChannel);
        result = 1;
      }
    } else {
      result = 0;

      // TODO:
      //            if (!testEnvironment->results->keepFiles) {
      //                _removeOutputFiles(testName);
      //            }
    }
    freeCharString(failedAnalysisFunctionName);
  } else {
    fprintf(stderr, "Expected result code %d (%s), got %d (%s). ",
            expectedResultCode, _getResultCodeString(expectedResultCode),
            resultCode, _getResultCodeString(resultCode));
    result = 1;
  }

  freeCharString(outputFilename);
  return result;
}
Example #17
0
File: Mutex.cpp Project: CCJY/ACE
 void log (LogMessage *msg)
 {
   ACE_GUARD (MUTEX, mon, mutex_);
   if (msg->priority () == LogMessage::CRITICAL)
     logCritical (msg);
 }
Example #18
0
static void noui_InitMessage(const std::string& message)
{
    logCritical(Log::Bitcoin) << "init message:" << message;
}
Example #19
0
void errorReporterInitialize(ErrorReporter self)
{
    CharString infoText = newCharStringWithCString(kErrorReportInfoText);
    CharString wrappedInfoText;
    time_t now;
    size_t length;
    size_t i;

    printf("=== Starting error report ===\n");
    wrappedInfoText = charStringWrap(infoText, 0);
    // The second newline here is intentional
    printf("%s\n", wrappedInfoText->data);

    time(&now);
    self->started = true;

    snprintf(self->reportName->data, self->reportName->capacity,
             "MrsWatson Report %s", ctime(&now));
    // Trim the final newline character from this string if it exists
    length = strlen(self->reportName->data);

    if (self->reportName->data[length - 1] == '\n') {
        self->reportName->data[length - 1] = '\0';
        length--;
    }

    for (i = 0; i < length; i++) {
        if (!(charStringIsLetter(self->reportName, i) ||
                charStringIsNumber(self->reportName, i))) {
            self->reportName->data[i] = '-';
        }
    }

#if UNIX
    snprintf(self->desktopPath->data, self->desktopPath->capacity,
             "%s/Desktop", getenv("HOME"));
#elif WINDOWS
    SHGetFolderPathA(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, self->desktopPath->data);
#endif

    // Try to place the report on the user's desktop. However, if we cannot find
    // the desktop (which may occur with localized Linux installations, for instance),
    // then just dump it in the current directory instead.
    File desktopPath = newFileWithPath(self->desktopPath);
    File reportPath;

    if (!fileExists(desktopPath)) {
        logWarn("Could not find desktop location, placing error report in current directory instead");
        CharString currentDirString = fileGetCurrentDirectory();
        File currentDir = newFileWithPath(currentDirString);
        reportPath = newFileWithParent(currentDir, self->reportName);
        freeFile(currentDir);
        freeCharString(currentDirString);
    } else {
        reportPath = newFileWithParent(desktopPath, self->reportName);
        freeFile(desktopPath);
    }

    if (fileExists(reportPath)) {
        logCritical("The path '%s' already contains a previous error report. Please remove the report data and try again.");
    } else {
        fileCreate(reportPath, kFileTypeDirectory);
    }

    // Now we should have a real error report path
    charStringCopy(self->reportDirPath, reportPath->absolutePath);

    freeFile(reportPath);
    freeCharString(wrappedInfoText);
    freeCharString(infoText);
}