<commit_before>//
//  readsToPWP.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "readsToPWP.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog) {
    std::cout << "**********\nChecking if processor is available...**********\n";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    std::string angsdCommand = "/home/evan/bin/angsd0.613/angsd -bam " + bamlist + " -out " + angsdPrefix + " -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads " + nThreads + " -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > " + angsdOutputLog + " 2>&1";

    if (system((angsdCommand).c_str()) != 0) {
        std::cout << "**********\nFailure running the following command: " << angsdCommand << "\n**********\n";
        exit(EXIT_FAILURE);
    } else {
        std::cout << "**********\nExecuted the following command: " << angsdCommand << "\n**********\n";
    }

    return 0;
}

unsigned char readCountToUnsignedChar(int individual, std::string allele, std::vector<std::string> countsVector) {
    /*    std::cout << "countsVector elements: ";
     for (int i=0; i < countsVector.size(); i++) {
     std::cout <<  countsVector.at(i) << " ";
     }
     std::cout << std::endl;
     */

    //    std::cout << "FunctionPassedAllele: " << allele << std::endl;

    unsigned char countChar;
    if (allele == "A") {
        //        std::cout << "Allele is an A" << std::endl;
        int countField = individual*4;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    }
    else if (allele == "C") {
        //	std::cout << "Allele is an C" << std::endl;
        int countField = (individual*4)+1;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else if (allele == "G") {
        //	std::cout << "Allele is a G" << std::endl;
        int countField = (individual*4) + 2;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else if (allele == "T") {
        //	std::cout << "Allele is a T" << std::endl;
        int countField = (individual*4) + 3;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else {
        std::cout << "Allele doesn't look right. The allele fed into readCountToUnsignedChar is: " << allele << ". Exiting now" << std::endl;
        exit(EXIT_FAILURE);
    }
    //    std::cout << std::to_string(countChar) << std::endl;
    return countChar;
}

int convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)
{
    std::string countsFileName = angsdPrefix + ".counts.gz";
    std::string mafsFileName = angsdPrefix + ".mafs.gz";
    std::ifstream countsFile(countsFileName, std::ios_base::in | std::ios_base::binary);
    std::ifstream mafsFile(mafsFileName, std::ios_base::in | std::ios_base::binary);
    std::ofstream outCountsFile(binaryOutputFileName, std::ios_base::out | std::ios_base::binary);

    try {
        boost::iostreams::filtering_istream in;
        boost::iostreams::filtering_istream inMafs;
        in.push(boost::iostreams::gzip_decompressor());
        in.push(countsFile);
        inMafs.push(boost::iostreams::gzip_decompressor());
        inMafs.push(mafsFile);
        int counter = 0;
        //int numIndividuals = 3;
        for(std::string str; std::getline(in, str); )
        {
            /* Make sure to get the maf string before we do anything else to keep it in
             sync with the counts string */
            std::string mafStr;
            std::getline(inMafs, mafStr);

            // Skip the first line of the counts and mafs file, since it is a header
            if (counter == 0) {
                counter++;
                continue;
            }

            // Just for monitoring progress
            if (counter % 1000000 == 0) {
                std::cout << "Processed " << counter << " loci" << std::endl;
            }

            /* The first thing we'll do after getting the lines from the gzipped file is to split
             the tab-separated lines into separate vectors for the counts and mafs. The vector will
             be recreated for every line of the gzipped counts and mafs files output by angsd (each
             line represents a locus) */
            std::vector<std::string> countsFields;
            boost::split(countsFields, str, boost::is_any_of("\t"), boost::token_compress_on);
            std::vector<std::string> mafFields;
            boost::split(mafFields, mafStr, boost::is_any_of("\t"), boost::token_compress_on);

            /* Since we're using a weighted PWP calculation, and since we don't want to overweight
             repetitive regions, we'll throw out any locus that has more than readDepthMax reads
             for any individual at that locus */
            auto countMax = std::minmax_element(countsFields.begin(),countsFields.end());
            if (*result.second > readDepthMax) {
                continue; // Skip to the next locus
            }

            // Now that the lines are parsed, pull the major and minor alleles from angsd's mafs output
            std::string majorAllele = mafFields[2];
            std::string minorAllele = mafFields[3];

            /* Next, we'll count find how many reads there are supporting the major and minor
             alleles for each individual by looking through the corresponding counts file. The
             function that does this, "readCountToUnsignedChar" is implemented above. It returns
             the readcount number as an unsigned char for binary printing. The max value of an
             unsigned char is 255, but we are skipping all loci with individual read depths
             above readDepthMax (which will usually be much less than 255)*/
            for (int individual = 0; individual < numIndividuals; individual++) {
                unsigned char majorAlleleUnsignedChar = readCountToUnsignedChar(individual, majorAllele, countsFields);
                unsigned char minorAlleleUnsignedChar = readCountToUnsignedChar(individual, minorAllele, countsFields);
                outCountsFile << majorAlleleUnsignedChar << minorAlleleUnsignedChar;
            }
            counter++; // Keep track of how many loci have been processed
        }
    }
    catch(const boost::iostreams::gzip_error& e) {
        std::cout << e.what() << '\n';
    }
    outCountsFile.close();

    return 0;
}

<commit_msg>Minor change<commit_after>//
//  readsToPWP.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "readsToPWP.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog) {
    std::cout << "**********\nChecking if processor is available...**********\n";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    std::string angsdCommand = "/home/evan/bin/angsd0.613/angsd -bam " + bamlist + " -out " + angsdPrefix + " -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads " + nThreads + " -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > " + angsdOutputLog + " 2>&1";

    if (system((angsdCommand).c_str()) != 0) {
        std::cout << "**********\nFailure running the following command: " << angsdCommand << "\n**********\n";
        exit(EXIT_FAILURE);
    } else {
        std::cout << "**********\nExecuted the following command: " << angsdCommand << "\n**********\n";
    }

    return 0;
}

unsigned char readCountToUnsignedChar(int individual, std::string allele, std::vector<std::string> countsVector) {
    /*    std::cout << "countsVector elements: ";
     for (int i=0; i < countsVector.size(); i++) {
     std::cout <<  countsVector.at(i) << " ";
     }
     std::cout << std::endl;
     */

    //    std::cout << "FunctionPassedAllele: " << allele << std::endl;

    unsigned char countChar;
    if (allele == "A") {
        //        std::cout << "Allele is an A" << std::endl;
        int countField = individual*4;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    }
    else if (allele == "C") {
        //	std::cout << "Allele is an C" << std::endl;
        int countField = (individual*4)+1;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else if (allele == "G") {
        //	std::cout << "Allele is a G" << std::endl;
        int countField = (individual*4) + 2;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else if (allele == "T") {
        //	std::cout << "Allele is a T" << std::endl;
        int countField = (individual*4) + 3;
        int countInt = atoi(countsVector[countField].c_str());
        countChar = (unsigned char) countInt;
    } else {
        std::cout << "Allele doesn't look right. The allele fed into readCountToUnsignedChar is: " << allele << ". Exiting now" << std::endl;
        exit(EXIT_FAILURE);
    }
    //    std::cout << std::to_string(countChar) << std::endl;
    return countChar;
}

int convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)
{
    std::string countsFileName = angsdPrefix + ".counts.gz";
    std::string mafsFileName = angsdPrefix + ".mafs.gz";
    std::ifstream countsFile(countsFileName, std::ios_base::in | std::ios_base::binary);
    std::ifstream mafsFile(mafsFileName, std::ios_base::in | std::ios_base::binary);
    std::ofstream outCountsFile(binaryOutputFileName, std::ios_base::out | std::ios_base::binary);

    try {
        boost::iostreams::filtering_istream in;
        boost::iostreams::filtering_istream inMafs;
        in.push(boost::iostreams::gzip_decompressor());
        in.push(countsFile);
        inMafs.push(boost::iostreams::gzip_decompressor());
        inMafs.push(mafsFile);
        int counter = 0;
        //int numIndividuals = 3;
        for(std::string str; std::getline(in, str); )
        {
            /* Make sure to get the maf string before we do anything else to keep it in
             sync with the counts string */
            std::string mafStr;
            std::getline(inMafs, mafStr);

            // Skip the first line of the counts and mafs file, since it is a header
            if (counter == 0) {
                counter++;
                continue;
            }

            // Just for monitoring progress
            if (counter % 1000000 == 0) {
                std::cout << "Processed " << counter << " loci" << std::endl;
            }

            /* The first thing we'll do after getting the lines from the gzipped file is to split
             the tab-separated lines into separate vectors for the counts and mafs. The vector will
             be recreated for every line of the gzipped counts and mafs files output by angsd (each
             line represents a locus) */
            std::vector<std::string> countsFields;
            boost::split(countsFields, str, boost::is_any_of("\t"), boost::token_compress_on);
            std::vector<std::string> mafFields;
            boost::split(mafFields, mafStr, boost::is_any_of("\t"), boost::token_compress_on);

            /* Since we're using a weighted PWP calculation, and since we don't want to overweight
             repetitive regions, we'll throw out any locus that has more than readDepthMax reads
             for any individual at that locus */
            auto countMax = std::minmax_element(countsFields.begin(),countsFields.end());
            if (*result.second > readDepthMax) {
                continue; // Skip to the next locus
            }

            // Now that the lines are parsed, pull the major and minor alleles from angsd's mafs output
            std::string majorAllele = mafFields[2];
            std::string minorAllele = mafFields[3];

            /* Next, we'll count find how many reads there are supporting the major and minor
             alleles for each individual by looking through the corresponding counts file. The
             function that does this, "readCountToUnsignedChar" is implemented above. It returns
             the readcount number as an unsigned char for binary printing. The max value of an
             unsigned char is 255, but we are skipping all loci with individual read depths
             above readDepthMax (which will usually be much less than 255)*/
            for (int individual = 0; individual < numIndividuals; individual++) {
                unsigned char majorAlleleUnsignedChar = readCountToUnsignedChar(individual, majorAllele, countsFields);
                unsigned char minorAlleleUnsignedChar = readCountToUnsignedChar(individual, minorAllele, countsFields);
                outCountsFile << majorAlleleUnsignedChar << minorAlleleUnsignedChar;
            }
            counter++; // Keep track of how many loci have been processed
        }
    }
    catch(const boost::iostreams::gzip_error& e) {
        std::cout << e.what() << '\n';
    }
    outCountsFile.close();

    return 0;
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  OpenNI+NITE+OpenCV
//
//  Created by Rishad Bharucha on 4/30/15.
//  Copyright (c) 2015 Rishad Bharucha. All rights reserved.
//

// STL Header
#include <iostream>

// OpenCV Header
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

// o1. OpenNI Header
#include "OpenNI.h"

// n1. NiTE Header
#include "NiTE.h"

#include "kinectbvh.h"

// namespace
using namespace std;
using namespace openni;
using namespace nite;

bool m_bRecording = false;
bool m_bIsCalibrated = false;
KinectBVH *m_pKinectBVH = NULL;

inline bool IsRecording() {
    return m_bRecording;
}

inline bool IsCalibrated() {
    return m_bIsCalibrated;
}

void StartRecording()
{
    if (!m_bRecording) {
        m_pKinectBVH = new KinectBVH();
        m_bRecording = true;
    }
}

void StopRecording()
{
    if (m_bRecording) {
        m_bRecording = false;
        time_t nowtime = time(NULL);
        struct tm *local = localtime(&nowtime);
        char buf[256];
        sprintf(buf, "%d-%d-%d-%d-%d-%d.bvh", local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
        m_pKinectBVH->SaveToBVHFile(buf);
        delete m_pKinectBVH;
        m_pKinectBVH = NULL;
        m_bIsCalibrated = false;
    }
}

void CalibrateSkeleton()
{
    m_pKinectBVH->CalibrateSkeleton();
    m_bIsCalibrated = true;
}

void ProcessBonesOrientation(const nite::Skeleton &skel)
{
    vector<Joint> joints(JOINT_SIZE);
    // Fill joints
    for (int i = 0; i < JOINT_SIZE; i++)
    {
        nite::Point3f pos = skel.getJoint((nite::JointType)i).getPosition();
        joints[i].pos.x = pos.x;
        joints[i].pos.y = pos.y;
        // convert to right hand coordinate
        joints[i].pos.z = -pos.z;
        joints[i].tracked = skel.getJoint((nite::JointType)i).getPositionConfidence() > 0.5f;
    }

    // Add the positions of all joints.
    m_pKinectBVH->AddAllJointsPosition(&joints[0]);

    // Increase the frame number.
    m_pKinectBVH->IncrementNbFrames();
}

int main( int argc, char **argv )
{
    // o2. Initial OpenNI
    OpenNI::initialize();

    // o3. Open Device
    Device  mDevice;
    mDevice.open( ANY_DEVICE );

    // o4. create depth stream
    VideoStream mDepthStream;
    mDepthStream.create( mDevice, SENSOR_DEPTH );
    // o4a. set video mode
    VideoMode mDMode;
    mDMode.setResolution( 640, 480 );
    mDMode.setFps( 30 );
    mDMode.setPixelFormat( PIXEL_FORMAT_DEPTH_1_MM );
    mDepthStream.setVideoMode( mDMode);

    // o5. Create color stream
    VideoStream mColorStream;
    mColorStream.create( mDevice, SENSOR_COLOR );
    // o5a. set video mode
    VideoMode mCMode;
    mCMode.setResolution( 640, 480 );
    mCMode.setFps( 30 );
    mCMode.setPixelFormat( PIXEL_FORMAT_RGB888 );
    mColorStream.setVideoMode( mCMode);

    // o6. image registration
    mDevice.setImageRegistrationMode( IMAGE_REGISTRATION_DEPTH_TO_COLOR );

    // n2. Initial NiTE
    NiTE::initialize();

    // n3. create user tracker
    UserTracker mUserTracker;
    mUserTracker.create( &mDevice );
    mUserTracker.setSkeletonSmoothingFactor( 0.0f );

    // create OpenCV Window
    cv::namedWindow( "User Image",  CV_WINDOW_AUTOSIZE );

    // p1. start
    mColorStream.start();
    mDepthStream.start();

    while( true )
    {
        // main loop
        // p2 - p5 ...

        // p2. prepare background
        cv::Mat cImageBGR;
        // p2a. get color frame
        VideoFrameRef mColorFrame;
        mColorStream.readFrame( &mColorFrame );
        // p2b. convert data to OpenCV format
        const cv::Mat mImageRGB( mColorFrame.getHeight(), mColorFrame.getWidth(),
                                CV_8UC3, (void*)mColorFrame.getData() );
        // p2c. convert form RGB to BGR
        cv::cvtColor( mImageRGB, cImageBGR, CV_RGB2BGR );

        // p3. get user frame
        UserTrackerFrameRef  mUserFrame;
        mUserTracker.readFrame( &mUserFrame );

        // p4. get users data
        const nite::Array<UserData>& aUsers = mUserFrame.getUsers();
        for( int i = 0; i < aUsers.getSize(); ++ i )
        {
            const UserData& rUser = aUsers[i];

            // p4a. check user status
            if( rUser.isNew() )
            {
                // start tracking for new user
                mUserTracker.startSkeletonTracking( rUser.getId() );
            }

            if( rUser.isVisible() )
            {
                // p4b. get user skeleton
                const Skeleton& rSkeleton = rUser.getSkeleton();
                if( rSkeleton.getState() == SKELETON_TRACKED )
                {
                    // start recording
                    if (!IsRecording())
                    {
                        printf("start recording\n");
                        StartRecording();
                    }

                    // calibrate T pose
                    if (!IsCalibrated())
                    {
                        printf("calibrate skeleton\n");
                        CalibrateSkeleton();
                    }

                    // record movement information
                    if (IsRecording() && IsCalibrated())
                    {
                        ProcessBonesOrientation(rSkeleton);
                    }

                    // p4c. build joints array
                    SkeletonJoint aJoints[15];
                    aJoints[ 0] = rSkeleton.getJoint( nite::JOINT_HEAD );
                    aJoints[ 1] = rSkeleton.getJoint( nite::JOINT_NECK );
                    aJoints[ 2] = rSkeleton.getJoint( nite::JOINT_LEFT_SHOULDER );
                    aJoints[ 3] = rSkeleton.getJoint( nite::JOINT_RIGHT_SHOULDER );
                    aJoints[ 4] = rSkeleton.getJoint( nite::JOINT_LEFT_ELBOW );
                    aJoints[ 5] = rSkeleton.getJoint( nite::JOINT_RIGHT_ELBOW );
                    aJoints[ 6] = rSkeleton.getJoint( nite::JOINT_LEFT_HAND );
                    aJoints[ 7] = rSkeleton.getJoint( nite::JOINT_RIGHT_HAND );
                    aJoints[ 8] = rSkeleton.getJoint( nite::JOINT_TORSO );
                    aJoints[ 9] = rSkeleton.getJoint( nite::JOINT_LEFT_HIP );
                    aJoints[10] = rSkeleton.getJoint( nite::JOINT_RIGHT_HIP );
                    aJoints[11] = rSkeleton.getJoint( nite::JOINT_LEFT_KNEE );
                    aJoints[12] = rSkeleton.getJoint( nite::JOINT_RIGHT_KNEE );
                    aJoints[13] = rSkeleton.getJoint( nite::JOINT_LEFT_FOOT );
                    aJoints[14] = rSkeleton.getJoint( nite::JOINT_RIGHT_FOOT );

                    // p4d. convert joint position to image
                    cv::Point2f aPoint[15];
                    for( int  s = 0; s < 15; ++ s )
                    {
                        const Point3f& rPos = aJoints[s].getPosition();
                        mUserTracker.convertJointCoordinatesToDepth(
                                                                    rPos.x, rPos.y, rPos.z,
                                                                    &(aPoint[s].x), &(aPoint[s].y) );
                    }

                    // p4e. draw line
                    cv::line( cImageBGR, aPoint[ 0], aPoint[ 1], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 2], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 3], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 2], aPoint[ 4], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 3], aPoint[ 5], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 4], aPoint[ 6], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 5], aPoint[ 7], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 8], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 8], aPoint[ 9], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 8], aPoint[10], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 9], aPoint[11], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[10], aPoint[12], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[11], aPoint[13], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[12], aPoint[14], cv::Scalar( 255, 0, 0 ), 3 );

                    // p4f. draw joint
                    for( int  s = 0; s < 15; ++ s )
                    {
                        if( aJoints[s].getPositionConfidence() > 0.5 )
                            cv::circle( cImageBGR, aPoint[s], 3, cv::Scalar( 0, 0, 255 ), 2 );
                        else
                            cv::circle( cImageBGR, aPoint[s], 3, cv::Scalar( 0, 255, 0 ), 2 );
                    }
                }
            } else {
                if (rUser.getSkeleton().getState() == SKELETON_TRACKED && IsRecording())
                {
                    printf("stop recording\n");
                    StopRecording();
                }
            }
        }

        // p5. show image
        cv::imshow( "User Image", cImageBGR );
        // p6. check keyboard
        if( cv::waitKey( 1 ) == 'q' )
            break;
    }

    if (IsRecording())
    {
        printf("stop recording\n");
        StopRecording();
    }

    if (m_pKinectBVH)
    {
        delete m_pKinectBVH;
        m_pKinectBVH = NULL;
    }

    // p7. stop
    mUserTracker.destroy();
    mColorStream.destroy();
    mDepthStream.destroy();
    mDevice.close();
    NiTE::shutdown();
    OpenNI::shutdown();

    return 0;
}
<commit_msg>Read tilt angle from file.<commit_after>//
//  main.cpp
//  OpenNI+NITE+OpenCV
//
//  Created by Rishad Bharucha on 4/30/15.
//  Copyright (c) 2015 Rishad Bharucha. All rights reserved.
//

// STL Header
#include <iostream>

// OpenCV Header
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

// o1. OpenNI Header
#include "OpenNI.h"

// n1. NiTE Header
#include "NiTE.h"

#include "kinectbvh.h"

// namespace
using namespace std;
using namespace openni;
using namespace nite;

bool m_bRecording = false;
bool m_bIsCalibrated = false;
KinectBVH *m_pKinectBVH = NULL;

inline bool IsRecording() {
    return m_bRecording;
}

inline bool IsCalibrated() {
    return m_bIsCalibrated;
}

void StartRecording()
{
    if (!m_bRecording) {
        m_pKinectBVH = new KinectBVH();
        m_bRecording = true;
    }
}

void StopRecording()
{
    if (m_bRecording) {
        m_bRecording = false;
        time_t nowtime = time(NULL);
        struct tm *local = localtime(&nowtime);
        char buf[256];
        sprintf(buf, "../data/%d-%d-%d-%d-%d-%d.bvh", local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
        m_pKinectBVH->SaveToBVHFile(buf);
        delete m_pKinectBVH;
        m_pKinectBVH = NULL;
        m_bIsCalibrated = false;
    }
}

void CalibrateSkeleton()
{
    m_pKinectBVH->CalibrateSkeleton();
    m_bIsCalibrated = true;
}

void ProcessBonesOrientation(const nite::Skeleton &skel)
{
    vector<Joint> joints(JOINT_SIZE);
    // Fill joints
    for (int i = 0; i < JOINT_SIZE; i++)
    {
        nite::Point3f pos = skel.getJoint((nite::JointType)i).getPosition();
        joints[i].pos.x = pos.x;
        joints[i].pos.y = pos.y;
        // convert to right hand coordinate
        joints[i].pos.z = -pos.z;
        joints[i].tracked = skel.getJoint((nite::JointType)i).getPositionConfidence() > 0.5f;
    }

    // Add the positions of all joints.
    m_pKinectBVH->AddAllJointsPosition(&joints[0]);

    // Increase the frame number.
    m_pKinectBVH->IncrementNbFrames();
}

int main( int argc, char **argv )
{
    // read tilt angle from file
    float tile_angle = 0.0f;
    ifstream rf("tilt-angle.txt");
    if (rf.is_open()) {
        rf >> tile_angle;
    }
    rf.close();

    // o2. Initial OpenNI
    OpenNI::initialize();

    // o3. Open Device
    Device  mDevice;
    mDevice.open( ANY_DEVICE );

    // o4. create depth stream
    VideoStream mDepthStream;
    mDepthStream.create( mDevice, SENSOR_DEPTH );
    // o4a. set video mode
    VideoMode mDMode;
    mDMode.setResolution( 640, 480 );
    mDMode.setFps( 30 );
    mDMode.setPixelFormat( PIXEL_FORMAT_DEPTH_1_MM );
    mDepthStream.setVideoMode( mDMode);

    // o5. Create color stream
    VideoStream mColorStream;
    mColorStream.create( mDevice, SENSOR_COLOR );
    // o5a. set video mode
    VideoMode mCMode;
    mCMode.setResolution( 640, 480 );
    mCMode.setFps( 30 );
    mCMode.setPixelFormat( PIXEL_FORMAT_RGB888 );
    mColorStream.setVideoMode( mCMode);

    // o6. image registration
    mDevice.setImageRegistrationMode( IMAGE_REGISTRATION_DEPTH_TO_COLOR );

    // n2. Initial NiTE
    NiTE::initialize();

    // n3. create user tracker
    UserTracker mUserTracker;
    mUserTracker.create( &mDevice );
    mUserTracker.setSkeletonSmoothingFactor( 0.0f );

    // create OpenCV Window
    cv::namedWindow( "User Image",  CV_WINDOW_AUTOSIZE );

    // p1. start
    mColorStream.start();
    mDepthStream.start();

    while( true )
    {
        // main loop
        // p2 - p5 ...

        // p2. prepare background
        cv::Mat cImageBGR;
        // p2a. get color frame
        VideoFrameRef mColorFrame;
        mColorStream.readFrame( &mColorFrame );
        // p2b. convert data to OpenCV format
        const cv::Mat mImageRGB( mColorFrame.getHeight(), mColorFrame.getWidth(),
                                CV_8UC3, (void*)mColorFrame.getData() );
        // p2c. convert form RGB to BGR
        cv::cvtColor( mImageRGB, cImageBGR, CV_RGB2BGR );

        // p3. get user frame
        UserTrackerFrameRef  mUserFrame;
        mUserTracker.readFrame( &mUserFrame );

        // p4. get users data
        const nite::Array<UserData>& aUsers = mUserFrame.getUsers();
        for( int i = 0; i < aUsers.getSize(); ++ i )
        {
            const UserData& rUser = aUsers[i];

            // p4a. check user status
            if( rUser.isNew() )
            {
                // start tracking for new user
                mUserTracker.startSkeletonTracking( rUser.getId() );
            }

            if( rUser.isVisible() )
            {
                // p4b. get user skeleton
                const Skeleton& rSkeleton = rUser.getSkeleton();
                if( rSkeleton.getState() == SKELETON_TRACKED )
                {
                    // start recording
                    if (!IsRecording())
                    {
                        printf("start recording\n");
                        StartRecording();
                        // set tile angle
                        m_pKinectBVH->SetTiltAngle(tile_angle);
                    }

                    // calibrate T pose
                    if (!IsCalibrated())
                    {
                        printf("calibrate skeleton\n");
                        CalibrateSkeleton();
                    }

                    // record movement information
                    if (IsRecording() && IsCalibrated())
                    {
                        ProcessBonesOrientation(rSkeleton);
                    }

                    // p4c. build joints array
                    SkeletonJoint aJoints[15];
                    aJoints[ 0] = rSkeleton.getJoint( nite::JOINT_HEAD );
                    aJoints[ 1] = rSkeleton.getJoint( nite::JOINT_NECK );
                    aJoints[ 2] = rSkeleton.getJoint( nite::JOINT_LEFT_SHOULDER );
                    aJoints[ 3] = rSkeleton.getJoint( nite::JOINT_RIGHT_SHOULDER );
                    aJoints[ 4] = rSkeleton.getJoint( nite::JOINT_LEFT_ELBOW );
                    aJoints[ 5] = rSkeleton.getJoint( nite::JOINT_RIGHT_ELBOW );
                    aJoints[ 6] = rSkeleton.getJoint( nite::JOINT_LEFT_HAND );
                    aJoints[ 7] = rSkeleton.getJoint( nite::JOINT_RIGHT_HAND );
                    aJoints[ 8] = rSkeleton.getJoint( nite::JOINT_TORSO );
                    aJoints[ 9] = rSkeleton.getJoint( nite::JOINT_LEFT_HIP );
                    aJoints[10] = rSkeleton.getJoint( nite::JOINT_RIGHT_HIP );
                    aJoints[11] = rSkeleton.getJoint( nite::JOINT_LEFT_KNEE );
                    aJoints[12] = rSkeleton.getJoint( nite::JOINT_RIGHT_KNEE );
                    aJoints[13] = rSkeleton.getJoint( nite::JOINT_LEFT_FOOT );
                    aJoints[14] = rSkeleton.getJoint( nite::JOINT_RIGHT_FOOT );

                    // p4d. convert joint position to image
                    cv::Point2f aPoint[15];
                    for( int  s = 0; s < 15; ++ s )
                    {
                        const Point3f& rPos = aJoints[s].getPosition();
                        mUserTracker.convertJointCoordinatesToDepth(
                                                                    rPos.x, rPos.y, rPos.z,
                                                                    &(aPoint[s].x), &(aPoint[s].y) );
                    }

                    // p4e. draw line
                    cv::line( cImageBGR, aPoint[ 0], aPoint[ 1], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 2], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 3], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 2], aPoint[ 4], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 3], aPoint[ 5], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 4], aPoint[ 6], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 5], aPoint[ 7], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 1], aPoint[ 8], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 8], aPoint[ 9], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 8], aPoint[10], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[ 9], aPoint[11], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[10], aPoint[12], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[11], aPoint[13], cv::Scalar( 255, 0, 0 ), 3 );
                    cv::line( cImageBGR, aPoint[12], aPoint[14], cv::Scalar( 255, 0, 0 ), 3 );

                    // p4f. draw joint
                    for( int  s = 0; s < 15; ++ s )
                    {
                        if( aJoints[s].getPositionConfidence() > 0.5 )
                            cv::circle( cImageBGR, aPoint[s], 3, cv::Scalar( 0, 0, 255 ), 2 );
                        else
                            cv::circle( cImageBGR, aPoint[s], 3, cv::Scalar( 0, 255, 0 ), 2 );
                    }
                }
            } else {
                if (rUser.getSkeleton().getState() == SKELETON_TRACKED && IsRecording())
                {
                    printf("stop recording\n");
                    StopRecording();
                }
            }
        }

        // p5. show image
        cv::imshow( "User Image", cImageBGR );
        // p6. check keyboard
        if( cv::waitKey( 1 ) == 27 )
            break;
    }

    if (IsRecording())
    {
        printf("stop recording\n");
        StopRecording();
    }

    if (m_pKinectBVH)
    {
        delete m_pKinectBVH;
        m_pKinectBVH = NULL;
    }

    // p7. stop
    mUserTracker.destroy();
    mColorStream.destroy();
    mDepthStream.destroy();
    mDevice.close();
    NiTE::shutdown();
    OpenNI::shutdown();

    return 0;
}
<|endoftext|>


<commit_before>
/* EGLBenchmark
 *
 * Author: Jarkko Vatjus-Anttila <jvatjusanttila@gmail.com>
 *
 * For conditions of distribution and use, see copyright notice in license.txt
 */

#include <iostream>
#include <stdlib.h>
#include <stdarg.h>

#include "EGLX11Benchmark.h"

#include "b01_ContextInit.h"
#include "b02_SimpleGLShading.h"
#include "b03_SimpleTriangle.h"
#include "b04_ETCTextureTest.h"
#include "b05_RGBTextureTest.h"

// the default settings
enum {
    TEST_CONTEXTINIT = 1,
    TEST_SIMPLESHADER,
    TEST_SIMPLETRIANGLE,
    TEST_ETCTEXTURE,
    TEST_RGBTEXTURE
};
static unsigned int width = 840;
static unsigned int height = 480;
static unsigned int fullscreen = false;
static int verbosity = 1;
static float duration = 5.0f;
static float fpslimit = 0.0f;
static unsigned int testcase = TEST_CONTEXTINIT;

bool parseArgs(int argc, char *argv[])
{
    typedef struct _o {
        const char *name;
        unsigned int symbol;
    } OPTION;
    enum {
        OPT_VERBOSE = 1,
        OPT_WIDTH,
        OPT_HEIGHT,
        OPT_FULLSCREEN,
        OPT_DURATION,
        OPT_TESTCASE,
        OPT_FPSLIMIT,
        OPT_LIST,
        OPT_USAGE,
        OPT_H,
        OPT_HELP,
    };
    OPTION options[] = {
        { "-verbose",    OPT_VERBOSE },
        { "-width",      OPT_WIDTH },
        { "-height",     OPT_HEIGHT },
        { "-fullscreen", OPT_FULLSCREEN },
        { "-duration",   OPT_DURATION },
        { "-testcase",   OPT_TESTCASE },
        { "-list",       OPT_LIST },
        { "-fpslimit",   OPT_FPSLIMIT },
        { "-usage",      OPT_USAGE },
        { "-h",          OPT_H },
        { "-help",       OPT_HELP },
    };

    for (int i=1; i<argc; i++)
    {
        for (unsigned int j=0; j<sizeof(options)/sizeof(OPTION); j++)
        {
            if (strncmp(argv[i], options[j].name, strlen(options[j].name)) == 0)
            {
                switch(options[j].symbol)
                {
                case OPT_VERBOSE:
                    if (i+1 == argc) break; // No params anymore
                    verbosity = atoi(argv[i+1]);
                    if (verbosity < 1) verbosity = 1;
                    if (verbosity > 5) verbosity = 5;
                    break;
                case OPT_WIDTH:
                    if (i+1 == argc) break; // No params anymore
                    width = atoi(argv[i+1]);
                    if (width < 1) width = 1;
                    break;
                case OPT_HEIGHT:
                    if (i+1 == argc) break; // No params anymore
                    height = atoi(argv[i+1]);
                    if (height < 1) height = 1;
                    break;
                case OPT_FULLSCREEN:
                    fullscreen = true;
                    break;
                case OPT_DURATION:
                    if (i+1 == argc) break; // No params anymore
                    duration = atof(argv[i+1]);
                    if (duration < 1.0f) duration = 1.0f;
                    break;
                case OPT_USAGE:
                case OPT_H:
                case OPT_HELP:
                    std::cout << "Usage:\n" << argv[0] << " -width <W> -height <H> -fullscreen";
                    std::cout << "  -verbose <LEVEL 1-5> -duration <seconds> -usage|-h|-help -list -testcase <testcasename>\n";
                    return false;
                case OPT_LIST:
                    std::cout << "List of available test cases:\n";
                    std::cout << "   context:  EGL context initialization test\n";
                    std::cout << "   shader:   Simple Shader test\n";
                    std::cout << "   triangle: Simple Triangle test\n";
                    std::cout << "   etctest:  ETC texture mapping test\n";
                    std::cout << "   rgbtest:  RGB texture mapping test\n";
                    return false;
                case OPT_TESTCASE:
                    if (i+1 == argc) break; // No params anymore
                    if (0 == strcmp(argv[i+1], "context")) testcase = TEST_CONTEXTINIT;
                    else if (0 == strcmp(argv[i+1], "shader")) testcase = TEST_SIMPLESHADER;
                    else if (0 == strcmp(argv[i+1], "triangle")) testcase = TEST_SIMPLETRIANGLE;
                    else if (0 == strcmp(argv[i+1], "etctest")) testcase = TEST_ETCTEXTURE;
                    else if (0 == strcmp(argv[i+1], "rgbtest")) testcase = TEST_RGBTEXTURE;
                    else
                    {
                        std::cout << "Unrecognized test case: " << argv[i+1] << "\n";
                        return false;
                    }
                    break;
                case OPT_FPSLIMIT:
                    if (i+1 == argc) break; // No params anymore
                    fpslimit = atof(argv[i+1]);
                    if (fpslimit < 0.0f) fpslimit = 0.0f;
                    break;
                }
            }
        }
    }
    return true;
}

int main(int argc, char *argv[])
{
    EGLX11Benchmark *bm;

    if (false == parseArgs(argc, argv))
    {
        return 0;
    }

    switch(testcase)
    {
    case TEST_CONTEXTINIT:
        bm = dynamic_cast<EGLX11Benchmark*>(new b01_ContextInit());
        break;
    case TEST_SIMPLESHADER:
        bm = dynamic_cast<EGLX11Benchmark*>(new b02_SimpleGLShading());
        break;
    case TEST_SIMPLETRIANGLE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b03_SimpleTriangle());
        break;
    case TEST_ETCTEXTURE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b04_ETCTextureTest());
        break;
    case TEST_RGBTEXTURE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b05_RGBTextureTest());
        break;
    }

    bm->setVerbosityLevel(verbosity);

    if (false == bm->initBenchmark(width, height, fullscreen))
    {
        std::cout << "initBenchmark() of '" << bm->getName() <<"' failed\n";
    }
    else
    {
        float totaltime;
        float deltatime;
        unsigned int renderedFrames;

        std::cout << "Benchmark name: " << bm->getName() << "\n";
        std::cout << "Description:    " << bm->getDescription() << "\n";
        std::cout << "Running benchmark (duration="<<duration<<" seconds)...\n";

        // Timer and variables
        bm->resetTimer();
        totaltime = 0.0f;
        deltatime = 0.0f;
        renderedFrames = 0.0f;

        while ( totaltime < duration )
        {
            bm->getTimeSinceLastFrame();
            if (false == bm->renderSingleFrame(deltatime))
            {
                std::cout << "Error during framerender. Abort!\n";
                break;
            }
            renderedFrames++;

            deltatime = bm->getTimeSinceLastFrame();

            // FPS limit
            if (fpslimit > 0.0f)
            {
                float frametime;
                frametime = 1.0f/fpslimit;
                if (deltatime < frametime)
                {
                    useconds_t sl = (useconds_t)((frametime-deltatime)*1000000);
                    usleep(sl);
                    deltatime = frametime;
                }
            }
            totaltime += deltatime;

            if (bm->userInterrupt() == true)
            {
                std::cout << "User interrupt!\n";
                break;
            }
        }
        std::cout << "Total rendering time:             " << totaltime << "\n";
        std::cout << "Total rendered frames:            " << renderedFrames << "\n";
        std::cout << "Frames per second:                " << renderedFrames/totaltime << "\n";
        std::cout << "Total GL errors during the test:  " << bm->getGLErrors() << "\n";
        std::cout << "Total EGL errors during the test: " << bm->getEGLErrors() << "\n";
        bm->destroyBenchmark();
    }

    std::cout << "Done!\n";
    return 0;
}
<commit_msg>Removed duration param for the time being and added framelimit instead. Also added calculation of frametime average and variance, for easier inspection of results<commit_after>
/* EGLBenchmark
 *
 * Author: Jarkko Vatjus-Anttila <jvatjusanttila@gmail.com>
 *
 * For conditions of distribution and use, see copyright notice in license.txt
 */

#include <iostream>
#include <stdlib.h>
#include <stdarg.h>

#include "EGLX11Benchmark.h"

#include "b01_ContextInit.h"
#include "b02_SimpleGLShading.h"
#include "b03_SimpleTriangle.h"
#include "b04_ETCTextureTest.h"
#include "b05_RGBTextureTest.h"

// the default settings
enum {
    TEST_CONTEXTINIT = 1,
    TEST_SIMPLESHADER,
    TEST_SIMPLETRIANGLE,
    TEST_ETCTEXTURE,
    TEST_RGBTEXTURE
};
static unsigned int width = 840;
static unsigned int height = 480;
static unsigned int fullscreen = false;
static unsigned int framelimit = 100;
static int verbosity = 1;
//static float duration = 5.0f;
static float fpslimit = 0.0f;
static unsigned int testcase = TEST_CONTEXTINIT;

bool parseArgs(int argc, char *argv[])
{
    typedef struct _o {
        const char *name;
        unsigned int symbol;
    } OPTION;
    enum {
        OPT_VERBOSE = 1,
        OPT_WIDTH,
        OPT_HEIGHT,
        OPT_FULLSCREEN,
//        OPT_DURATION,
        OPT_FRAMELIMIT,
        OPT_TESTCASE,
        OPT_FPSLIMIT,
        OPT_LIST,
        OPT_USAGE,
        OPT_H,
        OPT_HELP,
    };
    OPTION options[] = {
        { "-verbose",    OPT_VERBOSE },
        { "-width",      OPT_WIDTH },
        { "-height",     OPT_HEIGHT },
        { "-fullscreen", OPT_FULLSCREEN },
//        { "-duration",   OPT_DURATION },
        { "-framelimit", OPT_FRAMELIMIT },
        { "-testcase",   OPT_TESTCASE },
        { "-list",       OPT_LIST },
        { "-fpslimit",   OPT_FPSLIMIT },
        { "-usage",      OPT_USAGE },
        { "-h",          OPT_H },
        { "-help",       OPT_HELP },
    };

    for (int i=1; i<argc; i++)
    {
        for (unsigned int j=0; j<sizeof(options)/sizeof(OPTION); j++)
        {
            if (strncmp(argv[i], options[j].name, strlen(options[j].name)) == 0)
            {
                switch(options[j].symbol)
                {
                case OPT_VERBOSE:
                    if (i+1 == argc) break; // No params anymore
                    verbosity = atoi(argv[i+1]);
                    if (verbosity < 1) verbosity = 1;
                    if (verbosity > 5) verbosity = 5;
                    break;
                case OPT_WIDTH:
                    if (i+1 == argc) break; // No params anymore
                    width = atoi(argv[i+1]);
                    if (width < 1) width = 1;
                    break;
                case OPT_HEIGHT:
                    if (i+1 == argc) break; // No params anymore
                    height = atoi(argv[i+1]);
                    if (height < 1) height = 1;
                    break;
                case OPT_FULLSCREEN:
                    fullscreen = true;
                    break;
//                case OPT_DURATION:
//                    if (i+1 == argc) break; // No params anymore
//                    duration = atof(argv[i+1]);
//                    if (duration < 1.0f) duration = 1.0f;
//                    break;
                case OPT_FRAMELIMIT:
                    if (i+1 == argc) break; // No params anymore
                    framelimit = atoi(argv[i+1]);
                    if (framelimit < 1) framelimit = 1;
                    break;
                case OPT_USAGE:
                case OPT_H:
                case OPT_HELP:
                    std::cout << "Usage:\n" << argv[0] << " -width <W> -height <H> -fullscreen";
                    std::cout << "  -verbose <LEVEL 1-5> -framelimit <frames> -usage|-h|-help -list -testcase <testcasename>\n";
                    return false;
                case OPT_LIST:
                    std::cout << "List of available test cases:\n";
                    std::cout << "   context:  EGL context initialization test\n";
                    std::cout << "   shader:   Simple Shader test\n";
                    std::cout << "   triangle: Simple Triangle test\n";
                    std::cout << "   etctest:  ETC texture mapping test\n";
                    std::cout << "   rgbtest:  RGB texture mapping test\n";
                    return false;
                case OPT_TESTCASE:
                    if (i+1 == argc) break; // No params anymore
                    if (0 == strcmp(argv[i+1], "context")) testcase = TEST_CONTEXTINIT;
                    else if (0 == strcmp(argv[i+1], "shader")) testcase = TEST_SIMPLESHADER;
                    else if (0 == strcmp(argv[i+1], "triangle")) testcase = TEST_SIMPLETRIANGLE;
                    else if (0 == strcmp(argv[i+1], "etctest")) testcase = TEST_ETCTEXTURE;
                    else if (0 == strcmp(argv[i+1], "rgbtest")) testcase = TEST_RGBTEXTURE;
                    else
                    {
                        std::cout << "Unrecognized test case: " << argv[i+1] << "\n";
                        return false;
                    }
                    break;
                case OPT_FPSLIMIT:
                    if (i+1 == argc) break; // No params anymore
                    fpslimit = atof(argv[i+1]);
                    if (fpslimit < 0.0f) fpslimit = 0.0f;
                    break;
                }
            }
        }
    }
    return true;
}

void calculateFrameVariance(float *frametimes, unsigned int samples, float *average, float *variance)
{
    float sum, t;

    sum = 0.0f;
    for (unsigned int i=0; i<samples; i++)
    {
        sum += frametimes[i];
    }
    *average = sum / samples;

    sum = 0;
    for (unsigned int i=0; i<samples; i++)
    {
        sum += ((frametimes[i] - *average)*(frametimes[i] - *average));
    }
    *variance = sum / samples;
}

int main(int argc, char *argv[])
{
    EGLX11Benchmark *bm;
    float *frametimes;

    if (false == parseArgs(argc, argv))
    {
        return 0;
    }

    frametimes = new float[framelimit];

    switch(testcase)
    {
    case TEST_CONTEXTINIT:
        bm = dynamic_cast<EGLX11Benchmark*>(new b01_ContextInit());
        break;
    case TEST_SIMPLESHADER:
        bm = dynamic_cast<EGLX11Benchmark*>(new b02_SimpleGLShading());
        break;
    case TEST_SIMPLETRIANGLE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b03_SimpleTriangle());
        break;
    case TEST_ETCTEXTURE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b04_ETCTextureTest());
        break;
    case TEST_RGBTEXTURE:
        bm = dynamic_cast<EGLX11Benchmark*>(new b05_RGBTextureTest());
        break;
    }

    bm->setVerbosityLevel(verbosity);

    if (false == bm->initBenchmark(width, height, fullscreen))
    {
        std::cout << "initBenchmark() of '" << bm->getName() <<"' failed\n";
    }
    else
    {
        float totaltime;
        float deltatime;
        unsigned int renderedFrames;
        float average, variance;

        std::cout << "Benchmark name: " << bm->getName() << "\n";
        std::cout << "Description:    " << bm->getDescription() << "\n";
//        std::cout << "Running benchmark (duration="<<duration<<" seconds)...\n";
        std::cout << "Running benchmark (framelimit="<<framelimit<<" frames)...\n";

        // Timer and variables
        bm->resetTimer();
        totaltime = 0.0f;
        deltatime = 0.0f;
        renderedFrames = 0;

        while ( renderedFrames < framelimit )
        {
            bm->getTimeSinceLastFrame();
            if (false == bm->renderSingleFrame(deltatime))
            {
                std::cout << "Error during framerender. Abort!\n";
                break;
            }

            deltatime = bm->getTimeSinceLastFrame();
            frametimes[renderedFrames] = deltatime;
            renderedFrames++;

            // FPS limit
            if (fpslimit > 0.0f)
            {
                float frametime;
                frametime = 1.0f/fpslimit;
                if (deltatime < frametime)
                {
                    useconds_t sl = (useconds_t)((frametime-deltatime)*1000000);
                    usleep(sl);
                    deltatime = frametime;
                }
            }
            totaltime += deltatime;

            if (bm->userInterrupt() == true)
            {
                std::cout << "User interrupt!\n";
                break;
            }
        }
        calculateFrameVariance(frametimes, framelimit, &average, &variance);
        std::cout << "Total rendering time:             " << totaltime << "\n";
        std::cout << "Total rendered frames:            " << renderedFrames << "\n";
        std::cout << "Measurement frametime (average):  " << average << " seconds\n";
        std::cout << "Measurement frametime (variance)  " << variance << " seconds\n";
        std::cout << "Frames per second:                " << renderedFrames/totaltime << "\n";
        std::cout << "Total GL errors during the test:  " << bm->getGLErrors() << "\n";
        std::cout << "Total EGL errors during the test: " << bm->getEGLErrors() << "\n";
        bm->destroyBenchmark();
    }

    std::cout << "Done!\n";
    return 0;
}
<|endoftext|>


<commit_before>#include "erlang_v8_drv.h"

static unsigned _id = 0;

static void VmContextDestroy(Persistent<Value> value, void *ptr) {
  TRACE("VmContextDestroy\n");
  Handle<External> external = Handle<External>::Cast(value);
  ErlExternal *erlExternal = (ErlExternal *)external->Value();
  value.Dispose();
  free(erlExternal);
}

VmContext::VmContext(Vm *_vm, ErlNifEnv *env) {
  TRACE("VmContext::VmContext\n");
  vm = _vm;

  sprintf(id, "VmContext:%d", _id++);

  erlVmContext = (ErlVmContext *)enif_alloc_resource(VmContextResource, sizeof(ErlVmContext));
  erlVmContext->vmContext = this;
  term = MakeTerm(env);
  enif_release_resource(erlVmContext);
  enif_keep_resource(vm->erlVm);

  Locker locker(vm->isolate);
  Isolate::Scope iscope(vm->isolate);
  HandleScope handle_scope;
  context = Persistent<Context>::New(Context::New(NULL, vm->global));
}

VmContext::~VmContext() {
  TRACE("VmContext::~VmContext\n");
  Locker locker(vm->isolate);
  Isolate::Scope iscope(vm->isolate);
  context.Dispose();
  context.Clear();

  enif_release_resource(vm->erlVm);
}

Handle<Value> VmContext::MakeHandle() {
  ErlExternal *erlExternal = (ErlExternal *)malloc(sizeof(ErlExternal));
  erlExternal->type = VM_CONTEXT;
  erlExternal->ptr = this;
  Persistent<External> external = Persistent<External>::New(
      External::New(erlExternal));
  external.MakeWeak(NULL, VmContextDestroy);

  return external;
}

ERL_NIF_TERM VmContext::MakeTerm(ErlNifEnv *env) {
  TRACE("Vm::MakeTerm\n");
  return enif_make_resource_binary(env, erlVmContext, id, strlen(id));
}
<commit_msg>Don't try to lock multiple times with new contexts.<commit_after>#include "erlang_v8_drv.h"

static unsigned _id = 0;

static void VmContextDestroy(Persistent<Value> value, void *ptr) {
  TRACE("VmContextDestroy\n");
  Handle<External> external = Handle<External>::Cast(value);
  ErlExternal *erlExternal = (ErlExternal *)external->Value();
  value.Dispose();
  free(erlExternal);
}

VmContext::VmContext(Vm *_vm, ErlNifEnv *env) {
  TRACE("VmContext::VmContext\n");
  vm = _vm;

  sprintf(id, "VmContext:%d", _id++);

  erlVmContext = (ErlVmContext *)enif_alloc_resource(VmContextResource, sizeof(ErlVmContext));
  erlVmContext->vmContext = this;
  term = MakeTerm(env);
  enif_release_resource(erlVmContext);
  enif_keep_resource(vm->erlVm);

  context = Persistent<Context>::New(Context::New(NULL, vm->global));
}

VmContext::~VmContext() {
  TRACE("VmContext::~VmContext\n");
  Locker locker(vm->isolate);
  Isolate::Scope iscope(vm->isolate);
  context.Dispose();
  context.Clear();

  enif_release_resource(vm->erlVm);
}

Handle<Value> VmContext::MakeHandle() {
  ErlExternal *erlExternal = (ErlExternal *)malloc(sizeof(ErlExternal));
  erlExternal->type = VM_CONTEXT;
  erlExternal->ptr = this;
  Persistent<External> external = Persistent<External>::New(
      External::New(erlExternal));
  external.MakeWeak(NULL, VmContextDestroy);

  return external;
}

ERL_NIF_TERM VmContext::MakeTerm(ErlNifEnv *env) {
  TRACE("Vm::MakeTerm\n");
  return enif_make_resource_binary(env, erlVmContext, id, strlen(id));
}
<|endoftext|>


<commit_before>c38756b5-4b02-11e5-a944-28cfe9171a43<commit_msg>Hey we can now do a thing<commit_after>c392cafa-4b02-11e5-bbd7-28cfe9171a43<|endoftext|>


<commit_before>#include "precompiled.h"

#include "engine/math/vec2.h"

vec2::vec2() {
    x = 0;
    y = 0;
}

vec2::vec2(const int newX, const int newY) {
    x = newX;
    y = newY;
}

vec2::vec2(const vec2& vec) {
    x = vec.x;
    y = vec.y;
}

vec2& vec2::operator+=(const vec2 &rhs) {
    this->x += rhs.x;
    this->y += rhs.y;
    return *this;
}

vec2& vec2::operator-=(const vec2 &rhs) {
    this->x -= rhs.x;
    this->y -= rhs.y;
    return *this;
}

vec2& vec2::operator*=(int rhs) {
    this->x *= rhs;
    this->y *= rhs;
    return *this;
}

vec2& vec2::operator/=(int rhs) {
    this->x /= rhs;
    this->y /= rhs;
    return *this;
}

bool vec2::operator==(const vec2 &rhs) {
    return this->x == rhs.x && this->y == rhs.y;
}

bool vec2::operator!=(const vec2 &rhs) {
    return this->x != rhs.x || this->y != rhs.y;
}

vec2 vec2::operator+(const vec2 &rhs) {
    return vec2(*this) += rhs;
}

vec2 vec2::operator-(const vec2 &rhs) {
    return vec2(*this) -= rhs;
}

vec2 vec2::operator*(int rhs) {
    return vec2(*this) *= rhs;
}

vec2 vec2::operator/(int rhs) {
    return vec2(*this) /= rhs;
}

int vec2::operator*(const vec2 &rhs) {
    return this->x * rhs.x + this->y * rhs.y;
}

int vec2::distanceSquared() const {
    return x * x + y * y;
}

double vec2::distance() const {
    return sqrt((double) distanceSquared());
}

bool vec2::operator < (const vec2 & rhs) const {
    if ( distanceSquared() < rhs.distanceSquared() ) {
        return true;
    }
    else {
        return false;
    }
}

bool vec2::operator > (const vec2 & rhs) const {
    if ( distanceSquared() > rhs.distanceSquared() ) {
        return true;
    }
    else {
        return false;
    }
}<commit_msg>Converted spaces to tabs.<commit_after>#include "precompiled.h"

#include "engine/math/vec2.h"

vec2::vec2() {
	x = 0;
	y = 0;
}

vec2::vec2(const int newX, const int newY) {
	x = newX;
	y = newY;
}

vec2::vec2(const vec2& vec) {
	x = vec.x;
	y = vec.y;
}

vec2& vec2::operator+=(const vec2 &rhs) {
	this->x += rhs.x;
	this->y += rhs.y;
	return *this;
}

vec2& vec2::operator-=(const vec2 &rhs) {
	this->x -= rhs.x;
	this->y -= rhs.y;
	return *this;
}

vec2& vec2::operator*=(int rhs) {
	this->x *= rhs;
	this->y *= rhs;
	return *this;
}

vec2& vec2::operator/=(int rhs) {
	this->x /= rhs;
	this->y /= rhs;
	return *this;
}

bool vec2::operator==(const vec2 &rhs) {
	return this->x == rhs.x && this->y == rhs.y;
}

bool vec2::operator!=(const vec2 &rhs) {
	return this->x != rhs.x || this->y != rhs.y;
}

vec2 vec2::operator+(const vec2 &rhs) {
	return vec2(*this) += rhs;
}

vec2 vec2::operator-(const vec2 &rhs) {
	return vec2(*this) -= rhs;
}

vec2 vec2::operator*(int rhs) {
	return vec2(*this) *= rhs;
}

vec2 vec2::operator/(int rhs) {
	return vec2(*this) /= rhs;
}

int vec2::operator*(const vec2 &rhs) {
	return this->x * rhs.x + this->y * rhs.y;
}

int vec2::distanceSquared() const {
	return x * x + y * y;
}

double vec2::distance() const {
	return sqrt((double) distanceSquared());
}

bool vec2::operator < (const vec2 & rhs) const {
	if ( distanceSquared() < rhs.distanceSquared() ) {
		return true;
	}
	else {
		return false;
	}
}

bool vec2::operator > (const vec2 & rhs) const {
	if ( distanceSquared() > rhs.distanceSquared() ) {
		return true;
	}
	else {
		return false;
	}
}<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: NekLinAlgAlgorithms.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Linear Algebra Algorithms
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP
#define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP

#include <LibUtilities/LinearAlgebra/NekVector.hpp>
#include <LibUtilities/LinearAlgebra/NekMatrix.hpp>
#include <vector>

namespace Nektar
{
    /// \brief Calculates the orthogonal, normalized vectros from linearly independent input.
    /// \return A list of ortogonalized vectors corresponding to the input vectors.  If the size
    ///         of the output doesn't match the size of the input then an error occurred.
    /// This algorithm is taken from "Parallel Scientific Computing in C++ and MPI",
    /// Karniadakis and Kirby, page 55.
    template<typename DataType, unsigned int VectorDimension, typename space>
    std::vector<NekVector<DataType, VectorDimension, space> >
    GramSchmidtOrthogonalization(const std::vector<NekVector<DataType, VectorDimension, space> >& x)
    {
        typedef NekVector<DataType, VectorDimension, space> VectorType;
        typedef NekMatrix<DataType> MatrixType;

        typename dim = x[0].GetDimension();
        std::vector<VectorType> q(x.size(), VectorType());

        // This matrix holds the r_ij values.  Using the matrix object is a convenience
        // since it provides a 2D access to a table of values.
        MatrixType r(dim, dim);
        r(0,0) = x[0].L2Norm();

        if( r(0,0) == DataType(0) )
        {
            return q;
        }

        q[0] = x[0]/r(0,0);

        for(unsigned int j = 1; j < x.size(); ++j)
        {
            for(unsigned int i = 0; i <= j-1; ++i)
            {
                r(i,j) = q[i].Dot(x[j]);
            }

            VectorType y = x[j];
            for(unsigned int i = 0; i <= j-1; ++i)
            {
                y = y - r(i,j)*q[i];
            }

            r(j,j) = y.L2Norm();
            if( r(j,j) == DataType(0) )
            {
                return q;
            }

            q[j] = y/r(j,j);
        }

        return q;
    }
}

#endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP

/**
    $Log: NekLinAlgAlgorithms.hpp,v $
    Revision 1.2  2007/02/15 06:56:55  bnelson
    *** empty log message ***

    Revision 1.1  2006/11/20 03:39:06  bnelson
    Initial Revision

**/
<commit_msg>Changed the template declaration for the second template parameter from unsigned int to typename.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: NekLinAlgAlgorithms.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Linear Algebra Algorithms
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP
#define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP

#include <LibUtilities/LinearAlgebra/NekVector.hpp>
#include <LibUtilities/LinearAlgebra/NekMatrix.hpp>
#include <vector>

namespace Nektar
{
    /// \brief Calculates the orthogonal, normalized vectros from linearly independent input.
    /// \return A list of ortogonalized vectors corresponding to the input vectors.  If the size
    ///         of the output doesn't match the size of the input then an error occurred.
    /// This algorithm is taken from "Parallel Scientific Computing in C++ and MPI",
    /// Karniadakis and Kirby, page 55.
    template<typename DataType, typename VectorDimension, typename space>
    std::vector<NekVector<DataType, VectorDimension, space> >
    GramSchmidtOrthogonalization(const std::vector<NekVector<DataType, VectorDimension, space> >& x)
    {
        typedef NekVector<DataType, VectorDimension, space> VectorType;
        typedef NekMatrix<DataType> MatrixType;

        //typename dim = x[0].GetDimension();
        unsigned int dim = x[0].GetDimension();
        std::vector<VectorType> q(x.size(), VectorType());

        // This matrix holds the r_ij values.  Using the matrix object is a convenience
        // since it provides a 2D access to a table of values.
        MatrixType r(dim, dim);
        r(0,0) = x[0].L2Norm();

        if( r(0,0) == DataType(0) )
        {
            return q;
        }

        q[0] = x[0]/r(0,0);

        for(unsigned int j = 1; j < x.size(); ++j)
        {
            for(unsigned int i = 0; i <= j-1; ++i)
            {
                r(i,j) = q[i].Dot(x[j]);
            }

            VectorType y = x[j];
            for(unsigned int i = 0; i <= j-1; ++i)
            {
                y = y - r(i,j)*q[i];
            }

            r(j,j) = y.L2Norm();
            if( r(j,j) == DataType(0) )
            {
                return q;
            }

            q[j] = y/r(j,j);
        }

        return q;
    }
}

#endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_LIN_ALG_ALGORITHMS_HPP

/**
    $Log: NekLinAlgAlgorithms.hpp,v $
    Revision 1.3  2008/03/03 02:28:39  bnelson
    Changed OneD, TwoD, and ThreeD to classes instead of enums to support type parameters in NekVector instead of unsigned int for the dimensions.

    Added a new NekVector<const DataType> to allow wrapping of ConstArrays.

    Revision 1.2  2007/02/15 06:56:55  bnelson
    *** empty log message ***

    Revision 1.1  2006/11/20 03:39:06  bnelson
    Initial Revision

**/
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_obus_scom.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _INIT_P9_OBUS_SCOM_PROCEDURE_H_
#define _INIT_P9_OBUS_SCOM_PROCEDURE_H_

#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_obus_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>&,
        const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>&);

extern "C"
{

    fapi2::ReturnCode p9_obus_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
                                   const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1);

}

#endif
<commit_msg>Updates to initcompiler to support DD2 and cumulus<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_obus_scom.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _INIT_P9_OBUS_SCOM_PROCEDURE_H_
#define _INIT_P9_OBUS_SCOM_PROCEDURE_H_

#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_obus_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>&,
        const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>&, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

extern "C"
{

    fapi2::ReturnCode p9_obus_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
                                   const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2);

}

#endif
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "PlayerEndpointImpl.hpp"
#include <generated/MediaPipeline.hpp>

#define GST_CAT_DEFAULT kurento_player_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoPlayerEndpointImpl"

#define FACTORY_NAME "playerendpoint"

namespace kurento
{

static void
adaptor_function (GstElement *player, gpointer data)
{
  auto handler = reinterpret_cast<std::function<void() >*> (data);

  (*handler) ();
}

PlayerEndpointImpl::PlayerEndpointImpl (bool useEncodedMedia,
                                        const std::string &uri,
                                        std::shared_ptr< MediaObjectImpl > parent) :
  UriEndpointImpl (uri, FACTORY_NAME, parent)
{
  GstElement *element = getGstreamerElement();

  g_object_set (G_OBJECT (element), "use-encoded-media", useEncodedMedia, NULL);

  eosLambda = [&] () {
    try {
      EndOfStream event (shared_from_this(), EndOfStream::getName() );

      signalEndOfStream (event);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  invalidUriLambda = [&] () {
    try {
      /* TODO: Define error codes and types*/
      Error error (shared_from_this(), "Invalid Uri", 0, "INVALID_URI");

      signalError (error);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  invalidMediaLambda = [&] () {
    try {
      /* TODO: Define error codes and types*/
      Error error (shared_from_this(), "Invalid Media", 0, "INVALID_MEDIA");

      signalError (error);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  signalEOS = g_signal_connect (element, "eos", G_CALLBACK (adaptor_function),
                                &eosLambda);
  signalInvalidURI = g_signal_connect (element, "invalid-uri",
                                       G_CALLBACK (adaptor_function),
                                       &invalidUriLambda);
  signalInvalidMedia = g_signal_connect (element, "invalid-media",
                                         G_CALLBACK (adaptor_function),
                                         &invalidMediaLambda);
}

PlayerEndpointImpl::~PlayerEndpointImpl()
{
  g_signal_handler_disconnect (element, signalEOS);
  g_signal_handler_disconnect (element, signalInvalidMedia);
  g_signal_handler_disconnect (element, signalInvalidURI);
}

void
PlayerEndpointImpl::play ()
{
  start();
}

MediaObject *
PlayerEndpoint::Factory::createObject (
  std::shared_ptr<MediaPipeline> mediaPipeline, const std::string &uri,
  bool useEncodedMedia)
{
  return  new PlayerEndpointImpl (useEncodedMedia, uri,
                                  std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline) );
}

PlayerEndpointImpl::StaticConstructor PlayerEndpointImpl::staticConstructor;

PlayerEndpointImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<commit_msg>PlayerEndpoint: Stop player before release it<commit_after>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "PlayerEndpointImpl.hpp"
#include <generated/MediaPipeline.hpp>

#define GST_CAT_DEFAULT kurento_player_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoPlayerEndpointImpl"

#define FACTORY_NAME "playerendpoint"

namespace kurento
{

static void
adaptor_function (GstElement *player, gpointer data)
{
  auto handler = reinterpret_cast<std::function<void() >*> (data);

  (*handler) ();
}

PlayerEndpointImpl::PlayerEndpointImpl (bool useEncodedMedia,
                                        const std::string &uri,
                                        std::shared_ptr< MediaObjectImpl > parent) :
  UriEndpointImpl (uri, FACTORY_NAME, parent)
{
  GstElement *element = getGstreamerElement();

  g_object_set (G_OBJECT (element), "use-encoded-media", useEncodedMedia, NULL);

  eosLambda = [&] () {
    try {
      EndOfStream event (shared_from_this(), EndOfStream::getName() );

      signalEndOfStream (event);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  invalidUriLambda = [&] () {
    try {
      /* TODO: Define error codes and types*/
      Error error (shared_from_this(), "Invalid Uri", 0, "INVALID_URI");

      signalError (error);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  invalidMediaLambda = [&] () {
    try {
      /* TODO: Define error codes and types*/
      Error error (shared_from_this(), "Invalid Media", 0, "INVALID_MEDIA");

      signalError (error);
    } catch (std::bad_weak_ptr &e) {
    }
  };

  signalEOS = g_signal_connect (element, "eos", G_CALLBACK (adaptor_function),
                                &eosLambda);
  signalInvalidURI = g_signal_connect (element, "invalid-uri",
                                       G_CALLBACK (adaptor_function),
                                       &invalidUriLambda);
  signalInvalidMedia = g_signal_connect (element, "invalid-media",
                                         G_CALLBACK (adaptor_function),
                                         &invalidMediaLambda);
}

PlayerEndpointImpl::~PlayerEndpointImpl()
{
  g_signal_handler_disconnect (element, signalEOS);
  g_signal_handler_disconnect (element, signalInvalidMedia);
  g_signal_handler_disconnect (element, signalInvalidURI);
  stop();
}

void
PlayerEndpointImpl::play ()
{
  start();
}

MediaObject *
PlayerEndpoint::Factory::createObject (
  std::shared_ptr<MediaPipeline> mediaPipeline, const std::string &uri,
  bool useEncodedMedia)
{
  return  new PlayerEndpointImpl (useEncodedMedia, uri,
                                  std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline) );
}

PlayerEndpointImpl::StaticConstructor PlayerEndpointImpl::staticConstructor;

PlayerEndpointImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<|endoftext|>