<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NISO_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Export/Export_Niso.h"
#include "MediaInfo/File__Analyse_Automatic.h"
#include "MediaInfo/OutputHelpers.h"
#include <ctime>
#include <cmath>

using namespace std;

//---------------------------------------------------------------------------

namespace MediaInfoLib
{
//---------------------------------------------------------------------------
extern MediaInfo_Config Config;
//---------------------------------------------------------------------------

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
Export_Niso::Export_Niso ()
{
}

//---------------------------------------------------------------------------
Export_Niso::~Export_Niso ()
{
}

//***************************************************************************
// Helpers
//***************************************************************************

//---------------------------------------------------------------------------
Node* Transform_Header()
{
    //Root node
    Node* Node_Header=new Node("mix:mix");
    Node_Header->Add_Attribute("xmlns:mix", "http://www.loc.gov/mix/v20");
    Node_Header->Add_Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    Node_Header->Add_Attribute("xsi:schemaLocation", "http://www.loc.gov/mix/v20 http://www.loc.gov/standards/mix/mix20/mix20.xsd");

    return Node_Header;
}

//---------------------------------------------------------------------------
void ComputeSamplingFrequency(Node* Parent, Ztring& Value)
{
    while (Value.size()>0 && Value[Value.size()-1]==__T('0'))
        Value.resize(Value.size()-1);
    if (Value.size()>0 && Value[Value.size()-1]==__T('.'))
        Value.resize(Value.size()-1);

    int32u SamplingFrequencyDenominator=0;
    size_t Dot=Value.find(__T("."));
    if (Dot!=std::string::npos)
    {
        SamplingFrequencyDenominator=std::pow(10, Value.size()-Dot-1);
        Value.erase(Dot, 1);
    }

    Parent->Add_Child("mix:numerator", Value);

    if (SamplingFrequencyDenominator)
        Parent->Add_Child("mix:denominator", Ztring().From_Number(SamplingFrequencyDenominator));
}

//***************************************************************************
// Input
//***************************************************************************

//---------------------------------------------------------------------------
Ztring Export_Niso::Transform(MediaInfo_Internal &MI, Ztring ExternalMetadataValues, Ztring ExternalMetaDataConfig)
{
    bool UseExternalMetaData=(!ExternalMetaDataConfig.empty() && !ExternalMetadataValues.empty());

    Ztring ToReturn;
    for (size_t Pos=0; Pos<MI.Count_Get(Stream_Image); Pos++)
    {
        Node* Node_Root=Transform_Header();
        Node* Node_Extension=NULL;

        //Use external metadata
        if (UseExternalMetaData)
        {
            Ztring FileName;
            if (!MI.Get(Stream_General, 0, General_FileName).empty())
                FileName=MI.Get(Stream_General, 0, General_FileName);
            if (!MI.Get(Stream_General, 0, General_FileExtension).empty())
                FileName+=__T('.')+MI.Get(Stream_General, 0, General_FileExtension);
            if (FileName.empty())
            {
                MediaInfoLib::Config.Log_Send(0xC0, 0xFF, 0, "File name not found in external metadata file");
                delete Node_Root;
                return Ztring();
            }

            Node_Extension= new Node("mix:Extension");
            Node* Node_CoreMain=NULL;

            if (ExternalMetaDataConfig.find(__T("<ebucore:ebuCoreMain"))<100)
            {
                //TODO: merge with EBUCore code
                //Current date/time is ISO format
                time_t Seconds=time(NULL);
                Ztring DateTime; DateTime.Date_From_Seconds_1970((int32u)Seconds);
                if (DateTime.size() >= 4 && DateTime[0] == __T('U') && DateTime[1] == __T('T') && DateTime[2] == __T('C') && DateTime[3] == __T(' '))
                {
                    DateTime.erase(0, 4);
                    DateTime += __T('Z');
                }
                Ztring Date=DateTime.substr(0, 10);
                Ztring Time=DateTime.substr(11);

                Node* Node_CoreMain=Node_Extension->Add_Child("ebucore:ebuCoreMain");
                Node_CoreMain->Add_Attribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                {
                    Node_CoreMain->Add_Attribute("xmlns:ebucore", "urn:ebu:metadata-schema:ebucore");
                    Node_CoreMain->Add_Attribute("xmlns:xalan", "http://xml.apache.org/xalan");
                    Node_CoreMain->Add_Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    Node_CoreMain->Add_Attribute("xsi:schemaLocation", string("urn:ebu:metadata-schema:ebucore http") + string(MediaInfoLib::Config.Https_Get() ? "s" : "") + "://www.ebu.ch/metadata/schemas/EBUCore/20171009/ebucore.xsd");
                    Node_CoreMain->Add_Attribute("version", "1.8");
                    Node_CoreMain->Add_Attribute("writingLibraryName", "MediaInfoLib");
                    Node_CoreMain->Add_Attribute("writingLibraryVersion", MediaInfoLib::Config.Info_Version_Get().SubString(__T(" - v"), Ztring()));
                }
                Node_CoreMain->Add_Attribute("dateLastModified", Date);
                Node_CoreMain->Add_Attribute("timeLastModified", Time);
            }

            if (!ExternalMetadata(FileName, ExternalMetadataValues, ExternalMetaDataConfig,
                                  ZtringList(__T("mix:Extension;ebucore:ebuCoreMain")), __T(""),
                                  Node_CoreMain?Node_CoreMain:Node_Extension, NULL))
            {
                delete Node_Root;
                return Ztring();
            }
        }

        //BasicDigitalObjectInformation
        Node* Node_BasicDigitalObjectInformation=Node_Root->Add_Child("mix:BasicDigitalObjectInformation");
        Node* Node_ObjectIdentifier=Node_BasicDigitalObjectInformation->Add_Child("mix:ObjectIdentifier");

        Node_ObjectIdentifier->Add_Child("mix:objectIdentifierType", std::string("MediaInfo"));
        Node_ObjectIdentifier->Add_Child_IfNotEmpty(MI, Stream_General, 0, General_CompleteName, "mix:objectIdentifierValue");

        if (MI.Get(Stream_General, 0, General_FileSize).To_int64u()>0)
            Node_BasicDigitalObjectInformation->Add_Child("mix:fileSize", MI.Get(Stream_General, 0, General_FileSize));

        if (MI.Get(Stream_General, 0, General_Format)==__T("TIFF"))
             Node_BasicDigitalObjectInformation->Add_Child("mix:FormatDesignation")->Add_Child("mix:formatName", std::string("image/tiff"));

        std::string byteOrder=MI.Get(Stream_Image, Pos, Image_Format_Settings_Endianness).To_UTF8();
        if (!byteOrder.empty())
            Node_BasicDigitalObjectInformation->Add_Child("mix:byteOrder", byteOrder=="Little"?std::string("little endian"):(byteOrder=="Big"?std::string("big endian"): byteOrder));

        std::string CompressionScheme=MI.Get(Stream_Image, Pos, Image_Format).To_UTF8();
        if (!CompressionScheme.empty())
            Node_BasicDigitalObjectInformation->Add_Child("mix:Compression")->Add_Child("mix:compressionScheme", CompressionScheme=="Raw"?std::string("Uncompressed"):CompressionScheme);

        if (!MI.Get(Stream_Image, Pos, Image_Width).empty() ||
            !MI.Get(Stream_Image, Pos, Image_Height).empty() ||
            !MI.Get(Stream_Image, Pos, Image_ColorSpace).empty())
        {
            Node* Node_BasicImageCharacteristics=Node_Root->Add_Child("mix:BasicImageInformation")->Add_Child("mix:BasicImageCharacteristics");

            Node_BasicImageCharacteristics->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_Width, "mix:imageWidth");
            Node_BasicImageCharacteristics->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_Height, "mix:imageHeight");

            //ReferenceBlackWhite
            std::string ColorSpace=MI.Get(Stream_Image, Pos, Image_ColorSpace).To_UTF8();
            if (!ColorSpace.empty())
            {
                Node* Node_PhotometricInterpretation=Node_BasicImageCharacteristics->Add_Child("mix:PhotometricInterpretation");
                Node_PhotometricInterpretation->Add_Child("mix:colorSpace", ColorSpace);

                Node* ReferenceBlackWhite=Node_PhotometricInterpretation->Add_Child("mix:ReferenceBlackWhite");
                for (size_t i=0; i < ColorSpace.size(); i++)
                {
                    Node* Component=ReferenceBlackWhite->Add_Child("mix:Component");
                    Component->Add_Child("mix:componentPhotometricInterpretation", string(1, ColorSpace[i]));
                    Node* footroom=Component->Add_Child("mix:footroom");
                    footroom->Add_Child("mix:numerator", Ztring::ToZtring(0));
                    int8u BitDepth=MI.Get(Stream_Image, Pos, Image_BitDepth).To_int8u();
                    if (BitDepth)
                    {
                        Node* headroom=Component->Add_Child("mix:headroom");
                        headroom->Add_Child("mix:numerator", Ztring::ToZtring((1<<BitDepth)-1));
                    }
                }
            }
        }

        //ImageCaptureMetadata
        std::string Make=MI.Get(Stream_General, 0, General_Encoded_Application_CompanyName).To_UTF8();
        std::string Model=MI.Get(Stream_General, 0, General_Encoded_Library_Name).To_UTF8();
        std::string Software=MI.Get(Stream_General, 0, General_Encoded_Application_Name).To_UTF8();
        std::string Encoded_Date=MI.Get(Stream_Image, Pos, Image_Encoded_Date).To_UTF8();
        if (!Make.empty() || !Model.empty() || !Software.empty() || !Encoded_Date.empty())
        {
            Node* Node_ImageCaptureMetadata=Node_Root->Add_Child("mix:ImageCaptureMetadata");

            if (!Encoded_Date.empty())
            {
                if (Encoded_Date.size()>4 && Encoded_Date[4]==':')
                    Encoded_Date[4]='-';
                if (Encoded_Date.size()>7 && Encoded_Date[7]==':')
                    Encoded_Date[7]='-';
                if (Encoded_Date.size()>10 && Encoded_Date[10]==' ')
                    Encoded_Date[10]='T';
                Node* Node_GeneralCaptureInformation=Node_ImageCaptureMetadata->Add_Child("mix:GeneralCaptureInformation");
                Node_GeneralCaptureInformation->Add_Child("mix:dateTimeCreated", Encoded_Date);
            }

            if (!Make.empty() || !Model.empty() || !Software.empty() )
            {
                Node* Node_ScannerCapture=Node_ImageCaptureMetadata->Add_Child("mix:ScannerCapture");
                if (!Make.empty())
                    Node_ScannerCapture->Add_Child("mix:scannerManufacturer", Make);
                if (!Model.empty())
                    Node_ScannerCapture->Add_Child("mix:ScannerModel")->Add_Child("mix:scannerModelName", Model);
                if (!Software.empty())
                    Node_ScannerCapture->Add_Child("mix:ScanningSystemSoftware")->Add_Child("mix:scanningSoftwareName", Software);
            }
        }

        if (!MI.Get(Stream_Image, Pos, __T("Density_X")).empty() ||
            !MI.Get(Stream_Image, Pos, __T("Density_X")).empty() ||
            !MI.Get(Stream_Image, Pos, Image_ColorSpace).empty())
        {
            Node* Node_ImageAssessmentMetadata=Node_Root->Add_Child("mix:ImageAssessmentMetadata");

            //SpatialMetrics
            string samplingFrequencyUnit=MI.Get(Stream_Image, Pos, __T("Density_Unit")).To_UTF8();
            Ztring xSamplingFrequency=MI.Get(Stream_Image, Pos, __T("Density_X"));
            Ztring ySamplingFrequency=MI.Get(Stream_Image, Pos, __T("Density_Y"));
            if (!xSamplingFrequency.empty() || !ySamplingFrequency.empty())
            {
                Node* Node_SpatialMetrics=Node_ImageAssessmentMetadata->Add_Child("mix:SpatialMetrics");

                if (samplingFrequencyUnit.empty())
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("no absolute unit of measurement"));
                else if (samplingFrequencyUnit=="dpi")
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("in."));
                else if (samplingFrequencyUnit=="dpcm")
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("cm"));

                if (!xSamplingFrequency.empty())
                    ComputeSamplingFrequency(Node_SpatialMetrics->Add_Child("mix:xSamplingFrequency"), xSamplingFrequency);
                if (!ySamplingFrequency.empty())
                    ComputeSamplingFrequency(Node_SpatialMetrics->Add_Child("mix:ySamplingFrequency"), ySamplingFrequency);
            }

            size_t SamplesPerPixel=MI.Get(Stream_Image, Pos, Image_ColorSpace).length();
            if (SamplesPerPixel)
            {
                Node* Node_ImageColorEncoding=Node_ImageAssessmentMetadata->Add_Child("mix:ImageColorEncoding");

                Node* Node_BitsPerSample=new Node("mix:BitsPerSample");
                for (size_t Pos2=0; Pos2<SamplesPerPixel; ++Pos2)
                    Node_BitsPerSample->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_BitDepth, "mix:bitsPerSampleValue");

                if (!Node_BitsPerSample->Childs.empty())
                {
                    Node_BitsPerSample->Add_Child("mix:bitsPerSampleUnit", std::string("integer"));
                    Node_ImageColorEncoding->Childs.push_back(Node_BitsPerSample);
                }
                else
                   delete Node_BitsPerSample;

                Node_ImageColorEncoding->Add_Child("mix:samplesPerPixel", Ztring().From_Number(SamplesPerPixel).To_UTF8());
            }
        }

        if (Node_Extension)
            Node_Root->Childs.push_back(Node_Extension);

        ToReturn+=Ztring().From_UTF8(To_XML(*Node_Root, 0, true, true).c_str());
    }

    if (ToReturn.empty())
        ToReturn+=Ztring().From_UTF8(To_XML(*Transform_Header(), 0, true, true).c_str())+=__T("\n");

    //Carriage return
    if (MediaInfoLib::Config.LineSeparator_Get()!=__T("\n"))
        ToReturn.FindAndReplace(__T("\n"), MediaInfoLib::Config.LineSeparator_Get(), 0, Ztring_Recursive);

    return ToReturn;
}

//***************************************************************************
//
//***************************************************************************

} //NameSpace

#endif
<commit_msg>x Ambiguous call to std::pow<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NISO_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Export/Export_Niso.h"
#include "MediaInfo/File__Analyse_Automatic.h"
#include "MediaInfo/OutputHelpers.h"
#include <ctime>
#include <cmath>

using namespace std;

//---------------------------------------------------------------------------

namespace MediaInfoLib
{
//---------------------------------------------------------------------------
extern MediaInfo_Config Config;
//---------------------------------------------------------------------------

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
Export_Niso::Export_Niso ()
{
}

//---------------------------------------------------------------------------
Export_Niso::~Export_Niso ()
{
}

//***************************************************************************
// Helpers
//***************************************************************************

//---------------------------------------------------------------------------
Node* Transform_Header()
{
    //Root node
    Node* Node_Header=new Node("mix:mix");
    Node_Header->Add_Attribute("xmlns:mix", "http://www.loc.gov/mix/v20");
    Node_Header->Add_Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    Node_Header->Add_Attribute("xsi:schemaLocation", "http://www.loc.gov/mix/v20 http://www.loc.gov/standards/mix/mix20/mix20.xsd");

    return Node_Header;
}

//---------------------------------------------------------------------------
void ComputeSamplingFrequency(Node* Parent, Ztring& Value)
{
    while (Value.size()>0 && Value[Value.size()-1]==__T('0'))
        Value.resize(Value.size()-1);
    if (Value.size()>0 && Value[Value.size()-1]==__T('.'))
        Value.resize(Value.size()-1);

    int32u SamplingFrequencyDenominator=0;
    size_t Dot=Value.find(__T("."));
    if (Dot!=std::string::npos)
    {
        Value.erase(Dot, 1);
        SamplingFrequencyDenominator=(int32u)std::pow((double)10, (int)Value.size()-Dot);
    }

    Parent->Add_Child("mix:numerator", Value);

    if (SamplingFrequencyDenominator)
        Parent->Add_Child("mix:denominator", Ztring().From_Number(SamplingFrequencyDenominator));
}

//***************************************************************************
// Input
//***************************************************************************

//---------------------------------------------------------------------------
Ztring Export_Niso::Transform(MediaInfo_Internal &MI, Ztring ExternalMetadataValues, Ztring ExternalMetaDataConfig)
{
    bool UseExternalMetaData=(!ExternalMetaDataConfig.empty() && !ExternalMetadataValues.empty());

    Ztring ToReturn;
    for (size_t Pos=0; Pos<MI.Count_Get(Stream_Image); Pos++)
    {
        Node* Node_Root=Transform_Header();
        Node* Node_Extension=NULL;

        //Use external metadata
        if (UseExternalMetaData)
        {
            Ztring FileName;
            if (!MI.Get(Stream_General, 0, General_FileName).empty())
                FileName=MI.Get(Stream_General, 0, General_FileName);
            if (!MI.Get(Stream_General, 0, General_FileExtension).empty())
                FileName+=__T('.')+MI.Get(Stream_General, 0, General_FileExtension);
            if (FileName.empty())
            {
                MediaInfoLib::Config.Log_Send(0xC0, 0xFF, 0, "File name not found in external metadata file");
                delete Node_Root;
                return Ztring();
            }

            Node_Extension= new Node("mix:Extension");
            Node* Node_CoreMain=NULL;

            if (ExternalMetaDataConfig.find(__T("<ebucore:ebuCoreMain"))<100)
            {
                //TODO: merge with EBUCore code
                //Current date/time is ISO format
                time_t Seconds=time(NULL);
                Ztring DateTime; DateTime.Date_From_Seconds_1970((int32u)Seconds);
                if (DateTime.size() >= 4 && DateTime[0] == __T('U') && DateTime[1] == __T('T') && DateTime[2] == __T('C') && DateTime[3] == __T(' '))
                {
                    DateTime.erase(0, 4);
                    DateTime += __T('Z');
                }
                Ztring Date=DateTime.substr(0, 10);
                Ztring Time=DateTime.substr(11);

                Node* Node_CoreMain=Node_Extension->Add_Child("ebucore:ebuCoreMain");
                Node_CoreMain->Add_Attribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                {
                    Node_CoreMain->Add_Attribute("xmlns:ebucore", "urn:ebu:metadata-schema:ebucore");
                    Node_CoreMain->Add_Attribute("xmlns:xalan", "http://xml.apache.org/xalan");
                    Node_CoreMain->Add_Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    Node_CoreMain->Add_Attribute("xsi:schemaLocation", string("urn:ebu:metadata-schema:ebucore http") + string(MediaInfoLib::Config.Https_Get() ? "s" : "") + "://www.ebu.ch/metadata/schemas/EBUCore/20171009/ebucore.xsd");
                    Node_CoreMain->Add_Attribute("version", "1.8");
                    Node_CoreMain->Add_Attribute("writingLibraryName", "MediaInfoLib");
                    Node_CoreMain->Add_Attribute("writingLibraryVersion", MediaInfoLib::Config.Info_Version_Get().SubString(__T(" - v"), Ztring()));
                }
                Node_CoreMain->Add_Attribute("dateLastModified", Date);
                Node_CoreMain->Add_Attribute("timeLastModified", Time);
            }

            if (!ExternalMetadata(FileName, ExternalMetadataValues, ExternalMetaDataConfig,
                                  ZtringList(__T("mix:Extension;ebucore:ebuCoreMain")), __T(""),
                                  Node_CoreMain?Node_CoreMain:Node_Extension, NULL))
            {
                delete Node_Root;
                return Ztring();
            }
        }

        //BasicDigitalObjectInformation
        Node* Node_BasicDigitalObjectInformation=Node_Root->Add_Child("mix:BasicDigitalObjectInformation");
        Node* Node_ObjectIdentifier=Node_BasicDigitalObjectInformation->Add_Child("mix:ObjectIdentifier");

        Node_ObjectIdentifier->Add_Child("mix:objectIdentifierType", std::string("MediaInfo"));
        Node_ObjectIdentifier->Add_Child_IfNotEmpty(MI, Stream_General, 0, General_CompleteName, "mix:objectIdentifierValue");

        if (MI.Get(Stream_General, 0, General_FileSize).To_int64u()>0)
            Node_BasicDigitalObjectInformation->Add_Child("mix:fileSize", MI.Get(Stream_General, 0, General_FileSize));

        if (MI.Get(Stream_General, 0, General_Format)==__T("TIFF"))
             Node_BasicDigitalObjectInformation->Add_Child("mix:FormatDesignation")->Add_Child("mix:formatName", std::string("image/tiff"));

        std::string byteOrder=MI.Get(Stream_Image, Pos, Image_Format_Settings_Endianness).To_UTF8();
        if (!byteOrder.empty())
            Node_BasicDigitalObjectInformation->Add_Child("mix:byteOrder", byteOrder=="Little"?std::string("little endian"):(byteOrder=="Big"?std::string("big endian"): byteOrder));

        std::string CompressionScheme=MI.Get(Stream_Image, Pos, Image_Format).To_UTF8();
        if (!CompressionScheme.empty())
            Node_BasicDigitalObjectInformation->Add_Child("mix:Compression")->Add_Child("mix:compressionScheme", CompressionScheme=="Raw"?std::string("Uncompressed"):CompressionScheme);

        if (!MI.Get(Stream_Image, Pos, Image_Width).empty() ||
            !MI.Get(Stream_Image, Pos, Image_Height).empty() ||
            !MI.Get(Stream_Image, Pos, Image_ColorSpace).empty())
        {
            Node* Node_BasicImageCharacteristics=Node_Root->Add_Child("mix:BasicImageInformation")->Add_Child("mix:BasicImageCharacteristics");

            Node_BasicImageCharacteristics->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_Width, "mix:imageWidth");
            Node_BasicImageCharacteristics->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_Height, "mix:imageHeight");

            //ReferenceBlackWhite
            std::string ColorSpace=MI.Get(Stream_Image, Pos, Image_ColorSpace).To_UTF8();
            if (!ColorSpace.empty())
            {
                Node* Node_PhotometricInterpretation=Node_BasicImageCharacteristics->Add_Child("mix:PhotometricInterpretation");
                Node_PhotometricInterpretation->Add_Child("mix:colorSpace", ColorSpace);

                Node* ReferenceBlackWhite=Node_PhotometricInterpretation->Add_Child("mix:ReferenceBlackWhite");
                for (size_t i=0; i < ColorSpace.size(); i++)
                {
                    Node* Component=ReferenceBlackWhite->Add_Child("mix:Component");
                    Component->Add_Child("mix:componentPhotometricInterpretation", string(1, ColorSpace[i]));
                    Node* footroom=Component->Add_Child("mix:footroom");
                    footroom->Add_Child("mix:numerator", Ztring::ToZtring(0));
                    int8u BitDepth=MI.Get(Stream_Image, Pos, Image_BitDepth).To_int8u();
                    if (BitDepth)
                    {
                        Node* headroom=Component->Add_Child("mix:headroom");
                        headroom->Add_Child("mix:numerator", Ztring::ToZtring((1<<BitDepth)-1));
                    }
                }
            }
        }

        //ImageCaptureMetadata
        std::string Make=MI.Get(Stream_General, 0, General_Encoded_Application_CompanyName).To_UTF8();
        std::string Model=MI.Get(Stream_General, 0, General_Encoded_Library_Name).To_UTF8();
        std::string Software=MI.Get(Stream_General, 0, General_Encoded_Application_Name).To_UTF8();
        std::string Encoded_Date=MI.Get(Stream_Image, Pos, Image_Encoded_Date).To_UTF8();
        if (!Make.empty() || !Model.empty() || !Software.empty() || !Encoded_Date.empty())
        {
            Node* Node_ImageCaptureMetadata=Node_Root->Add_Child("mix:ImageCaptureMetadata");

            if (!Encoded_Date.empty())
            {
                if (Encoded_Date.size()>4 && Encoded_Date[4]==':')
                    Encoded_Date[4]='-';
                if (Encoded_Date.size()>7 && Encoded_Date[7]==':')
                    Encoded_Date[7]='-';
                if (Encoded_Date.size()>10 && Encoded_Date[10]==' ')
                    Encoded_Date[10]='T';
                Node* Node_GeneralCaptureInformation=Node_ImageCaptureMetadata->Add_Child("mix:GeneralCaptureInformation");
                Node_GeneralCaptureInformation->Add_Child("mix:dateTimeCreated", Encoded_Date);
            }

            if (!Make.empty() || !Model.empty() || !Software.empty() )
            {
                Node* Node_ScannerCapture=Node_ImageCaptureMetadata->Add_Child("mix:ScannerCapture");
                if (!Make.empty())
                    Node_ScannerCapture->Add_Child("mix:scannerManufacturer", Make);
                if (!Model.empty())
                    Node_ScannerCapture->Add_Child("mix:ScannerModel")->Add_Child("mix:scannerModelName", Model);
                if (!Software.empty())
                    Node_ScannerCapture->Add_Child("mix:ScanningSystemSoftware")->Add_Child("mix:scanningSoftwareName", Software);
            }
        }

        if (!MI.Get(Stream_Image, Pos, __T("Density_X")).empty() ||
            !MI.Get(Stream_Image, Pos, __T("Density_X")).empty() ||
            !MI.Get(Stream_Image, Pos, Image_ColorSpace).empty())
        {
            Node* Node_ImageAssessmentMetadata=Node_Root->Add_Child("mix:ImageAssessmentMetadata");

            //SpatialMetrics
            string samplingFrequencyUnit=MI.Get(Stream_Image, Pos, __T("Density_Unit")).To_UTF8();
            Ztring xSamplingFrequency=MI.Get(Stream_Image, Pos, __T("Density_X"));
            Ztring ySamplingFrequency=MI.Get(Stream_Image, Pos, __T("Density_Y"));
            if (!xSamplingFrequency.empty() || !ySamplingFrequency.empty())
            {
                Node* Node_SpatialMetrics=Node_ImageAssessmentMetadata->Add_Child("mix:SpatialMetrics");

                if (samplingFrequencyUnit.empty())
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("no absolute unit of measurement"));
                else if (samplingFrequencyUnit=="dpi")
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("in."));
                else if (samplingFrequencyUnit=="dpcm")
                    Node_SpatialMetrics->Add_Child("mix:samplingFrequencyUnit", string("cm"));

                if (!xSamplingFrequency.empty())
                    ComputeSamplingFrequency(Node_SpatialMetrics->Add_Child("mix:xSamplingFrequency"), xSamplingFrequency);
                if (!ySamplingFrequency.empty())
                    ComputeSamplingFrequency(Node_SpatialMetrics->Add_Child("mix:ySamplingFrequency"), ySamplingFrequency);
            }

            size_t SamplesPerPixel=MI.Get(Stream_Image, Pos, Image_ColorSpace).length();
            if (SamplesPerPixel)
            {
                Node* Node_ImageColorEncoding=Node_ImageAssessmentMetadata->Add_Child("mix:ImageColorEncoding");

                Node* Node_BitsPerSample=new Node("mix:BitsPerSample");
                for (size_t Pos2=0; Pos2<SamplesPerPixel; ++Pos2)
                    Node_BitsPerSample->Add_Child_IfNotEmpty(MI, Stream_Image, Pos, Image_BitDepth, "mix:bitsPerSampleValue");

                if (!Node_BitsPerSample->Childs.empty())
                {
                    Node_BitsPerSample->Add_Child("mix:bitsPerSampleUnit", std::string("integer"));
                    Node_ImageColorEncoding->Childs.push_back(Node_BitsPerSample);
                }
                else
                   delete Node_BitsPerSample;

                Node_ImageColorEncoding->Add_Child("mix:samplesPerPixel", Ztring().From_Number(SamplesPerPixel).To_UTF8());
            }
        }

        if (Node_Extension)
            Node_Root->Childs.push_back(Node_Extension);

        ToReturn+=Ztring().From_UTF8(To_XML(*Node_Root, 0, true, true).c_str());
    }

    if (ToReturn.empty())
        ToReturn+=Ztring().From_UTF8(To_XML(*Transform_Header(), 0, true, true).c_str())+=__T("\n");

    //Carriage return
    if (MediaInfoLib::Config.LineSeparator_Get()!=__T("\n"))
        ToReturn.FindAndReplace(__T("\n"), MediaInfoLib::Config.LineSeparator_Get(), 0, Ztring_Recursive);

    return ToReturn;
}

//***************************************************************************
//
//***************************************************************************

} //NameSpace

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: strmsys.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 13:03:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#if defined WNT
#include "strmwnt.cxx"
#elif defined UNX
#include "strmunx.cxx"
#elif defined OS2
#include "strmos2.cxx"
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.58); FILE MERGED 2008/03/28 15:41:27 rt 1.6.58.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: strmsys.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#if defined WNT
#include "strmwnt.cxx"
#elif defined UNX
#include "strmunx.cxx"
#elif defined OS2
#include "strmos2.cxx"
#endif
<|endoftext|>


<commit_before>/*
 * SourceIndex.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SourceIndex.hpp"

#include "UnsavedFiles.hpp"

using namespace core ;

namespace session {
namespace modules {
namespace clang {
namespace libclang {

SourceIndex::SourceIndex()
{
   index_ = clang().createIndex(0, 0);
}

SourceIndex::~SourceIndex()
{
   try
   {
      // dispose all translation units
      for(TranslationUnits::const_iterator it = translationUnits_.begin();
          it != translationUnits_.end(); ++it)
      {
         clang().disposeTranslationUnit(it->second);
      }

      // dispose the index
      clang().disposeIndex(index_);
   }
   catch(...)
   {
   }
}

unsigned SourceIndex::getGlobalOptions() const
{
   return clang().CXIndex_getGlobalOptions(index_);
}

void SourceIndex::setGlobalOptions(unsigned options)
{
   clang().CXIndex_setGlobalOptions(index_, options);
}

void SourceIndex::updateTranslationUnit(const std::string& filename)
{
   // check for an existing translation unit, if we don't have one then
   // parse the source file into a translation unit
   TranslationUnits::iterator it = translationUnits_.find(filename);
   if (it == translationUnits_.end())
   {

      // for now we use the default R command line args for an Rcpp
      // package on OSX. We ultimately need to do this dynamically.
      // The best way to accomplish this would seem to be the creation
      // of a compliation database json file and then the reading of it
      // via clang_CompilationDatabase_getCompileCommands
      const char *args[] = {
         "-I/Library/Frameworks/R.framework/Resources/include",
         "-DNDEBUG",
         "-I/usr/local/include/freetype2",
         "-I/opt/X11/include",
         "-I/Library/Frameworks/R.framework/Resources/library/Rcpp/include"
      };
      int numArgs = sizeof(args) / sizeof(*args);

      // create a new translation unit from the file
      CXTranslationUnit tu = clang().parseTranslationUnit(
                            index_,
                            filename.c_str(),
                            args,
                            numArgs,
                            unsavedFiles().unsavedFilesArray(),
                            unsavedFiles().numUnsavedFiles(),
                            clang().defaultEditingTranslationUnitOptions());

      // save it if we succeeded
      if (tu != NULL)
      {
         translationUnits_[filename] = tu;
      }
      else
      {
         LOG_ERROR_MESSAGE("Error parsing translation unit " + filename);
      }
   }

   // lookup and reparse the translation unit (multiple sources indicate that
   // you need to immediately reparse the translation unit after creation
   // in order to get the benefit of precompiled headers). note that this
   // lookup will fail in the case of error occurring during parsing above
   it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
   {
      int ret = clang().reparseTranslationUnit(
                                  it->second,
                                  unsavedFiles().numUnsavedFiles(),
                                  unsavedFiles().unsavedFilesArray(),
                                  clang().defaultReparseOptions(it->second));

      // if this returns an error then we need to dispose the translation unit
      if (ret != 0)
      {
         LOG_ERROR_MESSAGE("Error re-parsing translation unit " + filename);
         removeTranslationUnit(filename);
      }
   }
}

void SourceIndex::removeTranslationUnit(const std::string& filename)
{
   TranslationUnits::iterator it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
   {
      clang().disposeTranslationUnit(it->second);
      translationUnits_.erase(it->first);
   }
}

bool SourceIndex::hasTranslationUnit(const std::string& filename)
{
   return translationUnits_.find(filename) != translationUnits_.end();
}

TranslationUnit SourceIndex::getTranslationUnit(
                                          const std::string& filename) const
{
   TranslationUnits::const_iterator it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
      return TranslationUnit(it->first, it->second);
   else
      return TranslationUnit();
}

// singleton
SourceIndex& sourceIndex()
{
   static SourceIndex instance;
   return instance;
}

} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session

<commit_msg>add libstdc++ and /usr/local/include to mac defaults<commit_after>/*
 * SourceIndex.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SourceIndex.hpp"

#include "UnsavedFiles.hpp"

using namespace core ;

namespace session {
namespace modules {
namespace clang {
namespace libclang {

SourceIndex::SourceIndex()
{
   index_ = clang().createIndex(0, 0);
}

SourceIndex::~SourceIndex()
{
   try
   {
      // dispose all translation units
      for(TranslationUnits::const_iterator it = translationUnits_.begin();
          it != translationUnits_.end(); ++it)
      {
         clang().disposeTranslationUnit(it->second);
      }

      // dispose the index
      clang().disposeIndex(index_);
   }
   catch(...)
   {
   }
}

unsigned SourceIndex::getGlobalOptions() const
{
   return clang().CXIndex_getGlobalOptions(index_);
}

void SourceIndex::setGlobalOptions(unsigned options)
{
   clang().CXIndex_setGlobalOptions(index_, options);
}

void SourceIndex::updateTranslationUnit(const std::string& filename)
{
   // check for an existing translation unit, if we don't have one then
   // parse the source file into a translation unit
   TranslationUnits::iterator it = translationUnits_.find(filename);
   if (it == translationUnits_.end())
   {

      // for now we use the default R command line args for an Rcpp
      // package on OSX. We ultimately need to do this dynamically.
      // The best way to accomplish this would seem to be the creation
      // of a compliation database json file and then the reading of it
      // via clang_CompilationDatabase_getCompileCommands
      const char *args[] = {
         "-stdlib=libstdc++",
         "-I/Library/Frameworks/R.framework/Resources/include",
         "-DNDEBUG",
         "-I/usr/local/include",
         "-I/usr/local/include/freetype2",
         "-I/opt/X11/include",
         "-I/Library/Frameworks/R.framework/Resources/library/Rcpp/include"
      };
      int numArgs = sizeof(args) / sizeof(*args);

      // create a new translation unit from the file
      CXTranslationUnit tu = clang().parseTranslationUnit(
                            index_,
                            filename.c_str(),
                            args,
                            numArgs,
                            unsavedFiles().unsavedFilesArray(),
                            unsavedFiles().numUnsavedFiles(),
                            clang().defaultEditingTranslationUnitOptions());

      // save it if we succeeded
      if (tu != NULL)
      {
         translationUnits_[filename] = tu;
      }
      else
      {
         LOG_ERROR_MESSAGE("Error parsing translation unit " + filename);
      }
   }

   // lookup and reparse the translation unit (multiple sources indicate that
   // you need to immediately reparse the translation unit after creation
   // in order to get the benefit of precompiled headers). note that this
   // lookup will fail in the case of error occurring during parsing above
   it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
   {
      int ret = clang().reparseTranslationUnit(
                                  it->second,
                                  unsavedFiles().numUnsavedFiles(),
                                  unsavedFiles().unsavedFilesArray(),
                                  clang().defaultReparseOptions(it->second));

      // if this returns an error then we need to dispose the translation unit
      if (ret != 0)
      {
         LOG_ERROR_MESSAGE("Error re-parsing translation unit " + filename);
         removeTranslationUnit(filename);
      }
   }
}

void SourceIndex::removeTranslationUnit(const std::string& filename)
{
   TranslationUnits::iterator it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
   {
      clang().disposeTranslationUnit(it->second);
      translationUnits_.erase(it->first);
   }
}

bool SourceIndex::hasTranslationUnit(const std::string& filename)
{
   return translationUnits_.find(filename) != translationUnits_.end();
}

TranslationUnit SourceIndex::getTranslationUnit(
                                          const std::string& filename) const
{
   TranslationUnits::const_iterator it = translationUnits_.find(filename);
   if (it != translationUnits_.end())
      return TranslationUnit(it->first, it->second);
   else
      return TranslationUnit();
}

// singleton
SourceIndex& sourceIndex()
{
   static SourceIndex instance;
   return instance;
}

} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QWidget>
#include <qaccelerometer.h>
#include <qorientationsensor.h>

class MyWidget : public QWidget
{
    void create();
};

void MyWidget::create()
{
//! [Creating a sensor]
// On the heap (deleted when this object is deleted)
QAccelerometer *sensor = new QAccelerometer(this);

// On the stack (deleted when the current scope ends)
QOrientationSensor orient_sensor;
//! [Creating a sensor]

    Q_UNUSED(sensor)
    Q_UNUSED(orient_sensor);
}

<commit_msg>Don't include QWidget.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QObject>
#include <qaccelerometer.h>
#include <qorientationsensor.h>

class MyObject : public QObject
{
    void create();
};

void MyObject::create()
{
//! [Creating a sensor]
// On the heap (deleted when this object is deleted)
QAccelerometer *sensor = new QAccelerometer(this);

// On the stack (deleted when the current scope ends)
QOrientationSensor orient_sensor;
//! [Creating a sensor]

    Q_UNUSED(sensor)
    Q_UNUSED(orient_sensor);
}

<|endoftext|>


<commit_before>/*
 * SessionPanmirror.cpp
 *
 * Copyright (C) 2009-16 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPanmirror.hpp"

#include <shared_core/Error.hpp>
#include <core/Exec.hpp>
#include <core/StringUtils.hpp>

#include <core/system/Process.hpp>

#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {

namespace {

Error runPandoc(const std::vector<std::string>& args, const std::string& input, core::system::ProcessResult* pResult)
{
   FilePath pandocPath = FilePath(core::system::getenv("RSTUDIO_PANDOC")).completeChildPath("pandoc");
   return core::system::runProgram(
      string_utils::utf8ToSystem(pandocPath.getAbsolutePath()),
      args,
      input,
      core::system::ProcessOptions(),
      pResult
   );
}

Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
   for(json::Array::Iterator
         it = options.begin();
         it != options.end();
         ++it)
   {
      if ((*it).getType() != json::Type::STRING)
         return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);

      std::string option = (*it).getString() ;
      pOptions->push_back(option);
   }
   return Success();
}

std::string errorMessage(const Error& error)
{
   std::string msg = error.getMessage();
   if (msg.length() == 0)
   {
      msg = error.getProperty("category");
   }
   if (msg.length() == 0)
   {
      msg = error.getName();
   }
   return msg;
}

void setPandocErrorResponse(const Error& error,
                            json::JsonRpcResponse* pResponse)
{
   LOG_ERROR(error);
   pResponse->setError(error, errorMessage(error));
}

void setPandocErrorResponse(const core::system::ProcessResult& result,
                            json::JsonRpcResponse* pResponse)
{
   Error error = systemError(boost::system::errc::state_not_recoverable, result.stdErr, ERROR_LOCATION);
   LOG_ERROR(error);
   pResponse->setError(error, result.stdErr);
}

Error pandocAstToMarkdown(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // extract params
   json::Object jsonAst;
   std::string format;
   json::Array jsonOptions;
   Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back("json");
   args.push_back("--to");
   args.push_back(format);
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, jsonAst.write(), &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   if (result.exitStatus == EXIT_SUCCESS)
   {
      pResponse->setResult(result.stdOut);
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

Error pandocMarkdownToAst(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // extract params
   json::Array jsonOptions;
   std::string markdown, format;
   Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back(format);
   args.push_back("--to");
   args.push_back("json");
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, markdown, &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // return output on success
   if (result.exitStatus == EXIT_SUCCESS)
   {
      using namespace json;
      json::Value jsonAst;
      Error error = jsonAst.parse(result.stdOut);
      if (error)
      {
         Error parseError(boost::system::errc::state_not_recoverable,
                          errorMessage(error),
                          ERROR_LOCATION);
         setPandocErrorResponse(parseError, pResponse);
      }
      else if (!isType<json::Object>(jsonAst))
      {
         Error outputError(boost::system::errc::state_not_recoverable,
                           "Unexpected JSON output from pandoc",
                           ERROR_LOCATION);
         setPandocErrorResponse(outputError, pResponse);
      }
      else
      {
         pResponse->setResult(jsonAst);
      }
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

Error pandocListExtensions(const json::JsonRpcRequest& request,
                           json::JsonRpcResponse* pResponse)
{
   // extract format
   std::string format;
   Error error = json::readParams(request.params, &format);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   std::string extensions =  "--list-extensions";
   if (!format.empty())
      extensions += ('=' + format);
   args.push_back(extensions);

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, "", &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // return output on success
   if (result.exitStatus == EXIT_SUCCESS)
   {
      pResponse->setResult(result.stdOut);
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
      (boost::bind(module_context::registerRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
      (boost::bind(module_context::registerRpcMethod, "pandoc_list_extensions", pandocListExtensions))
   ;
   return initBlock.execute();
}

} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>correct path to pandoc on win32<commit_after>/*
 * SessionPanmirror.cpp
 *
 * Copyright (C) 2009-16 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPanmirror.hpp"

#include <shared_core/Error.hpp>
#include <core/Exec.hpp>
#include <core/StringUtils.hpp>

#include <core/system/Process.hpp>

#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {

namespace {

Error runPandoc(const std::vector<std::string>& args, const std::string& input, core::system::ProcessResult* pResult)
{
#ifndef WIN32
   std::string pandoc = "pandoc";
#else
   std::string pandoc = "pandoc.exe";
#endif
   FilePath pandocPath = FilePath(core::system::getenv("RSTUDIO_PANDOC")).completeChildPath(pandoc);
   return core::system::runProgram(
      string_utils::utf8ToSystem(pandocPath.getAbsolutePath()),
      args,
      input,
      core::system::ProcessOptions(),
      pResult
   );
}

Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
   for(json::Array::Iterator
         it = options.begin();
         it != options.end();
         ++it)
   {
      if ((*it).getType() != json::Type::STRING)
         return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);

      std::string option = (*it).getString() ;
      pOptions->push_back(option);
   }
   return Success();
}

std::string errorMessage(const Error& error)
{
   std::string msg = error.getMessage();
   if (msg.length() == 0)
   {
      msg = error.getProperty("category");
   }
   if (msg.length() == 0)
   {
      msg = error.getName();
   }
   return msg;
}

void setPandocErrorResponse(const Error& error,
                            json::JsonRpcResponse* pResponse)
{
   LOG_ERROR(error);
   pResponse->setError(error, errorMessage(error));
}

void setPandocErrorResponse(const core::system::ProcessResult& result,
                            json::JsonRpcResponse* pResponse)
{
   Error error = systemError(boost::system::errc::state_not_recoverable, result.stdErr, ERROR_LOCATION);
   LOG_ERROR(error);
   pResponse->setError(error, result.stdErr);
}

Error pandocAstToMarkdown(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // extract params
   json::Object jsonAst;
   std::string format;
   json::Array jsonOptions;
   Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back("json");
   args.push_back("--to");
   args.push_back(format);
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, jsonAst.write(), &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   if (result.exitStatus == EXIT_SUCCESS)
   {
      pResponse->setResult(result.stdOut);
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

Error pandocMarkdownToAst(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // extract params
   json::Array jsonOptions;
   std::string markdown, format;
   Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back(format);
   args.push_back("--to");
   args.push_back("json");
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, markdown, &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // return output on success
   if (result.exitStatus == EXIT_SUCCESS)
   {
      using namespace json;
      json::Value jsonAst;
      Error error = jsonAst.parse(result.stdOut);
      if (error)
      {
         Error parseError(boost::system::errc::state_not_recoverable,
                          errorMessage(error),
                          ERROR_LOCATION);
         setPandocErrorResponse(parseError, pResponse);
      }
      else if (!isType<json::Object>(jsonAst))
      {
         Error outputError(boost::system::errc::state_not_recoverable,
                           "Unexpected JSON output from pandoc",
                           ERROR_LOCATION);
         setPandocErrorResponse(outputError, pResponse);
      }
      else
      {
         pResponse->setResult(jsonAst);
      }
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

Error pandocListExtensions(const json::JsonRpcRequest& request,
                           json::JsonRpcResponse* pResponse)
{
   // extract format
   std::string format;
   Error error = json::readParams(request.params, &format);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // build args
   std::vector<std::string> args;
   std::string extensions =  "--list-extensions";
   if (!format.empty())
      extensions += ('=' + format);
   args.push_back(extensions);

   // run pandoc
   core::system::ProcessResult result;
   error = runPandoc(args, "", &result);
   if (error)
   {
      setPandocErrorResponse(error, pResponse);
      return Success();
   }

   // return output on success
   if (result.exitStatus == EXIT_SUCCESS)
   {
      pResponse->setResult(result.stdOut);
   }
   else
   {
      setPandocErrorResponse(result, pResponse);
   }

   return Success();
}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
      (boost::bind(module_context::registerRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
      (boost::bind(module_context::registerRpcMethod, "pandoc_list_extensions", pandocListExtensions))
   ;
   return initBlock.execute();
}

} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <machine/Machine.h>
#include <utilities/StaticString.h>

extern "C" void __cyg_profile_func_enter (void *func_address, void *call_site)
  __attribute__((no_instrument_function));
extern "C" void __cyg_profile_func_exit (void *func_address, void *call_site)
  __attribute__((no_instrument_function));

#define OUT(c) asm volatile ("outb %%al, %%dx" :: "d"(0x2f8), "a"(c))

extern "C" void __cyg_profile_func_enter (void *func_address, void *call_site)
{
    uint32_t _func_address = reinterpret_cast<uintptr_t>(func_address)&0xFFFFFFFF;
    uint32_t _call_site = reinterpret_cast<uintptr_t>(call_site)&0xFFFFFFFF;

//    register int eflags;
//    asm volatile ("pushf; pop %0; cli" : "=r" (eflags));
    OUT('E');
    OUT('0' + ((_func_address>>(32-4))&0xF));
    OUT('0' + ((_func_address>>(32-8))&0xF));
    OUT('0' + ((_func_address>>(32-12))&0xF));
    OUT('0' + ((_func_address>>(32-16))&0xF));
    OUT('0' + ((_func_address>>(32-20))&0xF));
    OUT('0' + ((_func_address>>(32-24))&0xF));
    OUT('0' + ((_func_address>>(32-28))&0xF));
    OUT('0' + ((_func_address>>(32-32))&0xF));
    OUT(' ');
    OUT('0' + ((_call_site>>(32-4))&0xF));
    OUT('0' + ((_call_site>>(32-8))&0xF));
    OUT('0' + ((_call_site>>(32-12))&0xF));
    OUT('0' + ((_call_site>>(32-16))&0xF));
    OUT('0' + ((_call_site>>(32-20))&0xF));
    OUT('0' + ((_call_site>>(32-24))&0xF));
    OUT('0' + ((_call_site>>(32-28))&0xF));
    OUT('0' + ((_call_site>>(32-32))&0xF));
    OUT('\n');
//    asm volatile("push %0; popf" ::"r" (eflags));
}

extern "C" void __cyg_profile_func_exit (void *func_address, void *call_site)
{
}
<commit_msg>Fix x86-only inline assembly in instrument.cc<commit_after>/*
 * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <machine/Machine.h>
#include <utilities/StaticString.h>

extern "C" void __cyg_profile_func_enter (void *func_address, void *call_site)
  __attribute__((no_instrument_function));
extern "C" void __cyg_profile_func_exit (void *func_address, void *call_site)
  __attribute__((no_instrument_function));

#ifdef X86_COMMON
#define OUT(c) asm volatile ("outb %%al, %%dx" :: "d"(0x2f8), "a"(c))
#else
#define OUT(C)
#endif

extern "C" void __cyg_profile_func_enter (void *func_address, void *call_site)
{
    uint32_t _func_address = reinterpret_cast<uintptr_t>(func_address)&0xFFFFFFFF;
    uint32_t _call_site = reinterpret_cast<uintptr_t>(call_site)&0xFFFFFFFF;

//    register int eflags;
//    asm volatile ("pushf; pop %0; cli" : "=r" (eflags));
    OUT('E');
    OUT('0' + ((_func_address>>(32-4))&0xF));
    OUT('0' + ((_func_address>>(32-8))&0xF));
    OUT('0' + ((_func_address>>(32-12))&0xF));
    OUT('0' + ((_func_address>>(32-16))&0xF));
    OUT('0' + ((_func_address>>(32-20))&0xF));
    OUT('0' + ((_func_address>>(32-24))&0xF));
    OUT('0' + ((_func_address>>(32-28))&0xF));
    OUT('0' + ((_func_address>>(32-32))&0xF));
    OUT(' ');
    OUT('0' + ((_call_site>>(32-4))&0xF));
    OUT('0' + ((_call_site>>(32-8))&0xF));
    OUT('0' + ((_call_site>>(32-12))&0xF));
    OUT('0' + ((_call_site>>(32-16))&0xF));
    OUT('0' + ((_call_site>>(32-20))&0xF));
    OUT('0' + ((_call_site>>(32-24))&0xF));
    OUT('0' + ((_call_site>>(32-28))&0xF));
    OUT('0' + ((_call_site>>(32-32))&0xF));
    OUT('\n');
//    asm volatile("push %0; popf" ::"r" (eflags));
}

extern "C" void __cyg_profile_func_exit (void *func_address, void *call_site)
{
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2014 PX4 Development Team. All rights reserved.
 *   Author: Holger Steinhaus <hsteinhaus@gmx.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file motor_test.c
 *
 * Tool for drive testing
 */

#include <drivers/drv_hrt.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <uORB/PublicationQueued.hpp>
#include <uORB/topics/test_motor.h>

extern "C" __EXPORT int motor_test_main(int argc, char *argv[]);

static void motor_test(unsigned channel, float value, uint8_t driver_instance, int timeout_ms);
static void usage(const char *reason);

void motor_test(unsigned channel, float value, uint8_t driver_instance, int timeout_ms)
{
	test_motor_s test_motor{};
	test_motor.timestamp = hrt_absolute_time();
	test_motor.motor_number = channel;
	test_motor.value = value;
	test_motor.action = value >= 0.f ? test_motor_s::ACTION_RUN : test_motor_s::ACTION_STOP;
	test_motor.driver_instance = driver_instance;
	test_motor.timeout_ms = timeout_ms;

	uORB::PublicationQueued<test_motor_s> test_motor_pub{ORB_ID(test_motor)};
	test_motor_pub.publish(test_motor);

	if (test_motor.action == test_motor_s::ACTION_STOP) {
		PX4_INFO("motors stop command sent");

	} else {
		PX4_INFO("motor %d set to %.2f", channel, (double)value);
	}
}

static void usage(const char *reason)
{
	if (reason != nullptr) {
		PX4_WARN("%s", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
Utility to test motors.

WARNING: remove all props before using this command.

Note: this can only be used for drivers which support the motor_test uorb topic (not px4io).
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("motor_test", "command");
	PRINT_MODULE_USAGE_COMMAND_DESCR("test", "Set motor(s) to a specific output value");
	PRINT_MODULE_USAGE_PARAM_INT('m', -1, 0, 7, "Motor to test (0...7, all if not specified)", true);
	PRINT_MODULE_USAGE_PARAM_INT('p', 0, 0, 100, "Power (0...100)", true);
	PRINT_MODULE_USAGE_PARAM_INT('t', 0, 0, 100, "Timeout in seconds (default=no timeout)", true);
	PRINT_MODULE_USAGE_PARAM_INT('i', 0, 0, 4, "driver instance", true);
	PRINT_MODULE_USAGE_COMMAND_DESCR("stop", "Stop all motors");
	PRINT_MODULE_USAGE_COMMAND_DESCR("iterate", "Iterate all motors starting and stopping one after the other");

}

int motor_test_main(int argc, char *argv[])
{
	int channel = -1; //default to all channels
	unsigned long lval;
	float value = 0.0f;
	uint8_t driver_instance = 0;
	int ch;
	int timeout_ms = 0;

	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "i:m:p:t:", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {

		case 'i':
			driver_instance = (uint8_t)strtol(myoptarg, nullptr, 0);
			break;

		case 'm':
			/* Read in motor number */
			channel = (int)strtol(myoptarg, nullptr, 0);
			break;

		case 'p':
			/* Read in power value */
			lval = strtoul(myoptarg, nullptr, 0);

			if (lval > 100) {
				usage("value invalid");
				return 1;
			}

			value = ((float)lval) / 100.f;
			break;

		case 't':
			timeout_ms = strtol(myoptarg, nullptr, 0) * 1000;
			break;

		default:
			usage(nullptr);
			return 1;
		}
	}

	bool run_test = true;

	if (myoptind >= 0 && myoptind < argc) {
		if (strcmp("stop", argv[myoptind]) == 0) {
			channel = 0;
			value = -1.f;

		} else if (strcmp("iterate", argv[myoptind]) == 0) {
			value = 0.15f;

			for (int i = 0; i < 8; ++i) {
				motor_test(i, value, driver_instance, 0);
				px4_usleep(500000);
				motor_test(i, -1.f, driver_instance, 0);
				px4_usleep(10000);
			}

			run_test = false;

		} else if (strcmp("test", argv[myoptind]) == 0) {
			// nothing to do
		} else {
			usage(nullptr);
			return 0;
		}

	} else {
		usage(nullptr);
		return 0;
	}

	if (run_test) {
		if (channel < 0) {
			for (int i = 0; i < 8; ++i) {
				motor_test(i, value, driver_instance, timeout_ms);
				px4_usleep(10000);
			}

		} else {
			motor_test(channel, value, driver_instance, timeout_ms);
		}
	}

	return 0;
}
<commit_msg>motor_test: remove note about supported drivers<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2014 PX4 Development Team. All rights reserved.
 *   Author: Holger Steinhaus <hsteinhaus@gmx.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file motor_test.c
 *
 * Tool for drive testing
 */

#include <drivers/drv_hrt.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <uORB/PublicationQueued.hpp>
#include <uORB/topics/test_motor.h>

extern "C" __EXPORT int motor_test_main(int argc, char *argv[]);

static void motor_test(unsigned channel, float value, uint8_t driver_instance, int timeout_ms);
static void usage(const char *reason);

void motor_test(unsigned channel, float value, uint8_t driver_instance, int timeout_ms)
{
	test_motor_s test_motor{};
	test_motor.timestamp = hrt_absolute_time();
	test_motor.motor_number = channel;
	test_motor.value = value;
	test_motor.action = value >= 0.f ? test_motor_s::ACTION_RUN : test_motor_s::ACTION_STOP;
	test_motor.driver_instance = driver_instance;
	test_motor.timeout_ms = timeout_ms;

	uORB::PublicationQueued<test_motor_s> test_motor_pub{ORB_ID(test_motor)};
	test_motor_pub.publish(test_motor);

	if (test_motor.action == test_motor_s::ACTION_STOP) {
		PX4_INFO("motors stop command sent");

	} else {
		PX4_INFO("motor %d set to %.2f", channel, (double)value);
	}
}

static void usage(const char *reason)
{
	if (reason != nullptr) {
		PX4_WARN("%s", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
Utility to test motors.

WARNING: remove all props before using this command.
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("motor_test", "command");
	PRINT_MODULE_USAGE_COMMAND_DESCR("test", "Set motor(s) to a specific output value");
	PRINT_MODULE_USAGE_PARAM_INT('m', -1, 0, 7, "Motor to test (0...7, all if not specified)", true);
	PRINT_MODULE_USAGE_PARAM_INT('p', 0, 0, 100, "Power (0...100)", true);
	PRINT_MODULE_USAGE_PARAM_INT('t', 0, 0, 100, "Timeout in seconds (default=no timeout)", true);
	PRINT_MODULE_USAGE_PARAM_INT('i', 0, 0, 4, "driver instance", true);
	PRINT_MODULE_USAGE_COMMAND_DESCR("stop", "Stop all motors");
	PRINT_MODULE_USAGE_COMMAND_DESCR("iterate", "Iterate all motors starting and stopping one after the other");

}

int motor_test_main(int argc, char *argv[])
{
	int channel = -1; //default to all channels
	unsigned long lval;
	float value = 0.0f;
	uint8_t driver_instance = 0;
	int ch;
	int timeout_ms = 0;

	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "i:m:p:t:", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {

		case 'i':
			driver_instance = (uint8_t)strtol(myoptarg, nullptr, 0);
			break;

		case 'm':
			/* Read in motor number */
			channel = (int)strtol(myoptarg, nullptr, 0);
			break;

		case 'p':
			/* Read in power value */
			lval = strtoul(myoptarg, nullptr, 0);

			if (lval > 100) {
				usage("value invalid");
				return 1;
			}

			value = ((float)lval) / 100.f;
			break;

		case 't':
			timeout_ms = strtol(myoptarg, nullptr, 0) * 1000;
			break;

		default:
			usage(nullptr);
			return 1;
		}
	}

	bool run_test = true;

	if (myoptind >= 0 && myoptind < argc) {
		if (strcmp("stop", argv[myoptind]) == 0) {
			channel = 0;
			value = -1.f;

		} else if (strcmp("iterate", argv[myoptind]) == 0) {
			value = 0.15f;

			for (int i = 0; i < 8; ++i) {
				motor_test(i, value, driver_instance, 0);
				px4_usleep(500000);
				motor_test(i, -1.f, driver_instance, 0);
				px4_usleep(10000);
			}

			run_test = false;

		} else if (strcmp("test", argv[myoptind]) == 0) {
			// nothing to do
		} else {
			usage(nullptr);
			return 0;
		}

	} else {
		usage(nullptr);
		return 0;
	}

	if (run_test) {
		if (channel < 0) {
			for (int i = 0; i < 8; ++i) {
				motor_test(i, value, driver_instance, timeout_ms);
				px4_usleep(10000);
			}

		} else {
			motor_test(channel, value, driver_instance, timeout_ms);
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
* BM3D denoising filter - VapourSynth plugin
* Copyright (C) 2015  mawen1250
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "BM3D.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions of struct BM3D_Para

BM3D_Para::BM3D_Para(bool _wiener, std::string _profile)
    : wiener(_wiener), profile(_profile), sigma({ 10.0, 10.0, 10.0 })
{
    BlockSize = 8;
    BMrange = 16;
    BMstep = 1;

    if (!wiener)
    {
        BlockStep = 4;
        GroupSize = 16;
        lambda = 2.7;
    }
    else
    {
        BlockStep = 3;
        GroupSize = 32;
    }

    if (profile == "fast")
    {
        BMrange = 9;

        if (!wiener)
        {
            BlockStep = 8;
        }
        else
        {
            BlockStep = 7;
            GroupSize = 16;
        }
    }
    else if (profile == "lc")
    {
        BMrange = 9;

        if (!wiener)
        {
            BlockStep = 6;
        }
        else
        {
            BlockStep = 5;
            GroupSize = 16;
        }
    }
    else if (profile == "high")
    {
        if (!wiener)
        {
            BlockStep = 3;
        }
        else
        {
            BlockStep = 2;
        }
    }
    else if (profile == "vn")
    {
        if (!wiener)
        {
            BlockStep = 4;
            GroupSize = 32;
            lambda = 2.8;
        }
        else
        {
            BlockSize = 11;
            BlockStep = 6;
        }
    }

    thMSE_Default();
}

void BM3D_Para::thMSE_Default()
{
    if (!wiener)
    {
        thMSE = 400 + sigma[0] * 80;

        if (profile == "vn")
        {
            thMSE = 1000 + sigma[0] * 150;
        }
    }
    else
    {
        thMSE = 200 + sigma[0] * 10;

        if (profile == "vn")
        {
            thMSE = 400 + sigma[0] * 40;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions of struct BM3D_FilterData

BM3D_FilterData::BM3D_FilterData(bool wiener, double sigma, PCType GroupSize, PCType BlockSize, double lambda)
    : fp(GroupSize), bp(GroupSize), finalAMP(GroupSize), thrTable(wiener ? 0 : GroupSize),
    wienerSigmaSqr(wiener ? GroupSize : 0)
{
    const unsigned int flags = FFTW_PATIENT;
    const fftw::r2r_kind fkind = FFTW_REDFT10;
    const fftw::r2r_kind bkind = FFTW_REDFT01;

    FLType *temp = nullptr;

    for (PCType i = 1; i <= GroupSize; ++i)
    {
        AlignedMalloc(temp, i * BlockSize * BlockSize);
        fp[i - 1].r2r_3d(i, BlockSize, BlockSize, temp, temp, fkind, fkind, fkind, flags);
        bp[i - 1].r2r_3d(i, BlockSize, BlockSize, temp, temp, bkind, bkind, bkind, flags);
        AlignedFree(temp);

        finalAMP[i - 1] = 2 * i * 2 * BlockSize * 2 * BlockSize;
        double forwardAMP = sqrt(finalAMP[i - 1]);

        if (wiener)
        {
            wienerSigmaSqr[i - 1] = static_cast<FLType>(sigma * forwardAMP * sigma * forwardAMP);
        }
        else
        {
            double thrBase = sigma * lambda * forwardAMP;
            std::vector<double> thr(4);

            thr[0] = thrBase;
            thr[1] = thrBase * sqrt(double(2));
            thr[2] = thrBase * double(2);
            thr[3] = thrBase * sqrt(double(8));

            thrTable[i - 1] = std::vector<FLType>(i * BlockSize * BlockSize);
            auto thr_d = thrTable[i - 1].data();

            for (PCType z = 0; z < i; ++z)
            {
                for (PCType y = 0; y < BlockSize; ++y)
                {
                    for (PCType x = 0; x < BlockSize; ++x, ++thr_d)
                    {
                        int flag = 0;

                        if (x == 0)
                        {
                            ++flag;
                        }
                        if (y == 0)
                        {
                            ++flag;
                        }
                        if (z == 0)
                        {
                            ++flag;
                        }

                        *thr_d = static_cast<FLType>(thr[flag]);
                    }
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Speed up: default value of group_size reduced from 16/16 to 8/8 for BM3D profile="fast"<commit_after>/*
* BM3D denoising filter - VapourSynth plugin
* Copyright (C) 2015  mawen1250
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "BM3D.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions of struct BM3D_Para

BM3D_Para::BM3D_Para(bool _wiener, std::string _profile)
    : wiener(_wiener), profile(_profile), sigma({ 10.0, 10.0, 10.0 })
{
    BlockSize = 8;
    BMrange = 16;
    BMstep = 1;

    if (!wiener)
    {
        BlockStep = 4;
        GroupSize = 16;
        lambda = 2.7;
    }
    else
    {
        BlockStep = 3;
        GroupSize = 32;
    }

    if (profile == "fast")
    {
        BMrange = 9;
        GroupSize = 8;

        if (!wiener)
        {
            BlockStep = 8;
        }
        else
        {
            BlockStep = 7;
        }
    }
    else if (profile == "lc")
    {
        BMrange = 9;

        if (!wiener)
        {
            BlockStep = 6;
        }
        else
        {
            BlockStep = 5;
            GroupSize = 16;
        }
    }
    else if (profile == "high")
    {
        if (!wiener)
        {
            BlockStep = 3;
        }
        else
        {
            BlockStep = 2;
        }
    }
    else if (profile == "vn")
    {
        if (!wiener)
        {
            BlockStep = 4;
            GroupSize = 32;
            lambda = 2.8;
        }
        else
        {
            BlockSize = 11;
            BlockStep = 6;
        }
    }

    thMSE_Default();
}

void BM3D_Para::thMSE_Default()
{
    if (!wiener)
    {
        thMSE = 400 + sigma[0] * 80;

        if (profile == "vn")
        {
            thMSE = 1000 + sigma[0] * 150;
        }
    }
    else
    {
        thMSE = 200 + sigma[0] * 10;

        if (profile == "vn")
        {
            thMSE = 400 + sigma[0] * 40;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions of struct BM3D_FilterData

BM3D_FilterData::BM3D_FilterData(bool wiener, double sigma, PCType GroupSize, PCType BlockSize, double lambda)
    : fp(GroupSize), bp(GroupSize), finalAMP(GroupSize), thrTable(wiener ? 0 : GroupSize),
    wienerSigmaSqr(wiener ? GroupSize : 0)
{
    const unsigned int flags = FFTW_PATIENT;
    const fftw::r2r_kind fkind = FFTW_REDFT10;
    const fftw::r2r_kind bkind = FFTW_REDFT01;

    FLType *temp = nullptr;

    for (PCType i = 1; i <= GroupSize; ++i)
    {
        AlignedMalloc(temp, i * BlockSize * BlockSize);
        fp[i - 1].r2r_3d(i, BlockSize, BlockSize, temp, temp, fkind, fkind, fkind, flags);
        bp[i - 1].r2r_3d(i, BlockSize, BlockSize, temp, temp, bkind, bkind, bkind, flags);
        AlignedFree(temp);

        finalAMP[i - 1] = 2 * i * 2 * BlockSize * 2 * BlockSize;
        double forwardAMP = sqrt(finalAMP[i - 1]);

        if (wiener)
        {
            wienerSigmaSqr[i - 1] = static_cast<FLType>(sigma * forwardAMP * sigma * forwardAMP);
        }
        else
        {
            double thrBase = sigma * lambda * forwardAMP;
            std::vector<double> thr(4);

            thr[0] = thrBase;
            thr[1] = thrBase * sqrt(double(2));
            thr[2] = thrBase * double(2);
            thr[3] = thrBase * sqrt(double(8));

            thrTable[i - 1] = std::vector<FLType>(i * BlockSize * BlockSize);
            auto thr_d = thrTable[i - 1].data();

            for (PCType z = 0; z < i; ++z)
            {
                for (PCType y = 0; y < BlockSize; ++y)
                {
                    for (PCType x = 0; x < BlockSize; ++x, ++thr_d)
                    {
                        int flag = 0;

                        if (x == 0)
                        {
                            ++flag;
                        }
                        if (y == 0)
                        {
                            ++flag;
                        }
                        if (z == 0)
                        {
                            ++flag;
                        }

                        *thr_d = static_cast<FLType>(thr[flag]);
                    }
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|>