Пример #1
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WriteImages::dataCheck()
{
  setErrorCondition(0);

  getDataContainerArray()->getPrereqGeometryFromDataContainer<ImageGeom, AbstractFilter>(this, getColorsArrayPath().getDataContainerName());

  QDir dir(getOutputPath());

  if (getOutputPath().isEmpty() == true)
  {
    setErrorCondition(-1003);
    notifyErrorMessage(getHumanLabel(), "The output directory must be set", getErrorCondition());
  }
  else if (dir.exists() == false)
  {
    QString ss = QObject::tr("The output directory path does not exist. DREAM.3D will attempt to create this path during execution");
    notifyWarningMessage(getHumanLabel(), ss, -1);
  }

  IDataArray::Pointer iDa = getDataContainerArray()->getPrereqIDataArrayFromPath<IDataArray, AbstractFilter>(this, getColorsArrayPath());
  if (getErrorCondition() < 0) { return; }

  QVector<size_t> cDims = iDa->getComponentDimensions();

  if (cDims[0] == 1)
  {
    m_ColorsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<uint8_t>, AbstractFilter>(this, getColorsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if (NULL != m_ColorsPtr.lock().get()) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_Colors = m_ColorsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  }
  else if (cDims[0] == 3)
  {
    m_ColorsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<uint8_t>, AbstractFilter>(this, getColorsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if (NULL != m_ColorsPtr.lock().get()) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_Colors = m_ColorsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  }
  else if (cDims[0] == 4)
  {
    m_ColorsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<uint8_t>, AbstractFilter>(this, getColorsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if (NULL != m_ColorsPtr.lock().get()) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_Colors = m_ColorsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  }
  else
  {
    setErrorCondition(-1006);
    notifyErrorMessage(getHumanLabel(), "Number of components must be 1 (grayscale), 3 (RGB) or 4 (ARGB) arrays", getErrorCondition());
  }
}
Пример #2
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
/* FILTER_WIDGETCODEGEN_AUTO_GENERATED_CODE BEGIN*/

  reader->openFilterGroup(this, index);
  setStlFilePrefix( reader->readValue("StlFilePrefix", getStlFilePrefix()) );
  setMaxIterations( reader->readValue("MaxIterations", getMaxIterations()) );
  setMisorientationTolerance( reader->readValue("MisorientationTolerance", getMisorientationTolerance()) );
  setInputFile( reader->readValue("InputFile", getInputFile()) );
  setInputPath( reader->readValue("InputPath", getInputPath()) );
  setOutputFile( reader->readValue("OutputFile", getOutputFile()) );
  setOutputPath( reader->readValue("OutputPath", getOutputPath()) );
  setWriteAlignmentShifts( reader->readValue("WriteAlignmentShifts", getWriteAlignmentShifts()) );
  setConversionType( reader->readValue("ConversionType", getConversionType()) );
  setDimensions( reader->readValue("Dimensions", getDimensions()) );
  setOrigin( reader->readValue("Origin", getOrigin()) );
  setCrystalSymmetryRotations( reader->readValue("CrystalSymmetryRotations", getCrystalSymmetryRotations()) );

  setSelectedVoxelCellArrayName( reader->readValue("SelectedVoxelCellArrayName", getSelectedVoxelCellArrayName()) );
  setSelectedVoxelFieldArrayName( reader->readValue("SelectedVoxelFieldArrayName", getSelectedVoxelFieldArrayName()) );
  setSelectedVoxelEnsembleArrayName( reader->readValue("SelectedVoxelEnsembleArrayName", getSelectedVoxelEnsembleArrayName()) );
  setSelectedSurfaceMeshPointArrayName( reader->readValue("SelectedSurfaceMeshPointArrayName", getSelectedSurfaceMeshPointArrayName()) );
  setSelectedSurfaceMeshFaceArrayName( reader->readValue("SelectedSurfaceMeshFaceArrayName", getSelectedSurfaceMeshFaceArrayName()) );
  setSelectedSurfaceMeshEdgeArrayName( reader->readValue("SelectedSurfaceMeshEdgeArrayName", getSelectedSurfaceMeshEdgeArrayName()) );
  setSelectedSolidMeshPointArrayName( reader->readValue("SelectedSolidMeshPointArrayName", getSelectedSolidMeshPointArrayName()) );
  setSelectedSolidMeshFaceArrayName( reader->readValue("SelectedSolidMeshFaceArrayName", getSelectedSolidMeshFaceArrayName()) );
  setSelectedSolidMeshEdgeArrayName( reader->readValue("SelectedSolidMeshEdgeArrayName", getSelectedSolidMeshEdgeArrayName()) );


  setStrVector( reader->readValue("StrVector", getStrVector() ) );
  reader->closeFilterGroup();
}
Пример #3
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int GenericExample::writeFilterParameters(AbstractFilterParametersWriter* writer, int index)
{
  writer->openFilterGroup(this, index);
  /* Place code that will write the inputs values into a file. reference the
   AbstractFilterParametersWriter class for the proper API to use. */
  writer->writeValue("StlFilePrefix", getStlFilePrefix());
  writer->writeValue("MaxIterations", getMaxIterations());
  writer->writeValue("MisorientationTolerance", getMisorientationTolerance());
  writer->writeValue("InputFile", getInputFile());
  writer->writeValue("InputPath", getInputPath());
  writer->writeValue("OutputFile", getOutputFile());
  writer->writeValue("OutputPath", getOutputPath());
  writer->writeValue("WriteAlignmentShifts", getWriteAlignmentShifts());
  writer->writeValue("ConversionType", getConversionType());
  writer->writeValue("Dimensions", getDimensions());
  writer->writeValue("Origin", getOrigin());
  writer->writeValue("CrystalSymmetryRotations", getCrystalSymmetryRotations());

  writer->writeValue("SelectedVoxelCellArrayName", getSelectedVoxelCellArrayName());
  writer->writeValue("SelectedVoxelFieldArrayName", getSelectedVoxelFieldArrayName());
  writer->writeValue("SelectedVoxelEnsembleArrayName", getSelectedVoxelEnsembleArrayName());
  writer->writeValue("SelectedSurfaceMeshPointArrayName", getSelectedSurfaceMeshPointArrayName());
  writer->writeValue("SelectedSurfaceMeshFaceArrayName", getSelectedSurfaceMeshFaceArrayName());
  writer->writeValue("SelectedSurfaceMeshEdgeArrayName", getSelectedSurfaceMeshEdgeArrayName());
  writer->writeValue("SelectedSolidMeshPointArrayName", getSelectedSolidMeshPointArrayName());
  writer->writeValue("SelectedSolidMeshFaceArrayName", getSelectedSolidMeshFaceArrayName());
  writer->writeValue("SelectedSolidMeshEdgeArrayName", getSelectedSolidMeshEdgeArrayName());

  writer->writeValue("StrVector", getStrVector());

  writer->closeFilterGroup();
  return ++index;
}
Пример #4
0
void litiv::IDatasetEvaluator_<litiv::eDatasetEval_None>::writeEvalReport() const {
    if(getBatches(false).empty()) {
        std::cout << "No report to write for dataset '" << getName() << "', skipping." << std::endl;
        return;
    }
    for(const auto& pGroupIter : getBatches(true))
        pGroupIter->shared_from_this_cast<const IDataReporter_<eDatasetEval_None>>(true)->IDataReporter_<eDatasetEval_None>::writeEvalReport();
    std::ofstream oMetricsOutput(getOutputPath()+"/overall.txt");
    if(oMetricsOutput.is_open()) {
        oMetricsOutput << std::fixed;
        oMetricsOutput << "Default evaluation report for dataset '" << getName() << "' :\n\n";
        oMetricsOutput << "            |   Packets  |   Seconds  |     Hz     \n";
        oMetricsOutput << "------------|------------|------------|------------\n";
        size_t nOverallPacketCount = 0;
        double dOverallTimeElapsed = 0.0;
        for(const auto& pGroupIter : getBatches(true)) {
            oMetricsOutput << pGroupIter->shared_from_this_cast<const IDataReporter_<eDatasetEval_None>>(true)->IDataReporter_<eDatasetEval_None>::writeInlineEvalReport(0);
            nOverallPacketCount += pGroupIter->getTotPackets();
            dOverallTimeElapsed += pGroupIter->getProcessTime();
        }
        oMetricsOutput << "------------|------------|------------|------------\n";
        oMetricsOutput << "     overall|" <<
                          std::setw(12) << nOverallPacketCount << "|" <<
                          std::setw(12) << dOverallTimeElapsed << "|" <<
                          std::setw(12) << nOverallPacketCount/dOverallTimeElapsed << "\n";
        oMetricsOutput << CxxUtils::getLogStamp();
    }
}
Пример #5
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void TestFilter::writeFilterParameters(AbstractFilterParametersWriter* writer)

{
 /* Place code that will write the inputs values into a file. reference the
   AbstractFilterParametersWriter class for the proper API to use. */
  writer->writeValue("StlFilePrefix", getStlFilePrefix() );
  writer->writeValue("MaxIterations", getMaxIterations() );
  writer->writeValue("MisorientationTolerance", getMisorientationTolerance() );
  writer->writeValue("InputFile", getInputFile() );
  writer->writeValue("InputPath", getInputPath() );
  writer->writeValue("OutputFile", getOutputFile() );
  writer->writeValue("OutputPath", getOutputPath() );
  writer->writeValue("WriteAlignmentShifts", getWriteAlignmentShifts() );
  writer->writeValue("ConversionType", getConversionType() );
  writer->writeValue("SelectedCellArrayName", getSelectedCellArrayName() );
  writer->writeValue("SelectedFieldArrayName", getSelectedFieldArrayName() );
  writer->writeValue("SelectedEnsembleArrayName", getSelectedEnsembleArrayName() );
  writer->writeValue("SurfaceMeshPointArrayName", getSurfaceMeshPointArrayName() );
  writer->writeValue("SurfaceMeshFaceArrayName", getSurfaceMeshFaceArrayName() );
  writer->writeValue("SurfaceMeshEdgeArrayName", getSurfaceMeshEdgeArrayName() );
  writer->writeValue("SolidMeshPointArrayName", getSolidMeshPointArrayName() );
  writer->writeValue("SolidMeshFaceArrayName", getSolidMeshFaceArrayName() );
  writer->writeValue("SolidMeshEdgeArrayName", getSolidMeshEdgeArrayName() );
  writer->writeValue("Dimensions", getDimensions() );
  writer->writeValue("Origin", getOrigin() );

  writer->writeValue("CellComparisonInputs", m_CellComparisonInputs);
  writer->writeValue("AxisAngleRotations", m_AxisAngleRotations);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::setupFilterParameters()
{
  FilterParameterVector parameters;

  {
    ChoiceFilterParameter::Pointer parameter = ChoiceFilterParameter::New();
    parameter->setHumanLabel("Image Format");
    parameter->setPropertyName("ImageFormat");

    QVector<QString> choices;
    choices.push_back("tif");
    choices.push_back("bmp");
    choices.push_back("png");
    parameter->setChoices(choices);
    parameter->setCategory(FilterParameter::Parameter);
    parameters.push_back(parameter);
  }
  parameters.push_back(IntFilterParameter::New("Lambert Image Size (Pixels)", "LambertSize", getLambertSize(), FilterParameter::Parameter));
  parameters.push_back(IntFilterParameter::New("Number of Colors", "NumColors", getNumColors(), FilterParameter::Parameter));
  {
    ChoiceFilterParameter::Pointer parameter = ChoiceFilterParameter::New();
    parameter->setHumanLabel("Image Layout");
    parameter->setPropertyName("ImageLayout");

    QVector<QString> choices;
    choices.push_back("Horizontal");
    choices.push_back("Vertical");
    choices.push_back("Square");
    parameter->setChoices(choices);
    parameter->setCategory(FilterParameter::Parameter);
    parameters.push_back(parameter);
  }
  parameters.push_back(StringFilterParameter::New("Image Prefix", "ImagePrefix", getImagePrefix(), FilterParameter::Parameter));
  parameters.push_back(OutputPathFilterParameter::New("Output Path", "OutputPath", getOutputPath(), FilterParameter::Parameter));
  parameters.push_back(IntFilterParameter::New("Image Size (Square Pixels)", "ImageSize", getImageSize(), FilterParameter::Parameter));
  parameters.push_back(SeparatorFilterParameter::New("Cell Data", FilterParameter::RequiredArray));
  {
    DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, 3, SIMPL::AttributeMatrixType::Cell, SIMPL::GeometryType::ImageGeometry);
    parameters.push_back(DataArraySelectionFilterParameter::New("Euler Angles", "CellEulerAnglesArrayPath", getCellEulerAnglesArrayPath(), FilterParameter::RequiredArray, req));
  }
  {
    DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Int32, 1, SIMPL::AttributeMatrixType::Cell, SIMPL::GeometryType::ImageGeometry);
    parameters.push_back(DataArraySelectionFilterParameter::New("Phases", "CellPhasesArrayPath", getCellPhasesArrayPath(), FilterParameter::RequiredArray, req));
  }
  {
    DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Bool, 1, SIMPL::AttributeMatrixType::Cell, SIMPL::GeometryType::ImageGeometry);
    parameters.push_back(DataArraySelectionFilterParameter::New("Mask", "GoodVoxelsArrayPath", getGoodVoxelsArrayPath(), FilterParameter::RequiredArray, req));
  }
  parameters.push_back(SeparatorFilterParameter::New("Cell Ensemble Data", FilterParameter::RequiredArray));
  {
    DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::UInt32, 1, SIMPL::AttributeMatrixType::CellEnsemble, SIMPL::GeometryType::ImageGeometry);
    parameters.push_back(DataArraySelectionFilterParameter::New("Crystal Structures", "CrystalStructuresArrayPath", getCrystalStructuresArrayPath(), FilterParameter::RequiredArray, req));
  }
  setFilterParameters(parameters);
}
Пример #7
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WriteImages::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
  reader->openFilterGroup(this, index);
  setImagePrefix( reader->readString("ImagePrefix", getImagePrefix()) );
  setFilePrefix( reader->readValue("FilePrefix", getFilePrefix()) );
  setOutputPath( reader->readString("OutputPath", getOutputPath()) );
  setColorsArrayPath( reader->readDataArrayPath("ColorsArrayPath", getColorsArrayPath()) );
  setImageFormat( reader->readValue("ImageFormat", getImageFormat()) );
  setPlane(reader->readValue("Plane", getPlane()));
  reader->closeFilterGroup();
}
Пример #8
0
void
Downloader::reset()
{
    _videoBytes = 0;
    _soundBytes = 0;
    _bytesTotal = 0;
    _bytesDownloaded = 0;
    _videoBytesReceived = 0;
    _soundBytesReceived = 0;
    _lastBytesDownloaded = 0;
    _eta = 0;
    _kbps = 0;
    _percent = 0;
    _cancelationPending = false;
    _convertPid = 0;

    QString filename = "";

    bool hasArtist = !_download.artist.isEmpty();
    bool hasTitle = !_download.title.isEmpty();
    bool hasCoartist = !_download.coartist.isEmpty();

    if (hasArtist && hasTitle)
    {
        filename += _download.artist;

        if (hasCoartist) {
            filename += " ft. " + _download.coartist;
        }

        filename += " - " + _download.title;
    }
    else
    {
        filename = _download.videoTitle;
    }

    _download.filename = filename;

    QString extension = _download.outputFormat.extension;
    QString savePath = getOutputPath(filename, extension);

    if (QFile::exists(savePath))
    {
        setStatus(Complete);
        setProgress(0, 0, 100);
    }
    else
    {
        setStatus(Ready);
        setProgress(0, 0, 0);
    }
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::dataCheck()
{
  setErrorCondition(0);

  QDir path(getOutputPath());

  getDataContainerArray()->getPrereqGeometryFromDataContainer<ImageGeom, AbstractFilter>(this, getCellPhasesArrayPath().getDataContainerName());

  if (m_OutputPath.isEmpty() == true)
  {
    setErrorCondition(-1003);
    notifyErrorMessage(getHumanLabel(), "The output directory must be set", getErrorCondition());
  }
  else if (path.exists() == false)
  {
    QString ss = QObject::tr("The directory path for the output file does not exist. DREAM.3D will attempt to create this path during execution of the filter");
    notifyWarningMessage(getHumanLabel(), ss, -1);
  }

  QVector<DataArrayPath> dataArrayPaths;

  QVector<size_t> cDims(1, 3);
  m_CellEulerAnglesPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<float>, AbstractFilter>(this, getCellEulerAnglesArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CellEulerAnglesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CellEulerAngles = m_CellEulerAnglesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  if(getErrorCondition() >= 0) { dataArrayPaths.push_back(getCellEulerAnglesArrayPath()); }

  cDims[0] = 1;
  m_CellPhasesPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter>(this, getCellPhasesArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CellPhasesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CellPhases = m_CellPhasesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  if(getErrorCondition() >= 0) { dataArrayPaths.push_back(getCellPhasesArrayPath()); }

  m_CrystalStructuresPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<uint32_t>, AbstractFilter>(this, getCrystalStructuresArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_CrystalStructuresPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_CrystalStructures = m_CrystalStructuresPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */

  // The good voxels array is optional, If it is available we are going to use it, otherwise we are going to create it
  cDims[0] = 1;
  m_GoodVoxelsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<bool>, AbstractFilter>(this, getGoodVoxelsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if (NULL != m_GoodVoxelsPtr.lock().get())
  {
    if( NULL != m_GoodVoxelsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_GoodVoxels = m_GoodVoxelsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
    if(getErrorCondition() >= 0) { dataArrayPaths.push_back(getGoodVoxelsArrayPath()); }
  }
  else
  {
    m_GoodVoxels = NULL;
  }

  getDataContainerArray()->validateNumberOfTuples<AbstractFilter>(this, dataArrayPaths);
}
Пример #10
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
  reader->openFilterGroup(this, index);
  setGoodVoxelsArrayPath(reader->readDataArrayPath("GoodVoxelsArrayPath", getGoodVoxelsArrayPath() ) );
  setCrystalStructuresArrayPath(reader->readDataArrayPath("CrystalStructuresArrayPath", getCrystalStructuresArrayPath() ) );
  setCellPhasesArrayPath(reader->readDataArrayPath("CellPhasesArrayPath", getCellPhasesArrayPath() ) );
  setCellEulerAnglesArrayPath(reader->readDataArrayPath("CellEulerAnglesArrayPath", getCellEulerAnglesArrayPath() ) );
  setImagePrefix( reader->readString("ImagePrefix", getImagePrefix()));
  setOutputPath( reader->readString("OutputPath", getOutputPath()));
  setImageFormat( reader->readValue("ImageFormat", getImageFormat()));
  setImageLayout( reader->readValue("ImageLayout", getImageLayout()));
  setImageSize( reader->readValue("ImageSize", getImageSize()));
  setLambertSize( reader->readValue("LambertSize", getLambertSize()));
  reader->closeFilterGroup();
}
Пример #11
0
void litiv::IDataReporter_<litiv::eDatasetEval_None>::writeEvalReport() const {
    if(!getTotPackets()) {
        std::cout << "No report to write for '" << getName() << "', skipping..." << std::endl;
        return;
    }
    else if(isGroup() && !isBare())
        for(const auto& pBatch : getBatches(true))
            pBatch->writeEvalReport();
    std::ofstream oMetricsOutput(PlatformUtils::AddDirSlashIfMissing(getOutputPath())+"../"+getName()+".txt");
    if(oMetricsOutput.is_open()) {
        oMetricsOutput << std::fixed;
        oMetricsOutput << "Default evaluation report for '" << getName() << "' :\n\n";
        oMetricsOutput << "            |   Packets  |   Seconds  |     Hz     \n";
        oMetricsOutput << "------------|------------|------------|------------\n";
        oMetricsOutput << IDataReporter_<eDatasetEval_None>::writeInlineEvalReport(0);
        oMetricsOutput << CxxUtils::getLogStamp();
    }
}
Пример #12
0
void litiv::IDatasetEvaluator_<litiv::eDatasetEval_BinaryClassifier>::writeEvalReport() const {
    if(getBatches(false).empty() || !isUsingEvaluator()) {
        IDatasetEvaluator_<litiv::eDatasetEval_None>::writeEvalReport();
        return;
    }
    for(const auto& pGroupIter : getBatches(true))
        pGroupIter->shared_from_this_cast<const IDataReporter_<eDatasetEval_BinaryClassifier>>(true)->IDataReporter_<eDatasetEval_BinaryClassifier>::writeEvalReport();
    IMetricsCalculatorConstPtr pMetrics = getMetrics(true);
    lvAssert(pMetrics.get());
    const BinClassifMetricsCalculator& oMetrics = dynamic_cast<const BinClassifMetricsCalculator&>(*pMetrics.get());
    std::cout << CxxUtils::clampString(getName(),12) << " => Rcl=" << std::fixed << std::setprecision(4) << oMetrics.dRecall << " Prc=" << oMetrics.dPrecision << " FM=" << oMetrics.dFMeasure << " MCC=" << oMetrics.dMCC << std::endl;
    std::ofstream oMetricsOutput(getOutputPath()+"/overall.txt");
    if(oMetricsOutput.is_open()) {
        oMetricsOutput << std::fixed;
        oMetricsOutput << "Video segmentation evaluation report for dataset '" << getName() << "' :\n\n";
        oMetricsOutput << "            |     Rcl    |     Spc    |     FPR    |     FNR    |     PBC    |     Prc    |     FM     |     MCC    \n";
        oMetricsOutput << "------------|------------|------------|------------|------------|------------|------------|------------|------------\n";
        size_t nOverallPacketCount = 0;
        double dOverallTimeElapsed = 0.0;
        for(const auto& pGroupIter : getBatches(true)) {
            oMetricsOutput << pGroupIter->shared_from_this_cast<const IDataReporter_<eDatasetEval_BinaryClassifier>>(true)->IDataReporter_<eDatasetEval_BinaryClassifier>::writeInlineEvalReport(0);
            nOverallPacketCount += pGroupIter->getTotPackets();
            dOverallTimeElapsed += pGroupIter->getProcessTime();
        }
        oMetricsOutput << "------------|------------|------------|------------|------------|------------|------------|------------|------------\n";
        oMetricsOutput << "     overall|" <<
                          std::setw(12) << oMetrics.dRecall << "|" <<
                          std::setw(12) << oMetrics.dSpecificity << "|" <<
                          std::setw(12) << oMetrics.dFPR << "|" <<
                          std::setw(12) << oMetrics.dFNR << "|" <<
                          std::setw(12) << oMetrics.dPBC << "|" <<
                          std::setw(12) << oMetrics.dPrecision << "|" <<
                          std::setw(12) << oMetrics.dFMeasure << "|" <<
                          std::setw(12) << oMetrics.dMCC << "\n";
        oMetricsOutput << "\nHz: " << nOverallPacketCount/dOverallTimeElapsed << "\n";
        oMetricsOutput << CxxUtils::getLogStamp();
    }
}
Пример #13
0
void litiv::IDataReporter_<litiv::eDatasetEval_BinaryClassifier>::writeEvalReport() const {
    if(!getTotPackets() || !getDatasetInfo()->isUsingEvaluator()) {
        IDataReporter_<litiv::eDatasetEval_None>::writeEvalReport();
        return;
    }
    else if(isGroup() && !isBare())
        for(const auto& pBatch : getBatches(true))
            pBatch->writeEvalReport();
    IMetricsCalculatorConstPtr pMetrics = getMetrics(true);
    lvAssert(pMetrics.get());
    const BinClassifMetricsCalculator& oMetrics = dynamic_cast<const BinClassifMetricsCalculator&>(*pMetrics.get());;
    std::cout << "\t" << CxxUtils::clampString(std::string(size_t(!isGroup()),'>')+getName(),12) << " => Rcl=" << std::fixed << std::setprecision(4) << oMetrics.dRecall << " Prc=" << oMetrics.dPrecision << " FM=" << oMetrics.dFMeasure << " MCC=" << oMetrics.dMCC << std::endl;
    std::ofstream oMetricsOutput(PlatformUtils::AddDirSlashIfMissing(getOutputPath())+"../"+getName()+".txt");
    if(oMetricsOutput.is_open()) {
        oMetricsOutput << std::fixed;
        oMetricsOutput << "Video segmentation evaluation report for '" << getName() << "' :\n\n";
        oMetricsOutput << "            |     Rcl    |     Spc    |     FPR    |     FNR    |     PBC    |     Prc    |     FM     |     MCC    \n";
        oMetricsOutput << "------------|------------|------------|------------|------------|------------|------------|------------|------------\n";
        oMetricsOutput << IDataReporter_<eDatasetEval_BinaryClassifier>::writeInlineEvalReport(0);
        oMetricsOutput << "\nHz: " << getTotPackets()/getProcessTime() << "\n";
        oMetricsOutput << CxxUtils::getLogStamp();
    }
}
Пример #14
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::execute()
{
  setErrorCondition(0);
  dataCheck();
  if(getErrorCondition() < 0) { return; }

  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(m_CellPhasesArrayPath.getDataContainerName());

  size_t dims[3] = { 0, 0, 0 };
  m->getGeometryAs<ImageGeom>()->getDimensions(dims);

  // Make sure any directory path is also available as the user may have just typed
  // in a path without actually creating the full path
  QDir path(getOutputPath());

  if (!path.mkpath(".") )
  {
    QString ss = QObject::tr("Error creating parent path '%1'").arg(path.absolutePath());
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  bool missingGoodVoxels = true;

  if (NULL != m_GoodVoxels)
  {
    missingGoodVoxels = false;
  }

  // Find how many phases we have by getting the number of Crystal Structures
  size_t numPoints = m->getGeometryAs<ImageGeom>()->getNumberOfElements();
  size_t numPhases = m_CrystalStructuresPtr.lock()->getNumberOfTuples();

  // Loop over all the voxels gathering the Eulers for a specific phase into an array
  for (size_t phase = 1; phase < numPhases; ++phase)
  {
    size_t count = 0;
    // First find out how many voxels we are going to have. This is probably faster to loop twice than to
    // keep allocating memory everytime we find one.
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          count++;
        }
      }
    }
    QVector<size_t> eulerCompDim(1, 3);
    FloatArrayType::Pointer subEulers = FloatArrayType::CreateArray(count, eulerCompDim, "Eulers_Per_Phase");
    subEulers->initializeWithValue(std::numeric_limits<float>::signaling_NaN());
    float* eu = subEulers->getPointer(0);

    // Now loop through the eulers again and this time add them to the subEulers Array
    count = 0;
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          eu[count * 3] = m_CellEulerAngles[i * 3];
          eu[count * 3 + 1] = m_CellEulerAngles[i * 3 + 1];
          eu[count * 3 + 2] = m_CellEulerAngles[i * 3 + 2];
          count++;
        }
      }
    }
    if (subEulers->getNumberOfTuples() == 0) { continue; } // Skip because we have no Pole Figure data

    QVector<UInt8ArrayType::Pointer> figures;

    PoleFigureConfiguration_t config;
    config.eulers = subEulers.get();
    config.imageDim = getImageSize();
    config.lambertDim = getLambertSize();
    config.numColors = getNumColors();

    QString label("Phase_");
    label.append(QString::number(phase));

    QString ss = QObject::tr("Generating Pole Figures for Phase %1").arg(phase);
    notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);

    switch(m_CrystalStructures[phase])
    {
      case Ebsd::CrystalStructure::Cubic_High:
        figures = makePoleFigures<CubicOps>(config);
        break;
      case Ebsd::CrystalStructure::Cubic_Low:
        figures = makePoleFigures<CubicLowOps>(config);
        break;
      case Ebsd::CrystalStructure::Hexagonal_High:
        figures = makePoleFigures<HexagonalOps>(config);
        break;
      case Ebsd::CrystalStructure::Hexagonal_Low:
        figures = makePoleFigures<HexagonalLowOps>(config);
        break;
      case Ebsd::CrystalStructure::Trigonal_High:
        //   figures = makePoleFigures<TrigonalOps>(config);
        notifyWarningMessage(getHumanLabel(), "Trigonal High Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Trigonal_Low:
        //  figures = makePoleFigures<TrigonalLowOps>(config);
        notifyWarningMessage(getHumanLabel(), "Trigonal Low Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Tetragonal_High:
        //  figures = makePoleFigures<TetragonalOps>(config);
        notifyWarningMessage(getHumanLabel(), "Tetragonal High Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Tetragonal_Low:
        //  figures = makePoleFigures<TetragonalLowOps>(config);
        notifyWarningMessage(getHumanLabel(), "Tetragonal Low Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::OrthoRhombic:
        figures = makePoleFigures<OrthoRhombicOps>(config);
        break;
      case Ebsd::CrystalStructure::Monoclinic:
        figures = makePoleFigures<MonoclinicOps>(config);
        break;
      case Ebsd::CrystalStructure::Triclinic:
        figures = makePoleFigures<TriclinicOps>(config);
        break;
      default:
        break;

    }

    if (figures.size() == 3)
    {
      QImage combinedImage = PoleFigureImageUtilities::Create3ImagePoleFigure(figures[0].get(), figures[1].get(), figures[2].get(), config, getImageLayout());
      writeImage(combinedImage, label);
    }
  }

  /* Let the GUI know we are done with this filter */
  notifyStatusMessage(getHumanLabel(), "Complete");
}
Пример #15
0
		virtual int execute(const string &command, ParameterList &params, unsigned int phase)
		{
			if (command == "-i" || command == "--input") {
				if (params.size()==0) {
					cerr << "Warning: " << command << " needs a file path to follow. Ignoring." << endl;
					return 0;
				} else {
					getInputPath() = params[0];
					params.erase(params.begin());
					return 0;
				}
			} else if (command == "-o" || command == "--output") {
				if (params.size()==0) {
					cerr << "Warning: " << command << " needs a file path to follow. Ignoring." << endl;
					return 0;
				} else {
					getOutputPath() = params[0];
					params.erase(params.begin());
					return 0;
				}
			} else if (command == "-c" || command == "--convert") {
				if (params.size() < 3) {
					cerr << "Fatal: " << command << " needs three arguments:\n"
						 << "\tmesher <...> " << command << " {XMesh|BFXM|Wavefront} (XMesh|BFXM|Wafefront|Ogre) (create|append|optimize)\n"
						 << "\n"
						 << "Do \"mesher --help convert\" for details" << endl;
					return 1;
				} else {
					if (phase == 0) {
						// Do nothing in phase 0.
						return 0;
					} else if (phase == 1) {
						ConversionImplList& registry = getRegistry();
						ConversionImpl::RetCodeEnum rc = ConversionImpl::RC_NOT_IMPLEMENTED;
						for (ConversionImplList::iterator cit=registry.begin(); (rc == ConversionImpl::RC_NOT_IMPLEMENTED)&&(cit!=registry.end()); ++cit) {
							rc = cit->second->convert(params[0],params[1],params[2]);
						}
						if (rc == ConversionImpl::RC_NOT_IMPLEMENTED) {
							cerr << "Error: " << params[2] << " from " << params[0] << " to " << params[1] << " unimplemneted" << endl;
							return ConversionImpl::RC_NOT_IMPLEMENTED;
						} else if (rc == ConversionImpl::RC_OK) {
							params.erase(params.begin(),params.begin()+3);
							return ConversionImpl::RC_OK;
						} else {
							cerr << "Error: ";
							switch (rc) {
							case ConversionImpl::RC_INVALID_PARAMS: 
								cerr << "Invalid parameters specified for " << command; 
								break;
							case ConversionImpl::RC_INVALID_INPUT:  
								cerr << "Invalid input"; 
								break;
							case ConversionImpl::RC_INTERNAL_ERROR: 
								cerr << "Internal error"; 
								break;
							default:                
								cerr << "(see above messages)"; 
								break;
							}
							cerr << endl;
							return rc;
						}
					} else {
						cerr << "Warning: ConvertHandler::execute(): received an unexpected phase. Ignoring." << endl;
						return 0;
					}
				}
			} else if (command.length()>2 && command[0]=='-' && command[1]!='-') {
				string::size_type eq = command.rfind('=');
				string::size_type nn = ((eq==string::npos)?string::npos:eq-1);
				string option = command.substr(1,nn);
				if (mOptions.count(option)) {				
					string value  = ((eq!=string::npos)?command.substr(eq+1):string("1"));
					AliasList::const_iterator ait = mAliases.find(option);
					if (ait != mAliases.end())
						option = ait->second;
					getNamedOption(option) = value;
					return 0;
				} else {
					cerr << "Fatal: Internal error - ConvertHandler::execute() received an unrecognized option" << endl;
					return 1;
				}
			} else {
				cerr << "Fatal: Internal error - ConvertHandler::execute() received an unrecognized command" << endl;
				return 1;
			}
		}
Пример #16
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WriteImages::setupFilterParameters()
{
  FilterParameterVector parameters;
  {
    ChoiceFilterParameter::Pointer parameter = ChoiceFilterParameter::New();
    parameter->setHumanLabel("Image Format");
    parameter->setPropertyName("ImageFormat");

    QVector<QString> choices;
    choices.push_back("tif");
    choices.push_back("bmp");
    choices.push_back("png");
    parameter->setChoices(choices);
    parameter->setCategory(FilterParameter::Parameter);
    parameters.push_back(parameter);
  }
  {
    ChoiceFilterParameter::Pointer parameter = ChoiceFilterParameter::New();
    parameter->setHumanLabel("Plane");
    parameter->setPropertyName("Plane");

    QVector<QString> choices;
    choices.push_back("XY");
    choices.push_back("XZ");
    choices.push_back("YZ");
    parameter->setChoices(choices);
    parameter->setCategory(FilterParameter::Parameter);
    parameters.push_back(parameter);
  }
  {
    QStringList linkedProps;
    linkedProps << "ImagePrefix";
    parameters.push_back(LinkedBooleanFilterParameter::New("File Prefix", "FilePrefix", getFilePrefix(), linkedProps, FilterParameter::Parameter));
  }
  parameters.push_back(OutputPathFilterParameter::New("Output Directory Path", "OutputPath", getOutputPath(), FilterParameter::Parameter));
  parameters.push_back(StringFilterParameter::New("Image File Prefix", "ImagePrefix", getImagePrefix(), FilterParameter::Parameter));
  parameters.push_back(SeparatorFilterParameter::New("Cell Data", FilterParameter::RequiredArray));
  parameters.push_back(DataArraySelectionFilterParameter::New("Color Data", "ColorsArrayPath", getColorsArrayPath(), FilterParameter::RequiredArray));
  setFilterParameters(parameters);
}
// Generate a PNG file by utilizing the LibreOffice conversion tool
void OutputGenerator::generatePNG()
{
	MSG(GROUP::DEBUG, DEBUG::FUNCTIONCALL) << "OutputGenerator::generatePNG()";
	MSG(GROUP::INFO) << "Generating PNG file";

	// Initialize common vars
	std::string arg = "\"\"";
	std::string SOFFICE_path = cfg.getString("PATH.soffice");	// Get path to the StarOffice / Libre Office installation
	std::string outputPath = cfg.getString("PNG.outputPath");	// If the user didn't specify a output path via command line arg read the default from config file

	// Get path to put output files in
	std::string fPath = getOutputPath(mSourcePath);

	#ifdef _WIN32
		if (!fPath.empty())
			fPath = cleanPath(fPath) + "\\" + cleanPath(cfg.getString("FODG.outputPath")) + "\\" + mSourceName;
		else
			fPath = cleanPath(cfg.getString("FODG.outputPath")) + "\\" + mSourceName;
	#else
		if (!fPath.empty())
			fPath = cleanPath(fPath) + "/" + cleanPath(cfg.getString("FODG.outputPath")) + "/" + mSourceName;
		else
			fPath = cleanPath(cfg.getString("FODG.outputPath")) + "/" + mSourceName;
	#endif
	
	MSG(GROUP::DEBUG, DEBUG::RESULT) << "PNG.outputPath = " << outputPath;

	// Check if a SO-Installation was specified
	if (SOFFICE_path.empty())
	{
		MSG(GROUP::WARNING) << "PATH.soffice not specified. Please edit your VEC.conf";
	}
	else
	{
		#ifdef _WIN32
			// Build the arg string to pass
			arg += SOFFICE_path + "\" --headless --convert-to png:\"draw_png_Export\" \"" + fPath + ".fodg\" --outdir \"";
		#else
			// Build the arg string to pass
			arg = "\'";
			arg += SOFFICE_path + "\' --headless  --convert-to png:\"draw_png_Export\" \'" + fPath + ".fodg\' --outdir \'";
		#endif			
		
		// If no output path was set via cmd line argument or config file use directory of the executable
		if (outputPath.empty())
			arg += cleanPath(cfg.getString("FODG.outputPath"));
		else
			arg += cleanPath(outputPath);

		#ifdef _WIN32
			// End arg string with quotes
			arg += "\"\"";
		#else		
			// End arg string with hard quotes
			arg += "\'";
		#endif			

		MSG(GROUP::INFO) << TAB << "SOFFICE call = " << arg;
		
		// Execute arg string
		system(arg.c_str());
	}
	return;
}
Пример #18
0
/**
 * The main function for the command line mode. Parses switches and runs decompile(filename).
 *
 * \return Zero on success, nonzero on faillure.
 */
int Boomerang::commandLine(int argc, const char **argv) 
{
	printf("Boomerang %s\n", VERSION);		// Display a version and date (mainly for release versions)
	if (argc < 2) usage();
	progPath = argv[0];
	size_t j = progPath.rfind('/');			// Chop off after the last slash
	if (j == (size_t)-1) 
		j = progPath.rfind('\\');			// .. or reverse slash
	if (j != (size_t)-1) {
		// Do the chop; keep the trailing slash or reverse slash
		progPath = progPath.substr(0, j+1);
	}
	else {
		progPath = "./";			// Just assume the current directory
	}
#ifdef _MSC_VER						// For the console mode version; Windows GUI will override in windows.cpp
	// As a special case for MSVC testing, make the program path the parent of the dir with the .exe
	j = progPath.find("ebug\\", progPath.length() - (4+1));
	if (j != std::string::npos)
		j--;			// Point to the 'd' or 'D'
	if (j == std::string::npos) {
			j = progPath.rfind("elease\\", progPath.length() - (6+1));
			if (j != std::string::npos)
				j--;			// Point to the 'r' or 'R'
	}
	if (j != std::string::npos)
		progPath = progPath.substr(0, j);			// Chop off "Release\" or "Debug\"
	SetCurrentDirectoryA(progPath.c_str());			// Note: setcwd() doesn't seem to work
#endif
	outputPath = progPath + "output/";				// Default output path (can be overridden with -o below)

	// Parse switches on command line
	if ((argc == 2) && (strcmp(argv[1], "-h") == 0)) {
		help();
		return 1;
	}
	if (argc == 3 && !strcmp(argv[1], "-h") && !strcmp(argv[2], "cmd")) {
		helpcmd();
		return 1;
	}

	int kmd = 0;

	for (int i=1; i < argc; i++) {
		if (argv[i][0] != '-' && i == argc - 1)
			break;
		if (argv[i][0] != '-')
			usage();
		switch (argv[i][1]) {
			case '-': break;		// No effect: ignored
			case 'h': help(); break;
			case 'v': vFlag = true; break;
			case 'x': dumpXML = true; break;
			case 'X': experimental = true;
				std::cout << "Warning: experimental code active!\n"; break;
			case 'r': printRtl = true; break;
			case 't': traceDecoder = true; break;
			case 'T':
				if (argv[i][2] == 'c') {
					conTypeAnalysis = true;		// -Tc: use old constraint-based type analysis
					dfaTypeAnalysis = false;
				}
				else if (argv[i][2] == 'd')
					dfaTypeAnalysis = true;		// -Td: use data-flow-based type analysis (now default)
				break;
			case 'g': 
				if(argv[i][2]=='d')
					dotFile = argv[++i];
				else if(argv[i][2]=='c')
					generateCallGraph=true;
				else if(argv[i][2]=='s') {
					generateSymbols=true;
					stopBeforeDecompile=true;
				}
				break;
			case 'o': {
				outputPath = argv[++i];
				char lastCh = outputPath[outputPath.size()-1];
				if (lastCh != '/' && lastCh != '\\')
					outputPath += '/';		// Maintain the convention of a trailing slash
				break;
			}
			case 'p':
				if (argv[i][2] == 'a') {
					propOnlyToAll = true;
					std::cerr << " * * Warning! -pa is not implemented yet!\n";
				}
				else {
					if (++i == argc) {
						usage();
						return 1;
					}
					sscanf(argv[i], "%i", &numToPropagate);
				}
				break;
			case 'n':
				switch(argv[i][2]) {
					case 'b':
						noBranchSimplify = true;
						break;
					case 'c':
						noDecodeChildren = true;
						break;
					case 'd':
						noDataflow = true;
						break;
					case 'D':
						noDecompile = true;
						break;
					case 'l':
						noLocals = true;
						break;
					case 'n':
						noRemoveNull = true;
						break;
					case 'P':
						noPromote = true;
						break;
					case 'p':
						noParameterNames = true;
						break;
					case 'r':
						noRemoveLabels = true;
						break;
					case 'R':
						noRemoveReturns = true;
						break;
					case 'g':
						noGlobals = true;
						break;
					case 'G':
#ifndef NO_GARBAGE_COLLECTOR
						GC_disable();
#endif
						break;
					default:
						help();
				}
				break;
			case 'E':
				noDecodeChildren = true;
				// Fall through
			case 'e':
				{
					ADDRESS addr;
					int n;
					decodeMain = false;
					if (++i == argc) {
						usage();
						return 1;
					}
					if (argv[i][0] == '0' && argv[i+1][1] == 'x') {
						n = sscanf(argv[i], "0x%x", &addr);
					} else {
						n = sscanf(argv[i], "%i", &addr);
					}
					if (n != 1) {
						std::cerr << "bad address: " << argv[i] << std::endl;
						exit(1);
					}
					entrypoints.push_back(addr);
				}
				break;
			case 's':
				{
					if (argv[i][2] == 'f') {
						symbolFiles.push_back(argv[i+1]);
						i++;
						break;
					}
					ADDRESS addr;
					int n;
					if (++i == argc) {
						usage();
						return 1;
					}
					if (argv[i][0] == '0' && argv[i+1][1] == 'x') {
						n = sscanf(argv[i], "0x%x", &addr);
					} else {
						n = sscanf(argv[i], "%i", &addr);
					}
					if (n != 1) {
						std::cerr << "bad address: " << argv[i+1] << std::endl;
						exit(1);
					}
					const char *nam = argv[++i];
					symbols[addr] = nam;
				}
				break;
			case 'd':
				switch(argv[i][2]) {
					case 'a':
						printAST = true;
						break;
					case 'c':
						debugSwitch = true;
						break;
					case 'd':
						debugDecoder = true;
						break;
					case 'g':
						debugGen = true;
						break;
					case 'l':
						debugLiveness = true;
						break;
					case 'p':
						debugProof = true;
						break;
					case 's':
						stopAtDebugPoints = true;
						break;
					case 't':		// debug type analysis
						debugTA = true;
						break;
					case 'u':		// debug unused locations (including returns and parameters now)
						debugUnused = true;
						break;
					default:
						help();
				}
				break;
			case 'm':
				if (++i == argc) {
					usage();
					return 1;
				}
				sscanf(argv[i], "%i", &maxMemDepth);
				break;
			case 'i':
				if (argv[i][2] == 'c')
					decodeThruIndCall = true;		// -ic;
				if (argv[i][2] == 'w')				// -iw
					if (ofsIndCallReport) {
						std::string fname = getOutputPath() + "indirect.txt";
						ofsIndCallReport = new std::ofstream(fname.c_str());
					}
				break;
			case 'L':
				if (argv[i][2] == 'D')
					#if USE_XML
					loadBeforeDecompile = true;
					#else
					std::cerr << "LD command not enabled since compiled without USE_XML\n";
					#endif
				break;
			case 'S':
				if (argv[i][2] == 'D')
					#if USE_XML
					saveBeforeDecompile = true;
					#else
					std::cerr << "SD command not enabled since compiled without USE_XML\n";
					#endif
				else {
					sscanf(argv[++i], "%i", &minsToStopAfter);					
				}
				break;
			case 'k':
				kmd = 1;
				break;
			case 'P':
				progPath = argv[++i];
				if (progPath[progPath.length()-1] != '\\')
					progPath += "\\";
				break;
			case 'a':
				assumeABI = true;
				break;
			case 'l':
				if (++i == argc) {
					usage();
					return 1;
				}
				sscanf(argv[i], "%i", &propMaxDepth);
				break;
			default:
				help();
		}
	}
Пример #19
0
void
Downloader::onDownloadFinished()
{
    QNetworkReply::NetworkError videoError;
    QNetworkReply::NetworkError soundError;

    bool finished = false;


    if (_videoNetworkReply != NULL)
    {
        videoError = _videoNetworkReply->error();
    }
    else
    {
        videoError = QNetworkReply::NoError;
    }


    if (_soundNetworkReply != NULL)
    {
        soundError = _soundNetworkReply->error();
    }
    else
    {
        soundError = QNetworkReply::NoError;
    }


    if (_videoNetworkReply != NULL && _soundNetworkReply != NULL)
    {
        bool videoFinished = _videoNetworkReply->isFinished();
        bool soundFinished = _soundNetworkReply->isFinished();

        finished = videoFinished && soundFinished;
    }
    else if (_videoNetworkReply != NULL)
    {
        finished = _videoNetworkReply->isFinished();
    }
    else
    {
        finished = _soundNetworkReply->isFinished();
    }


    if (finished)
    {
        if (soundError == QNetworkReply::OperationCanceledError &&
            _videoNetworkReply == NULL)
        {
            videoError = QNetworkReply::OperationCanceledError;
        }

        if (videoError == QNetworkReply::OperationCanceledError ||
            soundError == QNetworkReply::OperationCanceledError)
        {
            // User has canceled downloading

            goto Cleanup;
        }
        else if (videoError || soundError)
        {
            // Some kind of error occurred on both downloaders. Examine it.

            goto ErrorProcedure;
        }
        else
        {
            // It's possible that the downloaders finish without an error but
            // with no data downloaded. I've noticed that the video is still
            // available for download. This may happen if the video website has
            // issued a redirect. Check this and take action accordingly.

            if (_soundNetworkReply != NULL && _soundBytesReceived == 0)
            {
                if (redirect(_soundNetworkReply)) {
                    return;
                }

                qDebug() << QString("Invalid sound data from %1")
                            .arg(_soundNetworkReply->url().toString());

                goto ErrorProcedure;
            }

            if (_videoNetworkReply != NULL && _videoBytesReceived == 0)
            {
                if (redirect(_videoNetworkReply)) {
                    return;
                }

                qDebug() << QString("Invalid video data from %1")
                            .arg(_videoNetworkReply->url().toString());

                goto ErrorProcedure;
            }


            QString iargs = "-threads 1 -id3v2_version 3 -write_id3v1 1 ";

            bool hasArtist = !_download.artist.isEmpty();
            bool hasTitle = !_download.title.isEmpty();
            bool hasCoartist = !_download.coartist.isEmpty();

            if (hasArtist && hasTitle)
            {
                QString artist = _download.artist;

                if (hasCoartist) {
                    artist += " ft. " + _download.coartist;
                }

                // The filename so far contains the artist's name.
                // Write it using ID3 tags.
                // Delete " character as it will cause ffmpeg to fail.

                artist = artist.replace("\"", "");
                QString title = _download.title.replace("\"", "");

                iargs += " -metadata artist=\"" + artist + "\" ";
                iargs += " -metadata title=\"" + title + "\" ";
            }

            QString command;
            QString filename = _download.filename;
            QString extension = _download.outputFormat.extension;
            QString savePath = getOutputPath(filename, extension);
            QString ffmpeg = Utility::getFFmpegFilename();

            _download.outputFilename = savePath;


            if (_videoNetworkReply != NULL && _soundNetworkReply != NULL)
            {
                // Video service which separates sound and video stream.
                // The video was requested as both streams have been downloaded.
                // We will merge them into the final video file.

                QString vfilename = _videoFile->fileName();
                QString sfilename = _soundFile->fileName();
                QString args = "%1 -i \"%2\" -i \"%3\" %4 \"%5\"";

                command = QString(args)
                        .arg(ffmpeg)
                        .arg(vfilename)
                        .arg(sfilename)
                        .arg(iargs)
                        .arg(savePath);

                _videoFile->close();
                _soundFile->close();
            }
            else
            {
                QString filename = "";


                if (_soundNetworkReply != NULL)
                {
                    // Video service which separates sound and video stream.
                    // Only the sound was requested as only the sound stream
                    // has been downloaded. We will convert it to the final
                    // sound file.

                    filename = _soundFile->fileName();

                    _soundFile->close();
                }
                else
                {
                    // Video service which provides on video stream containing
                    // both the video and the sound streams. Call ffmpeg to
                    // convert it (or extract sound) to the requested format.

                    filename = _videoFile->fileName();

                    _videoFile->close();
                }

                command = QString("%1 -y -i \"%2\" %3 \"%4\"")
                        .arg(ffmpeg)
                        .arg(filename)
                        .arg(iargs)
                        .arg(savePath);
            }

            _convertPid = Tasks->enqueue(command);

            setStatus(Converting);
            setProgress(0, 0, 100);

            goto Cleanup;
        }
    }
    else
    {
        // One of the two downloaders (video/sound) has finished.
        // This may be normal. A common scenario is that sound has been
        // downloaded because of smaller size but video is still pending.
        // But maybe a downloader has finished because of an error.
        // Check and take action accordingly.
        if (videoError || soundError) {
            goto ErrorProcedure;
        }
    }

    return;


ErrorProcedure:

    // If at least one downloader has errored, stop the other.
    if (videoError && _soundNetworkReply != NULL) {
        _soundNetworkReply->abort();
    }

    if (soundError && _videoNetworkReply != NULL) {
        _videoNetworkReply->abort();
    }


    if (_retryCount < MAX_RETRIES)
    {
        _retryCount++;

        qDebug() << QString("Processor had an error connection. "
                            "Retrying for %1 time in %2 ms")
                            .arg(QString::number(_retryCount))
                            .arg(QString::number(RETRY_INTERVAL));

        QTimer *timer = new QTimer();

        timer->setSingleShot(true);
        timer->start(RETRY_INTERVAL);

        connect(timer,
                SIGNAL(timeout()),
                this,
                SLOT(onTimerTimeout()));

        return;
    }
    else
    {
        qDebug() << QString("Processor had an error connection. "
                            "Max retries of %1 reached")
                            .arg(MAX_RETRIES);

        setStatus(ErrorConnection);
        setProgress(0, 0, 0);

        goto Cleanup;
    }


Cleanup:
    if (_soundNetworkReply != NULL)
    {
        _soundNetworkReply->deleteLater();
        _soundNetworkReply = NULL;

        if (_soundFile->isOpen()) {
            _soundFile->close();
        }

        delete _soundFile;

        _soundFile = NULL;
    }

    if (_videoNetworkReply != NULL)
    {
        _videoNetworkReply->deleteLater();
        _videoNetworkReply = NULL;

        if (_videoFile->isOpen()) {
            _videoFile->close();
        }

        delete _videoFile;

        _videoFile = NULL;
    }
}