<commit_before>#pragma once

/*
MIT License

Copyright (c) 2017 Blockchain-VCS

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.
*/

#include "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file
#include <iostream> // std::cout
#include <string> // std::string
#include <ctime> // time_t localtime() struct tm* asctime()
#include <chrono> // std::chrono::high_resolution_clock, std::chrono::duration_cast, std::chrono::nanoseconds
#include <stdexcept> // throw throw std::runtime_error()
#include <vector> // std::vector
#include "operators.hpp"
#include "conversions.hpp" // toBytes()
#include "constants.hpp" // MAX_BLOCK_SIZE

extern "C" void lockBlockASM(unsigned long timeout);
extern "C" long mineASM(void* dataAddr, long dataSize);

namespace BlockchainCpp {

	template <class DataType>

	class Block {

	public:

		Block(DataType* data) {
			this->data = data;
		}

		virtual ~Block(){
			// delete data;
		}

		long mine() {
			std::cout << "Mining Block " << this->height << std::endl;
			auto start = std::chrono::high_resolution_clock::now();
			this->setValue(mineASM(reinterpret_cast<void*>(this->data), sizeof(this->data)));
			auto end = std::chrono::high_resolution_clock::now();
			auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
			std::cout << "Block " << this->height << " Was Sucessfully Mined in: " << diff << " ns" << std::endl;
			return this->value;
		}

		bool lock(unsigned long timeout = 1000L) {
			if(this->timeLocked != 0)
				return true;

			lockBlockASM(timeout);

			time_t now;
			time(&now);
			struct tm* timeinfo;
			timeinfo = localtime(&now);
			this->timeLocked = now - (timeout / 1000);
			time_t _time = this->timeLocked;
			this->hash = computeHash();
			std::cout << "Block " << this->height << " has sucessfully been locked" << std::endl;
			return this->timeLocked != 0;
		}

		bool verify() const {
			if(this->timeLocked == 0)
				if(!lock(1000))
				throw std::runtime_error("Could not lock block after 1000 cycles");
			std::string newHash = computeHash();
			return newHash == this->hash;
		}

		DataType* getData() const {
			return this->data;
		}

		std::string getHash() const {
			return this->hash;
		}

		long getHeight() const {
			return this->height;
		}

		time_t getTimeCreated() const {
			return this->timeCreated;
		}

		time_t getTimeLocked() const {
			return this->timeLocked;
		}

		unsigned long getSize() const {
			return this->getSize;
		}

		unsigned long getBits() const {
			return this.bits;
		}

		char isMainChain() const {
			if (this->isMainChain == -1)
				return 0;
			return this.mainChain;
		}

		long getIndex() const {
			return this->index;
		}

		long getValue() const {
			return this->value;
		}

		std::string getPreviousHash() const {
			if (this->previousHash == "")
				return "";
			return this-> previousHash;
		}

		void setData(DataType* data){
			if(this->data != nullptr)
				throw std::runtime_error("Data has already been set!");
			if(data == nullptr || *(data) = NULL)
				throw std::runtime_error("Can not set block data to null");
			*(this->data) = *(data);
			this-> data = data;
		}

		void setHash() {
			if(this->hash != "")
				throw std::runtime_error("Hash has already been set");
			this->hash = computeHash();
		}

		void setHeight(long height){
			if(this->height != -1)
				throw std::runtime_error("Block Height has already been set");
			if(height == 0)
				throw std::runtime_error("Height must be greater than 0");
			this->height = height;
		}

		void setTimeCreated(time_t time) {
			if(this->timeCreated != 0) {
				struct tm* timeinfo;
				timeinfo = localtime(&this->timeCreated);
				time_t _time = this->timeCreated;
				throw std::runtime_error("Block was already created");
			}
			this->time = time;
		}

		void setTimeLocked(time_t time) {
			if(this->timeLocked != 0) {
				struct tm* timeinfo;
				timeinfo = localtime(&this->timeLocked);
				time_t _time = this->timeLocked;
				throw std::runtime_error("Block was already locked");
			}
			this->timeLocked = time;
		}

		void setIsMainChain(bool isMainChain){
			if(this->mainChain != -1)
				throw std::runtime_error("Main Chain property has already been set to: " + static_cast<bool>(this->mainChain +
				"\n To unlink or link this block from the main chain " +
				"you must first create an immutable uncle (orphaned block) to merge into its place"));
			this->mainChain = static_cast<char>(isMainChain);
		}

		void setIndex(long index) {
			if(this->index >= 0)
				throw std::runtime_error("Index has already been set");
			this->index = index;
		}

		void setValue(long value) {
			if(this->value != -1)
				throw std::runtime_error("Value has already been set");
			this->value = value;
		}

		void setPreviousHash(std::string _hash){
			if(previousHash != "")
				throw std::runtime_error("Previous Hash has already been set!");
			previousHash = _hash;
		}

	protected:
		DataType* data = nullptr;
		std::string hash = "";
		long height = -1;
		time_t timeCreated = 0;
		time_t timeLocked = 0;
		const unsigned long size = sizeof(DataType);
		const unsigned long bits = size * 8;
		char mainChain = -1;
		long index = -1;
		long value = -1;
		long nonce = -1;
		std::string previousHash = "";

	private:
		std::vector<unsigned char> bytes = std::vector<unsigned char>(sizeof(DataType));

	std::string computeHash() {
		if(timeLocked == 0)
			throw std::runtime_error("Can not compute the hash of an unlocked block");
		std::string outHash = "";
		int b = 0;
		auto t = std::chrono::high_resolution_clock::now();
		long generator = std::chrono::time_point_cast<std::chrono::nanoseconds>(t).time_since_epoch().count();
		while(b < sizeof(DataType)) {
			bytes.push_back(static_cast<unsigned char>(*(data + b++)));
		}
		bytes += Conversions::toBytes(&generator);
		picosha2::hash256_hex_string(bytes, outHash);
		return outHash;
	}
	};
	template <class DataType>
	bool operator==(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height == rhs.height;
	}

	template <class DataType>
	bool operator!=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height != rhs.height;
	}

	template <class DataType>
	bool operator<(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height < rhs.height;
	}

	template <class DataType>
	bool operator<=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height <= rhs.height;
	}

	template <class DataType>
	bool operator>(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height > rhs.height;
	}

	template <class DataType>
	bool operator>=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height >= rhs.height;
	}
}

<commit_msg>Remove old hashing system from block<commit_after>#pragma once

/*
MIT License

Copyright (c) 2017 Blockchain-VCS

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.
*/

#include "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file
#include <iostream> // std::cout
#include <string> // std::string
#include <ctime> // time_t localtime() struct tm* asctime()
#include <chrono> // std::chrono::high_resolution_clock, std::chrono::duration_cast, std::chrono::nanoseconds
#include <stdexcept> // throw throw std::runtime_error()
#include <vector> // std::vector
#include "operators.hpp"
#include "conversions.hpp" // toBytes()
#include "constants.hpp" // MAX_BLOCK_SIZE

extern "C" void lockBlockASM(unsigned long timeout);
extern "C" long mineASM(void* dataAddr, long dataSize);

namespace BlockchainCpp {

	template <class DataType>

	class Block {

	public:

		Block(DataType* data) {
			this->data = data;
		}

		virtual ~Block(){
			// delete data;
		}

		long mine() {
			std::cout << "Mining Block " << this->height << std::endl;
			auto start = std::chrono::high_resolution_clock::now();
			this->setValue(mineASM(reinterpret_cast<void*>(this->data), sizeof(this->data)));
			auto end = std::chrono::high_resolution_clock::now();
			auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
			std::cout << "Block " << this->height << " Was Sucessfully Mined in: " << diff << " ns" << std::endl;
			return this->value;
		}

		bool lock(unsigned long timeout = 1000L) {
			if(this->timeLocked != 0)
				return true;

			lockBlockASM(timeout);

			time_t now;
			time(&now);
			struct tm* timeinfo;
			timeinfo = localtime(&now);
			this->timeLocked = now - (timeout / 1000);
			time_t _time = this->timeLocked;
			this->hash = computeHash();
			std::cout << "Block " << this->height << " has sucessfully been locked" << std::endl;
			return this->timeLocked != 0;
		}

		bool verify() const {
			if(this->timeLocked == 0)
				if(!lock(1000))
				throw std::runtime_error("Could not lock block after 1000 cycles");
			std::string newHash = computeHash();
			return newHash == this->hash;
		}

		DataType* getData() const {
			return this->data;
		}

		std::string getHash() const {
			return this->hash;
		}

		long getHeight() const {
			return this->height;
		}

		time_t getTimeCreated() const {
			return this->timeCreated;
		}

		time_t getTimeLocked() const {
			return this->timeLocked;
		}

		unsigned long getSize() const {
			return this->getSize;
		}

		unsigned long getBits() const {
			return this.bits;
		}

		char isMainChain() const {
			if (this->isMainChain == -1)
				return 0;
			return this.mainChain;
		}

		long getIndex() const {
			return this->index;
		}

		long getValue() const {
			return this->value;
		}

		std::string getPreviousHash() const {
			if (this->previousHash == "")
				return "";
			return this-> previousHash;
		}

		void setData(DataType* data){
			if(this->data != nullptr)
				throw std::runtime_error("Data has already been set!");
			if(data == nullptr || *(data) = NULL)
				throw std::runtime_error("Can not set block data to null");
			*(this->data) = *(data);
			this-> data = data;
		}

		void setHash() {
			if(this->hash != "")
				throw std::runtime_error("Hash has already been set");
			this->hash = computeHash();
		}

		void setHeight(long height){
			if(this->height != -1)
				throw std::runtime_error("Block Height has already been set");
			if(height == 0)
				throw std::runtime_error("Height must be greater than 0");
			this->height = height;
		}

		void setTimeCreated(time_t time) {
			if(this->timeCreated != 0) {
				struct tm* timeinfo;
				timeinfo = localtime(&this->timeCreated);
				time_t _time = this->timeCreated;
				throw std::runtime_error("Block was already created");
			}
			this->time = time;
		}

		void setTimeLocked(time_t time) {
			if(this->timeLocked != 0) {
				struct tm* timeinfo;
				timeinfo = localtime(&this->timeLocked);
				time_t _time = this->timeLocked;
				throw std::runtime_error("Block was already locked");
			}
			this->timeLocked = time;
		}

		void setIsMainChain(bool isMainChain){
			if(this->mainChain != -1)
				throw std::runtime_error("Main Chain property has already been set to: " + static_cast<bool>(this->mainChain +
				"\n To unlink or link this block from the main chain " +
				"you must first create an immutable uncle (orphaned block) to merge into its place"));
			this->mainChain = static_cast<char>(isMainChain);
		}

		void setIndex(long index) {
			if(this->index >= 0)
				throw std::runtime_error("Index has already been set");
			this->index = index;
		}

		void setValue(long value) {
			if(this->value != -1)
				throw std::runtime_error("Value has already been set");
			this->value = value;
		}

		void setPreviousHash(std::string _hash){
			if(previousHash != "")
				throw std::runtime_error("Previous Hash has already been set!");
			previousHash = _hash;
		}

	protected:
		DataType* data = nullptr;
		std::string hash = "";
		long height = -1;
		time_t timeCreated = 0;
		time_t timeLocked = 0;
		const unsigned long size = sizeof(DataType);
		const unsigned long bits = size * 8;
		char mainChain = -1;
		long index = -1;
		long value = -1;
		long nonce = -1;
		std::string previousHash = "";

	private:
		std::vector<unsigned char> bytes = std::vector<unsigned char>(sizeof(DataType));

	std::string computeHash() {
		return "";
	}
	};
	template <class DataType>
	bool operator==(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height == rhs.height;
	}

	template <class DataType>
	bool operator!=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height != rhs.height;
	}

	template <class DataType>
	bool operator<(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height < rhs.height;
	}

	template <class DataType>
	bool operator<=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height <= rhs.height;
	}

	template <class DataType>
	bool operator>(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height > rhs.height;
	}

	template <class DataType>
	bool operator>=(const Block<DataType>& lhs, const Block<DataType>& rhs) {
		return lhs.height >= rhs.height;
	}
}

<|endoftext|>


<commit_before>#ifndef TESTLINEDETECTION_HPP
#define TESTLINEDETECTION_HPP

#include <QtTest>
#include <intelligence/linedetection/linedetector.h>
#include <iostream>
#ifdef _WIN32
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
#endif

class TestLineDetection: public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void testCase1()
    {
        //char videoFile[] = "../igvc_cam_data/stills/img_left2.jpg";
        char videoFile[] = "../src/intelligence/igvc_cam_data/video/CompCourse_left0.mpeg";

         LineDetector ln(videoFile);
         bool success =true;
         while(success){

             ln.applyAlgorithm();
             success = ln.loadImage(videoFile);
         }
    }
};

#endif // TESTLINEDETECTION_HPP
<commit_msg>Added some more comments<commit_after>#ifndef TESTLINEDETECTION_HPP
#define TESTLINEDETECTION_HPP

#include <QtTest>
#include <intelligence/linedetection/linedetector.h>
#include <iostream>
#ifdef _WIN32
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
#endif

class TestLineDetection: public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void testCase1()
    {
        //char videoFile[] = "../igvc_cam_data/stills/img_left2.jpg";
        ///Note: This may not be the correct directory on your computer
        char videoFile[] = "../src/intelligence/igvc_cam_data/video/CompCourse_left0.mpeg";

         LineDetector ln(videoFile);
         bool success =true;
         while(success){

             ln.applyAlgorithm();
             success = ln.loadImage(videoFile);
         }
    }
};

#endif // TESTLINEDETECTION_HPP
<|endoftext|>


<commit_before>#include "videoviewfactory.h"

#include "videowidget.h"
#include "videoglwidget.h"
#include "videoyuvwidget.h"

// this annoys me, but I can live with it. The only smart way to fix it would be to get signal connect working
#include "conferenceview.h"

#include "common.h"
#include "settingskeys.h"
#include "logger.h"

#include <QSettings>

VideoviewFactory::VideoviewFactory(ConferenceView* conf):
  conf_(conf),
  sessionIDtoWidgetlist_(),
  sessionIDtoVideolist_(),
  selfViews_(),
  selfVideos_(),
  opengl_(false)
{}

VideoviewFactory::~VideoviewFactory()
{
  sessionIDtoWidgetlist_.clear(); // these are the same pointers as in videolist

  for (auto& video : sessionIDtoVideolist_)
  {
    if (video.second)
    {
      delete video.second;
    }
  }
  sessionIDtoVideolist_.clear();
}

void VideoviewFactory::createWidget(uint32_t sessionID)
{
  Logger::getLogger()->printDebug(DEBUG_NORMAL, "View Factory",
                                  "Creating videoWidget", {"SessionID"}, {QString::number(sessionID)});

  bool openGLEnabled = settingEnabled(SettingsKey::videoOpenGL);

  QWidget* vw = nullptr;
  VideoInterface* video = nullptr;

  // couldn't get these to work with videointerface, so the videowidget is used.
  // TODO: try qobject_cast to get the signal working for videointerface

  QWidget* parent = nullptr;

  if(false && !opengl_) // YUV widget not working yet
  {
    VideoYUVWidget* yuv = new VideoYUVWidget(parent, sessionID);
    vw = yuv;
    video = yuv;

    // signals reattaching after fullscreen mode
    QObject::connect(yuv, &VideoYUVWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(yuv, &VideoYUVWidget::detach, conf_, &ConferenceView::detachWidget);

    opengl_ = true;
  }
  else if(openGLEnabled)
  {
    VideoGLWidget* opengl = new VideoGLWidget(parent, sessionID);
    vw = opengl;
    video = opengl;

    // couldn't get this to work with videointerface, so the videowidget is used.

    // signals reattaching after fullscreen mode
    QObject::connect(opengl, &VideoGLWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(opengl, &VideoGLWidget::detach, conf_, &ConferenceView::detachWidget);
  }
  else
  {
    VideoWidget* normal = new VideoWidget(parent, sessionID);
    vw = normal;
    video = normal;
    // couldn't get this to work with videointerface, so the videowidget is used.

    // signals reattaching after fullscreen mode
    QObject::connect(normal, &VideoWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(normal, &VideoWidget::detach, conf_, &ConferenceView::detachWidget);
  }

  if (vw != nullptr && video != nullptr)
  {
    sessionIDtoWidgetlist_[sessionID] = vw;
    sessionIDtoVideolist_[sessionID]  = video;
    Logger::getLogger()->printDebug(DEBUG_NORMAL, "VideoviewFactory",
                                    "Created video widget.", {"SessionID"},
                                    {QString::number(sessionID)});
  }
  else
  {
    Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, "VideoviewFactory", "Failed to create view widget.");
  }
}

void VideoviewFactory::addSelfview(VideoInterface *video, QWidget *view)
{
  selfViews_.push_back(view);
  selfVideos_.push_back(video);
}

QList<QWidget*> VideoviewFactory::getSelfViews()
{
  return selfViews_;
}

QList<VideoInterface*> VideoviewFactory::getSelfVideos()
{
  return selfVideos_;
}

QWidget* VideoviewFactory::getView(uint32_t sessionID)
{
  if(sessionIDtoWidgetlist_.find(sessionID) == sessionIDtoWidgetlist_.end())
  {
    createWidget(sessionID);
  }
  return sessionIDtoWidgetlist_[sessionID];
}

VideoInterface* VideoviewFactory::getVideo(uint32_t sessionID)
{
  if(sessionIDtoVideolist_.find(sessionID) == sessionIDtoVideolist_.end())
  {
    createWidget(sessionID);
  }
  return sessionIDtoVideolist_[sessionID];
}

void VideoviewFactory::clearWidgets(uint32_t sessionID)
{
  Logger::getLogger()->printDebug(DEBUG_NORMAL, "VideoviewFactory",  "Clearing widgets",
                                  {"SessionID"}, {QString::number(sessionID)});

  if (sessionIDtoWidgetlist_.find(sessionID) != sessionIDtoWidgetlist_.end())
  {
    sessionIDtoWidgetlist_.erase(sessionID);
  }

  if (sessionIDtoVideolist_.find(sessionID) != sessionIDtoVideolist_.end())
  {
    delete sessionIDtoVideolist_[sessionID];
    sessionIDtoVideolist_.erase(sessionID);
  }
}
<commit_msg>fix(GUI): Do not double delete widgets<commit_after>#include "videoviewfactory.h"

#include "videowidget.h"
#include "videoglwidget.h"
#include "videoyuvwidget.h"

// this annoys me, but I can live with it. The only smart way to fix it would be to get signal connect working
#include "conferenceview.h"

#include "common.h"
#include "settingskeys.h"
#include "logger.h"

#include <QSettings>

VideoviewFactory::VideoviewFactory(ConferenceView* conf):
  conf_(conf),
  sessionIDtoWidgetlist_(),
  sessionIDtoVideolist_(),
  selfViews_(),
  selfVideos_(),
  opengl_(false)
{}

VideoviewFactory::~VideoviewFactory()
{
  sessionIDtoWidgetlist_.clear(); // these are the same pointers as in videolist
  sessionIDtoVideolist_.clear();
}

void VideoviewFactory::createWidget(uint32_t sessionID)
{
  Logger::getLogger()->printDebug(DEBUG_NORMAL, "View Factory",
                                  "Creating videoWidget", {"SessionID"}, {QString::number(sessionID)});

  bool openGLEnabled = settingEnabled(SettingsKey::videoOpenGL);

  QWidget* vw = nullptr;
  VideoInterface* video = nullptr;

  // couldn't get these to work with videointerface, so the videowidget is used.
  // TODO: try qobject_cast to get the signal working for videointerface

  QWidget* parent = nullptr;

  if(false && !opengl_) // YUV widget not working yet
  {
    VideoYUVWidget* yuv = new VideoYUVWidget(parent, sessionID);
    vw = yuv;
    video = yuv;

    // signals reattaching after fullscreen mode
    QObject::connect(yuv, &VideoYUVWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(yuv, &VideoYUVWidget::detach, conf_, &ConferenceView::detachWidget);

    opengl_ = true;
  }
  else if(openGLEnabled)
  {
    VideoGLWidget* opengl = new VideoGLWidget(parent, sessionID);
    vw = opengl;
    video = opengl;

    // couldn't get this to work with videointerface, so the videowidget is used.

    // signals reattaching after fullscreen mode
    QObject::connect(opengl, &VideoGLWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(opengl, &VideoGLWidget::detach, conf_, &ConferenceView::detachWidget);
  }
  else
  {
    VideoWidget* normal = new VideoWidget(parent, sessionID);
    vw = normal;
    video = normal;
    // couldn't get this to work with videointerface, so the videowidget is used.

    // signals reattaching after fullscreen mode
    QObject::connect(normal, &VideoWidget::reattach, conf_, &ConferenceView::reattachWidget);
    QObject::connect(normal, &VideoWidget::detach, conf_, &ConferenceView::detachWidget);
  }

  if (vw != nullptr && video != nullptr)
  {
    sessionIDtoWidgetlist_[sessionID] = vw;
    sessionIDtoVideolist_[sessionID]  = video;
    Logger::getLogger()->printDebug(DEBUG_NORMAL, "VideoviewFactory",
                                    "Created video widget.", {"SessionID"},
                                    {QString::number(sessionID)});
  }
  else
  {
    Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, "VideoviewFactory", "Failed to create view widget.");
  }
}

void VideoviewFactory::addSelfview(VideoInterface *video, QWidget *view)
{
  selfViews_.push_back(view);
  selfVideos_.push_back(video);
}

QList<QWidget*> VideoviewFactory::getSelfViews()
{
  return selfViews_;
}

QList<VideoInterface*> VideoviewFactory::getSelfVideos()
{
  return selfVideos_;
}

QWidget* VideoviewFactory::getView(uint32_t sessionID)
{
  if(sessionIDtoWidgetlist_.find(sessionID) == sessionIDtoWidgetlist_.end())
  {
    createWidget(sessionID);
  }
  return sessionIDtoWidgetlist_[sessionID];
}

VideoInterface* VideoviewFactory::getVideo(uint32_t sessionID)
{
  if(sessionIDtoVideolist_.find(sessionID) == sessionIDtoVideolist_.end())
  {
    createWidget(sessionID);
  }
  return sessionIDtoVideolist_[sessionID];
}

void VideoviewFactory::clearWidgets(uint32_t sessionID)
{
  Logger::getLogger()->printDebug(DEBUG_NORMAL, "VideoviewFactory",  "Clearing widgets",
                                  {"SessionID"}, {QString::number(sessionID)});

  if (sessionIDtoWidgetlist_.find(sessionID) != sessionIDtoWidgetlist_.end())
  {
    sessionIDtoWidgetlist_.erase(sessionID);
  }

  if (sessionIDtoVideolist_.find(sessionID) != sessionIDtoVideolist_.end())
  {
    delete sessionIDtoVideolist_[sessionID];
    sessionIDtoVideolist_.erase(sessionID);
  }
}
<|endoftext|>


<commit_before>#include "environment/program_config.h"

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <random>

#include "cppunit-header.h"

class test_config : public program_config
{
 public:
	test_config()
	  : program_config({
		{ argument_type::none, "help", 'h', "Prints this message" },
		{ argument_type::required, "required", 'r', "Required argument" },
		{ argument_type::optional, "optional", 'o', "Optional argument" },
		{ argument_type::none, "longfakeout",'l', "Long opt without param" },
		{ argument_type::optional, "long-only", -1, "No short option" },
	    })
	{
	}

	bool process_option(const config_option & opt,
	                    const std::string & param) override
	{
		if (config::verbose)
			printf("Got option %s with param %s\n",
			       opt.option_synopsis().c_str(), param.c_str());
		return true;
	}

	bool process_option(const config_option & opt)
	{
		if (config::verbose)
			printf("Got option %s\n", opt.option_synopsis().c_str());
		return true;
	}

};

class Test_program_config : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_program_config);
	CPPUNIT_TEST(construction);
	CPPUNIT_TEST(short_options);
	CPPUNIT_TEST(long_options);
	CPPUNIT_TEST(bad_options);
	CPPUNIT_TEST_SUITE_END();

 protected:
	void construction()
	{
		test_config tc;
	}

	void short_options()
	{
		test_config tc;

		const char * command_line[3] = { "prog_name", "-h", "param" };
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-rfoo";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		command_line[1] = "-r";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-o";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-l";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

	}

	void long_options()
	{
		test_config tc;

		const char * command_line[3] = { "prog_name", "--help", "param" };
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--required=foo";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		command_line[1] = "--required";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--optional";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--long-only";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--long-";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--longfakeout";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--longf";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));
	}

	void bad_options()
	{
		test_config tc;

		const char * bad_opts[3] = { "prog_name", "-q", nullptr };

		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--foo";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--long";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--required";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);
#if 0
		const char * bad_opts2[3] = { "prog_name", "--foo", nullptr };
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts2),
		                     std::runtime_error);

		const char * bad_opts3[3] = { "prog_name", "--long", nullptr };
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts3),
		                     std::runtime_error);
#endif
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_program_config);
<commit_msg>More unit test coverage<commit_after>#include "environment/program_config.h"

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <random>

#include "cppunit-header.h"

class parent_config : public program_config
{
 public:
	parent_config()
	  : program_config({
		{ argument_type::none,     "help",       'h', "Prints this message" },
		{ argument_type::required, "required",   'r', "Required argument" },
		{ argument_type::optional, "optional",   'o', "Optional argument" },
		{ argument_type::none,     "longfakeout",'l', "Long opt w/o param" },
		{ argument_type::none,      nullptr,     's', "short only opt" },
		{ argument_type::optional, "long-only",   -1, "No short option" },
	    })
	{
	}
};

class test_config : public program_config
{
 public:
	test_config()
	  : program_config({
		{ argument_type::none,     "help",       'h', "Prints this message" },
		{ argument_type::required, "required",   'r', "Required argument" },
		{ argument_type::optional, "optional",   'o', "Optional argument" },
		{ argument_type::none,     "longfakeout",'l', "Long opt w/o param" },
		{ argument_type::none,     nullptr,      's', "short only opt" },
		{ argument_type::optional, "long-only",   -1, "No short option" },
	    })
	{
	}

	bool process_option(const config_option & opt,
	                    const std::string & param) override
	{
		if (config::verbose)
			printf("Got option %s with param %s\n",
			       opt.option_synopsis().c_str(), param.c_str());
		return true;
	}

	bool process_option(const config_option & opt)
	{
		if (config::verbose)
			printf("Got option %s\n", opt.option_synopsis().c_str());
		return true;
	}

};

class Test_program_config : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_program_config);
	CPPUNIT_TEST(construction);
	CPPUNIT_TEST(overridable_functions);
	CPPUNIT_TEST(short_options);
	CPPUNIT_TEST(long_options);
	CPPUNIT_TEST(non_options);
	CPPUNIT_TEST(bad_options);
	CPPUNIT_TEST_SUITE_END();

 protected:
	void construction()
	{
		parent_config pc;
		test_config tc;
	}

	void overridable_functions()
	{
		parent_config pc;
		const char * command_line[4] = { "prog_name", "-h", "-rxxx", "-l" };
		CPPUNIT_ASSERT_NO_THROW(pc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(pc.parse_command_line(3, command_line));
		CPPUNIT_ASSERT_NO_THROW(pc.parse_command_line(4, command_line));
	}

	void short_options()
	{
		test_config tc;

		const char * command_line[3] = { "prog_name", "-h", "param" };
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-rfoo";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		command_line[1] = "-r";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-o";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "-l";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));
	}

	void long_options()
	{
		test_config tc;

		const char * command_line[3] = { "prog_name", "--help", "param" };
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--required=foo";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		command_line[1] = "--required";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--optional";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--long-only";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--long-";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--longfakeout";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));

		command_line[1] = "--longf";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));
	}

	void bad_options()
	{
		test_config tc;

		const char * bad_opts[3] = { "prog_name", "-q", nullptr };

		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--foo";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--long";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);

		bad_opts[1] = "--required";
		CPPUNIT_ASSERT_THROW(tc.parse_command_line(2, bad_opts),
		                     std::runtime_error);
	}

	void non_options()
	{
		test_config tc;

		const char * command_line[3] = { "prog_name", "--", nullptr };
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT(tc.params().size() == 0);

		command_line[1] = "-";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(2, command_line));
		CPPUNIT_ASSERT(tc.params().size() == 1);

		tc.params().clear();
		command_line[1] = "--";
		command_line[2] = "--help";
		CPPUNIT_ASSERT_NO_THROW(tc.parse_command_line(3, command_line));
		CPPUNIT_ASSERT(tc.params().size() == 1);
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_program_config);
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/targeting/common/util.C $                             */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2015                        */
/* [+] 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                                                     */
/**
 *  @file targeting/common/util.C
 *
 *  @brief Provides miscellaneous utility functions to targeting, including
 *     a check for whether system is in simulation or not.
 */

//******************************************************************************
// Includes
//******************************************************************************
#include <stdint.h>
#include <targeting/common/attributes.H>
#include <targeting/common/targetservice.H>
#include <targeting/common/utilFilter.H>

namespace TARGETING
{

/**
 * @brief Checks to see if we are running in a hardware simulation
 *    environment, i.e. VPO/VBU  (not Simics)
 */
bool is_vpo( void )
{
    struct IsVpoFunctor
    {
        static bool operate()
        {
            bool rc = false;

            Target* sys = NULL;
            targetService().getTopLevelTarget(sys);

            uint8_t vpo_mode = 0;
            if (unlikely(sys &&
                         sys->tryGetAttr<ATTR_IS_SIMULATION>(vpo_mode) &&
                         (1 == vpo_mode)))
            {
                rc = true;
            }
            return rc;
        }
    };

#ifdef __HOSTBOOT_MODULE
    // In Hostboot this value cannot change, so cache it as a static.
    static bool is_vpo_mode = IsVpoFunctor::operate();
    return is_vpo_mode;
#else
    // On FSP, assumption is that the user could change this, so we cannot
    // cache it as a static.  Read from the attribute directly.
    return IsVpoFunctor::operate();
#endif
};

/**
 * @brief Safely fetch the HUID of a Target
 */
uint32_t get_huid( const Target* i_target )
{
    uint32_t huid = 0;
    if( i_target == NULL )
    {
        huid = 0x0;
    }
    else if( i_target == MASTER_PROCESSOR_CHIP_TARGET_SENTINEL )
    {
        huid = 0xFFFFFFFF;
    }
    else
    {
        i_target->tryGetAttr<ATTR_HUID>(huid);
    }
    return huid;
}

/**
 * @brief set HWAS Changed flag to subscription mask
 *
 *   This will be used by the HCDB service - when the target has
 *   changed, this will get called to tell the appropriate services
 *   that the change has occurred.
 */
void update_hwas_changed_mask(Target * i_target)
{
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(
            i_target->getAttr<ATTR_HWAS_STATE_CHANGED_SUBSCRIPTION_MASK>());
}

/**
 * @brief set HWAS Changed flag to specific bits
 *
 *   This will be used by different services when the target needs processing.
 */
void update_hwas_changed_mask(Target * i_target, const uint64_t i_bits)
{
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(
            i_target->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>() |
            (i_target->getAttr<ATTR_HWAS_STATE_CHANGED_SUBSCRIPTION_MASK>() &
                i_bits));
}

/**
 * @brief clear bit in HWAS Changed Mask
 *
 *   This will be used by the appropriate services when they have handled
 *   the change flag for this target.
 */
void clear_hwas_changed_bit(Target * i_target, const HWAS_CHANGED_BIT i_bit)
{
    ATTR_HWAS_STATE_CHANGED_FLAG_type hwasChangedState =
        i_target->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();
    hwasChangedState &= ~i_bit;
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(hwasChangedState);
}

/**
 * @brief   Checks if we are loading a PHYP payload
 */
bool is_phyp_load( ATTR_PAYLOAD_KIND_type* o_type )
{
    Target* sys = NULL;
    targetService().getTopLevelTarget( sys );
    assert(sys != NULL);

    // get the current payload kind
    TARGETING::PAYLOAD_KIND payload_kind = sys->getAttr<ATTR_PAYLOAD_KIND>();

    if( o_type )
    {
        *o_type = payload_kind;
    }

    //If in AVP mode default to false
    bool is_phyp = false;
    if(!is_avp_load())
    {
        is_phyp = (PAYLOAD_KIND_PHYP == payload_kind);
    }
    return is_phyp;
 }

/**
 * @brief  Utility function to determine if Sapphire is the payload
 *
 * @description  If the payload kind is Sapphire returns true.  Does
 *    not matter if it is Sapphire with FSP or standalone
 *
 * @return bool  True when loadding sapphire
 */
bool is_sapphire_load(void)
{
    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );
    assert(sys != NULL);
    bool is_sapphire = false;

    //If in AVP mode default to false
    if(!is_avp_load())
    {
        is_sapphire = (PAYLOAD_KIND_SAPPHIRE ==
                       sys->getAttr<TARGETING::ATTR_PAYLOAD_KIND>());
    }
    return is_sapphire;
}

/**
 * @brief  Utility function to determine if an AVP is the payload
 *         Note the actual payload could be something else -- this
 *         is based solely on MFG flags
 *
 * @description  If MFG AVP mode flags are set then returns true
 *      Does not matter what the actual payload is
 *
 * @return bool  True when in AVP mode
 */
bool is_avp_load(void)
{
    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );
    assert(sys != NULL);

    TARGETING::ATTR_MNFG_FLAGS_type mnfg_flags =
      sys->getAttr<TARGETING::ATTR_MNFG_FLAGS>();
    return ((mnfg_flags & TARGETING::MNFG_FLAG_AVP_ENABLE)
       || (mnfg_flags & TARGETING::MNFG_FLAG_HDAT_AVP_ENABLE));
}

/**
 * @brief Utility function to obtain the highest known address in the system
 */
uint64_t get_top_mem_addr(void)
{
    uint64_t top_addr = 0;

    do
    {
        // Get all functional proc chip targets
        TARGETING::TargetHandleList l_cpuTargetList;
        TARGETING::getAllChips(l_cpuTargetList, TYPE_PROC);

        for ( size_t proc = 0; proc < l_cpuTargetList.size(); proc++ )
        {
            TARGETING::Target * l_pProc = l_cpuTargetList[proc];

            //Not checking success here as fail results in no change to
            // top_addr
            uint64_t l_mem_bases[8] = {0,};
            uint64_t l_mem_sizes[8] = {0,};
            l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_BASES>(l_mem_bases);
            l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_SIZES>(l_mem_sizes);

            for (size_t i=0; i< 8; i++)
            {
                if(l_mem_sizes[i]) //non zero means that there is memory present
                {
                    top_addr = std::max(top_addr,
                                        l_mem_bases[i] + l_mem_sizes[i]);
                }
            }
        }
    }while(0);

    return top_addr;
}

/**
 * @brief Utility function to obtain the lowest known address in the system
 */
uint64_t get_bottom_mem_addr(void)
{
    uint64_t bottom_addr = UINT64_MAX;

    do
    {
        // Get all functional proc chip targets
        TARGETING::TargetHandleList l_cpuTargetList;
        TARGETING::getAllChips(l_cpuTargetList, TYPE_PROC);

        for ( size_t proc = 0; proc < l_cpuTargetList.size(); proc++ )
        {
            TARGETING::Target * l_pProc = l_cpuTargetList[proc];

            uint64_t l_mem_bases[8] = {};
            uint64_t l_mem_sizes[8] = {};
            TARG_ASSERT(
               l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_BASES>(l_mem_bases),
               "Unable to get ATTR_PROC_MEM_BASES attribute");

            TARG_ASSERT(
               l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_SIZES>(l_mem_sizes),
               "Unable to get ATTR_PROC_MEM_SIZES attribute");

            for (size_t i=0; i< 8; i++)
            {
                if(l_mem_sizes[i]) //non zero means that there is memory present
                {
                    bottom_addr = std::min(bottom_addr, l_mem_bases[i]);
                }
            }
        }
    }while(0);

    // There's no reason the lowest address should be the largest
    // 64 bit value
    TARG_ASSERT(
        bottom_addr < UINT64_MAX,
        "Lowest address is maximum 64-bit value");

    return bottom_addr;
}

bool orderByNodeAndPosition(  Target* i_firstProc,
                              Target* i_secondProc)
{
    uint8_t nodeId0 = i_firstProc->getAttr<ATTR_FABRIC_NODE_ID>();
    uint8_t nodeId1 = i_secondProc->getAttr<ATTR_FABRIC_NODE_ID>();
    uint8_t fabpos0 = i_firstProc->getAttr<ATTR_FABRIC_CHIP_ID>();
    uint8_t fabpos1 = i_secondProc->getAttr<ATTR_FABRIC_CHIP_ID>();

    if (nodeId0 == nodeId1)
    {
        return fabpos0 < fabpos1;
    }
    return nodeId0 < nodeId1;
}

}
<commit_msg>Improve error message for no memory situation<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/targeting/common/util.C $                             */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2015                        */
/* [+] 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                                                     */
/**
 *  @file targeting/common/util.C
 *
 *  @brief Provides miscellaneous utility functions to targeting, including
 *     a check for whether system is in simulation or not.
 */

//******************************************************************************
// Includes
//******************************************************************************
#include <stdint.h>
#include <targeting/common/attributes.H>
#include <targeting/common/targetservice.H>
#include <targeting/common/utilFilter.H>

namespace TARGETING
{

/**
 * @brief Checks to see if we are running in a hardware simulation
 *    environment, i.e. VPO/VBU  (not Simics)
 */
bool is_vpo( void )
{
    struct IsVpoFunctor
    {
        static bool operate()
        {
            bool rc = false;

            Target* sys = NULL;
            targetService().getTopLevelTarget(sys);

            uint8_t vpo_mode = 0;
            if (unlikely(sys &&
                         sys->tryGetAttr<ATTR_IS_SIMULATION>(vpo_mode) &&
                         (1 == vpo_mode)))
            {
                rc = true;
            }
            return rc;
        }
    };

#ifdef __HOSTBOOT_MODULE
    // In Hostboot this value cannot change, so cache it as a static.
    static bool is_vpo_mode = IsVpoFunctor::operate();
    return is_vpo_mode;
#else
    // On FSP, assumption is that the user could change this, so we cannot
    // cache it as a static.  Read from the attribute directly.
    return IsVpoFunctor::operate();
#endif
};

/**
 * @brief Safely fetch the HUID of a Target
 */
uint32_t get_huid( const Target* i_target )
{
    uint32_t huid = 0;
    if( i_target == NULL )
    {
        huid = 0x0;
    }
    else if( i_target == MASTER_PROCESSOR_CHIP_TARGET_SENTINEL )
    {
        huid = 0xFFFFFFFF;
    }
    else
    {
        i_target->tryGetAttr<ATTR_HUID>(huid);
    }
    return huid;
}

/**
 * @brief set HWAS Changed flag to subscription mask
 *
 *   This will be used by the HCDB service - when the target has
 *   changed, this will get called to tell the appropriate services
 *   that the change has occurred.
 */
void update_hwas_changed_mask(Target * i_target)
{
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(
            i_target->getAttr<ATTR_HWAS_STATE_CHANGED_SUBSCRIPTION_MASK>());
}

/**
 * @brief set HWAS Changed flag to specific bits
 *
 *   This will be used by different services when the target needs processing.
 */
void update_hwas_changed_mask(Target * i_target, const uint64_t i_bits)
{
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(
            i_target->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>() |
            (i_target->getAttr<ATTR_HWAS_STATE_CHANGED_SUBSCRIPTION_MASK>() &
                i_bits));
}

/**
 * @brief clear bit in HWAS Changed Mask
 *
 *   This will be used by the appropriate services when they have handled
 *   the change flag for this target.
 */
void clear_hwas_changed_bit(Target * i_target, const HWAS_CHANGED_BIT i_bit)
{
    ATTR_HWAS_STATE_CHANGED_FLAG_type hwasChangedState =
        i_target->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();
    hwasChangedState &= ~i_bit;
    i_target->setAttr<ATTR_HWAS_STATE_CHANGED_FLAG>(hwasChangedState);
}

/**
 * @brief   Checks if we are loading a PHYP payload
 */
bool is_phyp_load( ATTR_PAYLOAD_KIND_type* o_type )
{
    Target* sys = NULL;
    targetService().getTopLevelTarget( sys );
    assert(sys != NULL);

    // get the current payload kind
    TARGETING::PAYLOAD_KIND payload_kind = sys->getAttr<ATTR_PAYLOAD_KIND>();

    if( o_type )
    {
        *o_type = payload_kind;
    }

    //If in AVP mode default to false
    bool is_phyp = false;
    if(!is_avp_load())
    {
        is_phyp = (PAYLOAD_KIND_PHYP == payload_kind);
    }
    return is_phyp;
 }

/**
 * @brief  Utility function to determine if Sapphire is the payload
 *
 * @description  If the payload kind is Sapphire returns true.  Does
 *    not matter if it is Sapphire with FSP or standalone
 *
 * @return bool  True when loadding sapphire
 */
bool is_sapphire_load(void)
{
    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );
    assert(sys != NULL);
    bool is_sapphire = false;

    //If in AVP mode default to false
    if(!is_avp_load())
    {
        is_sapphire = (PAYLOAD_KIND_SAPPHIRE ==
                       sys->getAttr<TARGETING::ATTR_PAYLOAD_KIND>());
    }
    return is_sapphire;
}

/**
 * @brief  Utility function to determine if an AVP is the payload
 *         Note the actual payload could be something else -- this
 *         is based solely on MFG flags
 *
 * @description  If MFG AVP mode flags are set then returns true
 *      Does not matter what the actual payload is
 *
 * @return bool  True when in AVP mode
 */
bool is_avp_load(void)
{
    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );
    assert(sys != NULL);

    TARGETING::ATTR_MNFG_FLAGS_type mnfg_flags =
      sys->getAttr<TARGETING::ATTR_MNFG_FLAGS>();
    return ((mnfg_flags & TARGETING::MNFG_FLAG_AVP_ENABLE)
       || (mnfg_flags & TARGETING::MNFG_FLAG_HDAT_AVP_ENABLE));
}

/**
 * @brief Utility function to obtain the highest known address in the system
 */
uint64_t get_top_mem_addr(void)
{
    uint64_t top_addr = 0;

    do
    {
        // Get all functional proc chip targets
        TARGETING::TargetHandleList l_cpuTargetList;
        TARGETING::getAllChips(l_cpuTargetList, TYPE_PROC);

        for ( size_t proc = 0; proc < l_cpuTargetList.size(); proc++ )
        {
            TARGETING::Target * l_pProc = l_cpuTargetList[proc];

            //Not checking success here as fail results in no change to
            // top_addr
            uint64_t l_mem_bases[8] = {0,};
            uint64_t l_mem_sizes[8] = {0,};
            l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_BASES>(l_mem_bases);
            l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_SIZES>(l_mem_sizes);

            for (size_t i=0; i< 8; i++)
            {
                if(l_mem_sizes[i]) //non zero means that there is memory present
                {
                    top_addr = std::max(top_addr,
                                        l_mem_bases[i] + l_mem_sizes[i]);
                }
            }
        }
    }while(0);

    return top_addr;
}

/**
 * @brief Utility function to obtain the lowest known address in the system
 */
uint64_t get_bottom_mem_addr(void)
{
    uint64_t bottom_addr = UINT64_MAX;

    do
    {
        // Get all functional proc chip targets
        TARGETING::TargetHandleList l_cpuTargetList;
        TARGETING::getAllChips(l_cpuTargetList, TYPE_PROC);

        for ( size_t proc = 0; proc < l_cpuTargetList.size(); proc++ )
        {
            TARGETING::Target * l_pProc = l_cpuTargetList[proc];

            uint64_t l_mem_bases[8] = {};
            uint64_t l_mem_sizes[8] = {};
            TARG_ASSERT(
               l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_BASES>(l_mem_bases),
               "Unable to get ATTR_PROC_MEM_BASES attribute");

            TARG_ASSERT(
               l_pProc->tryGetAttr<TARGETING::ATTR_PROC_MEM_SIZES>(l_mem_sizes),
               "Unable to get ATTR_PROC_MEM_SIZES attribute");

            for (size_t i=0; i< 8; i++)
            {
                if(l_mem_sizes[i]) //non zero means that there is memory present
                {
                    bottom_addr = std::min(bottom_addr, l_mem_bases[i]);
                }
            }
        }
    }while(0);

    // There's no reason the lowest address should be the largest
    // 64 bit value
    TARG_ASSERT(
        bottom_addr < UINT64_MAX,
        "Lowest address is maximum 64-bit value, probably have no memory");

    return bottom_addr;
}

bool orderByNodeAndPosition(  Target* i_firstProc,
                              Target* i_secondProc)
{
    uint8_t nodeId0 = i_firstProc->getAttr<ATTR_FABRIC_NODE_ID>();
    uint8_t nodeId1 = i_secondProc->getAttr<ATTR_FABRIC_NODE_ID>();
    uint8_t fabpos0 = i_firstProc->getAttr<ATTR_FABRIC_CHIP_ID>();
    uint8_t fabpos1 = i_secondProc->getAttr<ATTR_FABRIC_CHIP_ID>();

    if (nodeId0 == nodeId1)
    {
        return fabpos0 < fabpos1;
    }
    return nodeId0 < nodeId1;
}

}
<|endoftext|>


<commit_before>//===- AsmStreamerTest.cpp - Triple unit tests ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

namespace {

// Helper class.
class StringAsmStreamer {
  std::string Str;
  raw_string_ostream OS;
  MCContext Context;
  MCStreamer *Streamer;

public:
  StringAsmStreamer() : OS(Str), Streamer(createAsmStreamer(Context, OS)) {}
  ~StringAsmStreamer() {
    delete Streamer;
  }

  MCContext &getContext() { return Context; }
  MCStreamer &getStreamer() { return *Streamer; }

  const std::string &getString() {
    Streamer->Finish();
    return Str;
  }
};

TEST(AsmStreamer, EmptyOutput) {
  StringAsmStreamer S;
  EXPECT_EQ("", S.getString());
}

TEST(AsmStreamer, Sections) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  EXPECT_EQ(".section foo\n", S.getString());
}

TEST(AsmStreamer, Values) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", S.getContext());
  MCSymbol *A = S.getContext().CreateSymbol("a");
  MCSymbol *B = S.getContext().CreateSymbol("b");
  S.getStreamer().SwitchSection(Sec0);
  S.getStreamer().EmitLabel(A);
  S.getStreamer().EmitLabel(B);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 1);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 2);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 4);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 8);
  EXPECT_EQ(".section foo\n\
a:\n\
b:\n\
.byte a - b + 10\n\
.short a - b + 10\n\
.long a - b + 10\n\
.quad a - b + 10\n", S.getString());
}

TEST(AsmStreamer, Align) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  S.getStreamer().EmitValueToAlignment(4);
  S.getStreamer().EmitValueToAlignment(4, /*Value=*/12, /*ValueSize=*/2);
  S.getStreamer().EmitValueToAlignment(8, /*Value=*/12, /*ValueSize=*/4,
                                       /*MaxBytesToEmit=*/24);
  EXPECT_EQ(".section foo\n\
.p2align 2, 0\n\
.p2alignw 2, 12\n\
.p2alignl 3, 12, 24\n", S.getString());
}

TEST(AsmStreamer, Org) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  MCSymbol *A = S.getContext().CreateSymbol("a");
  S.getStreamer().EmitLabel(A);
  S.getStreamer().EmitValueToOffset(MCValue::get(A, 0, 4), 32);
  EXPECT_EQ(".section foo\n\
a:\n\
.org a + 4, 32\n", S.getString());
}

}
<commit_msg>update for new api<commit_after>//===- AsmStreamerTest.cpp - Triple unit tests ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

namespace {

// Helper class.
class StringAsmStreamer {
  std::string Str;
  raw_string_ostream OS;
  MCContext Context;
  MCStreamer *Streamer;

public:
  StringAsmStreamer() : OS(Str), Streamer(createAsmStreamer(Context, OS)) {}
  ~StringAsmStreamer() {
    delete Streamer;
  }

  MCContext &getContext() { return Context; }
  MCStreamer &getStreamer() { return *Streamer; }

  const std::string &getString() {
    Streamer->Finish();
    return Str;
  }
};

TEST(AsmStreamer, EmptyOutput) {
  StringAsmStreamer S;
  EXPECT_EQ("", S.getString());
}

TEST(AsmStreamer, Sections) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", SectionKind(), S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  EXPECT_EQ(".section foo\n", S.getString());
}

TEST(AsmStreamer, Values) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", SectionKind(), S.getContext());
  MCSymbol *A = S.getContext().CreateSymbol("a");
  MCSymbol *B = S.getContext().CreateSymbol("b");
  S.getStreamer().SwitchSection(Sec0);
  S.getStreamer().EmitLabel(A);
  S.getStreamer().EmitLabel(B);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 1);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 2);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 4);
  S.getStreamer().EmitValue(MCValue::get(A, B, 10), 8);
  EXPECT_EQ(".section foo\n\
a:\n\
b:\n\
.byte a - b + 10\n\
.short a - b + 10\n\
.long a - b + 10\n\
.quad a - b + 10\n", S.getString());
}

TEST(AsmStreamer, Align) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", SectionKind(), S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  S.getStreamer().EmitValueToAlignment(4);
  S.getStreamer().EmitValueToAlignment(4, /*Value=*/12, /*ValueSize=*/2);
  S.getStreamer().EmitValueToAlignment(8, /*Value=*/12, /*ValueSize=*/4,
                                       /*MaxBytesToEmit=*/24);
  EXPECT_EQ(".section foo\n\
.p2align 2, 0\n\
.p2alignw 2, 12\n\
.p2alignl 3, 12, 24\n", S.getString());
}

TEST(AsmStreamer, Org) {
  StringAsmStreamer S;
  MCSection *Sec0 = MCSection::Create("foo", SectionKind(), S.getContext());
  S.getStreamer().SwitchSection(Sec0);
  MCSymbol *A = S.getContext().CreateSymbol("a");
  S.getStreamer().EmitLabel(A);
  S.getStreamer().EmitValueToOffset(MCValue::get(A, 0, 4), 32);
  EXPECT_EQ(".section foo\n\
a:\n\
.org a + 4, 32\n", S.getString());
}

}
<|endoftext|>


<commit_before>#include <functional>

#include "gtest/gtest.h"

#include "paxos/bootstrap.hpp"
#include "paxos/serialization.hpp"

TEST(BootstrapTest, testBootstrapListenerRegistersAction)
{
    static bool is_action_registered = false;

    class MockServer
    {
    public:
        MockServer(std::string address, short port)
        {
        }
        void RegisterAction(std::function<void(std::string content)> action)
        {
            is_action_registered = true;
        }
        void Start()
        {
        }
    };

    auto legislators = std::make_shared<paxos::ReplicaSet>();
    paxos::BootstrapListener<MockServer> listener(legislators, "my-address", 111);
    ASSERT_TRUE(is_action_registered);
}
<commit_msg>Add unittest coverage for send bootstrap<commit_after>#include <functional>

#include "gtest/gtest.h"

#include "paxos/bootstrap.hpp"
#include "paxos/serialization.hpp"

TEST(BootstrapTest, testBootstrapListenerRegistersAction)
{
    static bool is_action_registered = false;

    class MockServer
    {
    public:
        MockServer(std::string address, short port)
        {
        }
        void RegisterAction(std::function<void(std::string content)> action)
        {
            is_action_registered = true;
        }
        void Start()
        {
        }
    };

    auto legislators = std::make_shared<paxos::ReplicaSet>();
    paxos::BootstrapListener<MockServer> listener(legislators, "my-address", 111);
    ASSERT_TRUE(is_action_registered);
}

TEST(BootstrapTest, testSendBootstrapFirstFileSentIsEmptyReplicaSetFile)
{
    std::vector<paxos::BootstrapFile> sent_files;
    auto send_file = [&](paxos::BootstrapFile file)
    {
        sent_files.push_back(file);
    };
    paxos::SendBootstrap(
        "local_directorty",
        "remote_directory",
        std::vector<boost::filesystem::directory_entry>{},
        send_file);

    ASSERT_EQ("remote_directory/paxos.replicaset", sent_files[0].name);
    ASSERT_EQ("", sent_files[0].content);
}

TEST(BootstrapTest, testSendBootstrapPentultimateFileSentIsAcceptedDecreeFile)
{
    std::vector<paxos::BootstrapFile> sent_files;
    auto send_file = [&](paxos::BootstrapFile file)
    {
        sent_files.push_back(file);
    };
    paxos::SendBootstrap(
        "local_directorty",
        "remote_directory",
        std::vector<boost::filesystem::directory_entry>{},
        send_file);

    size_t index = sent_files.size() - 2;
    ASSERT_EQ("remote_directory/paxos.accepted_decree", sent_files[index].name);
}

TEST(BootstrapTest, testSendBootstrapLastFileSentIsActualReplicaSetFile)
{
    std::vector<paxos::BootstrapFile> sent_files;
    auto send_file = [&](paxos::BootstrapFile file)
    {
        sent_files.push_back(file);
    };
    paxos::SendBootstrap(
        "local_directorty",
        "remote_directory",
        std::vector<boost::filesystem::directory_entry>{},
        send_file);

    size_t index = sent_files.size() - 1;
    ASSERT_EQ("remote_directory/paxos.replicaset", sent_files[index].name);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * 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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.3  1999/11/12 20:36:51  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:31  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:22  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int   XMLUInt32;

// ---------------------------------------------------------------------------
//  Force on the XML4C debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XML4C_DEBUG
#endif

// ---------------------------------------------------------------------------
//  Provide some common string ops that are different/notavail on CSet
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
    if ((toUpper >= 'a') && (toUpper <= 'z'))
        return char(toUpper - 0x20);
    return toUpper;
}

inline char tolower(const char toLower)
{
    if ((toLower >= 'A') && (toLower <= 'Z'))
        return char(toLower + 0x20);
    return toLower;
}

int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the CSet C++ version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<commit_msg>XMLCh now defined to wchar_t<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * 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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.4  2000/01/12 19:11:49  aruna1
 * XMLCh now defined to wchar_t
 *
 * Revision 1.3  1999/11/12 20:36:51  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:31  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:22  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
//typedef unsigned short XMLCh;
typedef wchar_t XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int   XMLUInt32;

// ---------------------------------------------------------------------------
//  Force on the XML4C debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XML4C_DEBUG
#endif

// ---------------------------------------------------------------------------
//  Provide some common string ops that are different/notavail on CSet
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
    if ((toUpper >= 'a') && (toUpper <= 'z'))
        return char(toUpper - 0x20);
    return toUpper;
}

inline char tolower(const char toLower)
{
    if ((toLower >= 'A') && (toLower <= 'Z'))
        return char(toLower + 0x20);
    return toLower;
}

int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the CSet C++ version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/detail/swap.hpp>
#include <utility>
#include <memory>
#include <type_traits>

namespace agency
{
namespace detail
{

template<class Allocator>
class deleter
{
  public:
    using value_type = typename std::allocator_traits<Allocator>::value_type;

    using pointer = typename std::allocator_traits<Allocator>::pointer;

    __AGENCY_ANNOTATION
    deleter() = default;

    __AGENCY_ANNOTATION
    deleter(const deleter&) = default;

    template<class OtherAllocator,
             class = typename std::enable_if<
               std::is_convertible<
                 typename std::allocator_traits<OtherAllocator>::pointer,
                 pointer
               >::value
             >::type
            >
    __AGENCY_ANNOTATION
    deleter(const deleter<OtherAllocator>&) {}

    __AGENCY_ANNOTATION
    void operator()(pointer ptr) const
    {
      // destroy the object
      // XXX should use allocator_traits::destroy()
      ptr->~value_type();

      // deallocate
      Allocator alloc;
      alloc.deallocate(ptr, 1);
    }
};

template<class T>
using default_delete = deleter<std::allocator<T>>;

template<class T, class Deleter = default_delete<T>>
class unique_ptr
{
  public:
    using element_type = agency::detail::decay_t<T>;
    using pointer      = element_type*;
    using deleter_type = Deleter;

    __AGENCY_ANNOTATION
    unique_ptr(pointer ptr, const deleter_type& deleter = deleter_type())
      : ptr_(ptr),
        deleter_(deleter)
    {}

    __AGENCY_ANNOTATION
    unique_ptr() : unique_ptr(nullptr) {}

    __AGENCY_ANNOTATION
    unique_ptr(unique_ptr&& other)
      : ptr_(),
        deleter_(std::move(other.get_deleter()))
    {
      using agency::detail::swap;
      swap(ptr_, other.ptr_);
      swap(deleter_, other.deleter_);
    }

    template<class OtherT,
             class OtherDelete,
             class = typename std::enable_if<
               std::is_convertible<typename unique_ptr<OtherT,OtherDelete>::pointer,pointer>::value
             >::type
            >
    __AGENCY_ANNOTATION
    unique_ptr(unique_ptr<OtherT,OtherDelete>&& other)
      : ptr_(other.release()),
        deleter_(std::move(other.get_deleter()))
    {}

    __AGENCY_ANNOTATION
    ~unique_ptr()
    {
      reset(nullptr);
    }

    __AGENCY_ANNOTATION
    unique_ptr& operator=(unique_ptr&& other)
    {
      using agency::detail::swap;
      swap(ptr_,     other.ptr_);
      swap(deleter_, other.deleter_);
      return *this;
    }

    __AGENCY_ANNOTATION
    pointer get() const
    {
      return ptr_;
    }

    __AGENCY_ANNOTATION
    pointer release()
    {
      pointer result = nullptr;

      using agency::detail::swap;
      swap(ptr_, result);

      return result;
    }

    __AGENCY_ANNOTATION
    void reset(pointer ptr = pointer())
    {
      pointer old_ptr = ptr_;
      ptr_ = ptr;

      if(old_ptr != nullptr)
      {
        get_deleter()(old_ptr);
      }
    }

    __AGENCY_ANNOTATION
    deleter_type& get_deleter()
    {
      return deleter_;
    }

    __AGENCY_ANNOTATION
    const deleter_type& get_deleter() const
    {
      return deleter_;
    }

    __AGENCY_ANNOTATION
    const T& operator*() const
    {
      return *ptr_;
    }

    __AGENCY_ANNOTATION
    T& operator*()
    {
      return *ptr_;
    }

    __AGENCY_ANNOTATION
    operator bool () const
    {
      return get();
    }

    __AGENCY_ANNOTATION
    void swap(unique_ptr& other)
    {
      using agency::detail::swap;
      swap(ptr_, other.ptr_);
      swap(deleter_, other.deleter_);
    }

  private:
    T* ptr_;
    deleter_type deleter_;
};

template<class T, class Alloc, class... Args>
__AGENCY_ANNOTATION
unique_ptr<T,deleter<Alloc>> allocate_unique(const Alloc& alloc, Args&&... args)
{
  Alloc alloc_copy = alloc;

  unique_ptr<T,deleter<Alloc>> result(alloc_copy.allocate(1), deleter<Alloc>());

  // XXX should use allocator_traits::construct()
  alloc_copy.template construct<T>(result.get(), std::forward<Args>(args)...);

  return std::move(result);
}

} // end detail
} // end agency

<commit_msg>Avoid calling swap via ADL in unique_ptr because it is ambiguous<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/detail/swap.hpp>
#include <utility>
#include <memory>
#include <type_traits>

namespace agency
{
namespace detail
{

template<class Allocator>
class deleter
{
  public:
    using value_type = typename std::allocator_traits<Allocator>::value_type;

    using pointer = typename std::allocator_traits<Allocator>::pointer;

    __AGENCY_ANNOTATION
    deleter() = default;

    __AGENCY_ANNOTATION
    deleter(const deleter&) = default;

    template<class OtherAllocator,
             class = typename std::enable_if<
               std::is_convertible<
                 typename std::allocator_traits<OtherAllocator>::pointer,
                 pointer
               >::value
             >::type
            >
    __AGENCY_ANNOTATION
    deleter(const deleter<OtherAllocator>&) {}

    __AGENCY_ANNOTATION
    void operator()(pointer ptr) const
    {
      // destroy the object
      // XXX should use allocator_traits::destroy()
      ptr->~value_type();

      // deallocate
      Allocator alloc;
      alloc.deallocate(ptr, 1);
    }
};

template<class T>
using default_delete = deleter<std::allocator<T>>;

template<class T, class Deleter = default_delete<T>>
class unique_ptr
{
  public:
    using element_type = agency::detail::decay_t<T>;
    using pointer      = element_type*;
    using deleter_type = Deleter;

    __AGENCY_ANNOTATION
    unique_ptr(pointer ptr, const deleter_type& deleter = deleter_type())
      : ptr_(ptr),
        deleter_(deleter)
    {}

    __AGENCY_ANNOTATION
    unique_ptr() : unique_ptr(nullptr) {}

    __AGENCY_ANNOTATION
    unique_ptr(unique_ptr&& other)
      : ptr_(),
        deleter_(std::move(other.get_deleter()))
    {
      agency::detail::swap(ptr_, other.ptr_);
      agency::detail::swap(deleter_, other.deleter_);
    }

    template<class OtherT,
             class OtherDelete,
             class = typename std::enable_if<
               std::is_convertible<typename unique_ptr<OtherT,OtherDelete>::pointer,pointer>::value
             >::type
            >
    __AGENCY_ANNOTATION
    unique_ptr(unique_ptr<OtherT,OtherDelete>&& other)
      : ptr_(other.release()),
        deleter_(std::move(other.get_deleter()))
    {}

    __AGENCY_ANNOTATION
    ~unique_ptr()
    {
      reset(nullptr);
    }

    __AGENCY_ANNOTATION
    unique_ptr& operator=(unique_ptr&& other)
    {
      using agency::detail::swap;
      swap(ptr_,     other.ptr_);
      swap(deleter_, other.deleter_);
      return *this;
    }

    __AGENCY_ANNOTATION
    pointer get() const
    {
      return ptr_;
    }

    __AGENCY_ANNOTATION
    pointer release()
    {
      pointer result = nullptr;

      using agency::detail::swap;
      swap(ptr_, result);

      return result;
    }

    __AGENCY_ANNOTATION
    void reset(pointer ptr = pointer())
    {
      pointer old_ptr = ptr_;
      ptr_ = ptr;

      if(old_ptr != nullptr)
      {
        get_deleter()(old_ptr);
      }
    }

    __AGENCY_ANNOTATION
    deleter_type& get_deleter()
    {
      return deleter_;
    }

    __AGENCY_ANNOTATION
    const deleter_type& get_deleter() const
    {
      return deleter_;
    }

    __AGENCY_ANNOTATION
    const T& operator*() const
    {
      return *ptr_;
    }

    __AGENCY_ANNOTATION
    T& operator*()
    {
      return *ptr_;
    }

    __AGENCY_ANNOTATION
    operator bool () const
    {
      return get();
    }

    __AGENCY_ANNOTATION
    void swap(unique_ptr& other)
    {
      using agency::detail::swap;
      swap(ptr_, other.ptr_);
      swap(deleter_, other.deleter_);
    }

  private:
    T* ptr_;
    deleter_type deleter_;
};

template<class T, class Alloc, class... Args>
__AGENCY_ANNOTATION
unique_ptr<T,deleter<Alloc>> allocate_unique(const Alloc& alloc, Args&&... args)
{
  Alloc alloc_copy = alloc;

  unique_ptr<T,deleter<Alloc>> result(alloc_copy.allocate(1), deleter<Alloc>());

  // XXX should use allocator_traits::construct()
  alloc_copy.template construct<T>(result.get(), std::forward<Args>(args)...);

  return std::move(result);
}

} // end detail
} // end agency

<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright 2009-2013 Jörg Müller
 *
 * 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.
 ******************************************************************************/

#include "PyAPI.h"
#include "PySound.h"
#include "PyHandle.h"
#include "PyDevice.h"
#include "PySequenceEntry.h"
#include "PySequence.h"

#include "respec/Specification.h"
#include "devices/IHandle.h"
#include "devices/I3DDevice.h"
#include "plugin/PluginManager.h"
#include "ISound.h"

#include <memory>

#include <structmember.h>

using namespace aud;

// ====================================================================

#define PY_MODULE_ADD_CONSTANT(module, name) PyModule_AddIntConstant(module, #name, name)

// ====================================================================

extern PyObject* AUDError;
PyObject* AUDError = nullptr;

// ====================================================================

PyDoc_STRVAR(M_aud_doc,
			 "This module provides access to the audaspace audio library.");

static struct PyModuleDef audmodule = {
	PyModuleDef_HEAD_INIT,
	"aud",     /* name of module */
	M_aud_doc, /* module documentation */
	-1,        /* size of per-interpreter state of the module,
				  or -1 if the module keeps state in global variables. */
   nullptr, nullptr, nullptr, nullptr, nullptr
};

PyMODINIT_FUNC
PyInit_aud()
{
	PyObject* module;

	PluginManager::loadPlugins();

	if(!initializeSound())
		return nullptr;

	if(!initializeDevice())
		return nullptr;

	if(!initializeHandle())
		return nullptr;

	if(!initializeSequenceEntry())
		return nullptr;

	if(!initializeSequence())
		return nullptr;

	module = PyModule_Create(&audmodule);
	if(module == nullptr)
		return nullptr;

	addSoundToModule(module);
	addHandleToModule(module);
	addDeviceToModule(module);
	addSequenceEntryToModule(module);
	addSequenceToModule(module);

	AUDError = PyErr_NewException("aud.error", nullptr, nullptr);
	Py_INCREF(AUDError);
	PyModule_AddObject(module, "error", AUDError);

	// format constants
	PY_MODULE_ADD_CONSTANT(module, FORMAT_FLOAT32);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_FLOAT64);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_INVALID);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S16);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S24);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S32);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_U8);
	// status constants
	PY_MODULE_ADD_CONSTANT(module, STATUS_INVALID);
	PY_MODULE_ADD_CONSTANT(module, STATUS_PAUSED);
	PY_MODULE_ADD_CONSTANT(module, STATUS_PLAYING);
	PY_MODULE_ADD_CONSTANT(module, STATUS_STOPPED);
	// distance model constants
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_EXPONENT);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_EXPONENT_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVERSE);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVERSE_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_LINEAR);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_LINEAR_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVALID);

	return module;
}

PyObject* AUD_getPythonSound(void* sound)
{
	if(sound)
	{
		Sound* object = (Sound*) Sound_empty();
		if(object)
		{
			object->sound = new std::shared_ptr<ISound>(*reinterpret_cast<std::shared_ptr<ISound>*>(sound));
			return (PyObject *) object;
		}
	}

	return nullptr;
}

void* AUD_getSoundFromPython(PyObject* object)
{
	Sound* sound = checkSound(object);

	if(!sound)
		return nullptr;

	return new std::shared_ptr<ISound>(*reinterpret_cast<std::shared_ptr<ISound>*>(sound->sound));
}
<commit_msg>Python API: Adding new constants/enums.<commit_after>/*******************************************************************************
 * Copyright 2009-2013 Jörg Müller
 *
 * 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.
 ******************************************************************************/

#include "PyAPI.h"
#include "PySound.h"
#include "PyHandle.h"
#include "PyDevice.h"
#include "PySequenceEntry.h"
#include "PySequence.h"

#include "respec/Specification.h"
#include "devices/IHandle.h"
#include "devices/I3DDevice.h"
#include "file/IWriter.h"
#include "plugin/PluginManager.h"
#include "sequence/AnimateableProperty.h"
#include "ISound.h"

#include <memory>

#include <structmember.h>

using namespace aud;

// ====================================================================

#define PY_MODULE_ADD_CONSTANT(module, name) PyModule_AddIntConstant(module, #name, name)

// ====================================================================

extern PyObject* AUDError;
PyObject* AUDError = nullptr;

// ====================================================================

PyDoc_STRVAR(M_aud_doc,
			 "This module provides access to the audaspace audio library.");

static struct PyModuleDef audmodule = {
	PyModuleDef_HEAD_INIT,
	"aud",     /* name of module */
	M_aud_doc, /* module documentation */
	-1,        /* size of per-interpreter state of the module,
				  or -1 if the module keeps state in global variables. */
   nullptr, nullptr, nullptr, nullptr, nullptr
};

PyMODINIT_FUNC
PyInit_aud()
{
	PyObject* module;

	PluginManager::loadPlugins();

	if(!initializeSound())
		return nullptr;

	if(!initializeDevice())
		return nullptr;

	if(!initializeHandle())
		return nullptr;

	if(!initializeSequenceEntry())
		return nullptr;

	if(!initializeSequence())
		return nullptr;

	module = PyModule_Create(&audmodule);
	if(module == nullptr)
		return nullptr;

	addSoundToModule(module);
	addHandleToModule(module);
	addDeviceToModule(module);
	addSequenceEntryToModule(module);
	addSequenceToModule(module);

	AUDError = PyErr_NewException("aud.error", nullptr, nullptr);
	Py_INCREF(AUDError);
	PyModule_AddObject(module, "error", AUDError);

	// animatable property type constants
	PY_MODULE_ADD_CONSTANT(module, AP_VOLUME);
	PY_MODULE_ADD_CONSTANT(module, AP_PANNING);
	PY_MODULE_ADD_CONSTANT(module, AP_PITCH);
	PY_MODULE_ADD_CONSTANT(module, AP_LOCATION);
	PY_MODULE_ADD_CONSTANT(module, AP_ORIENTATION);
	// channels constants
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_INVALID);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_MONO);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_STEREO);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_STEREO_LFE);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_SURROUND4);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_SURROUND5);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_SURROUND51);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_SURROUND61);
	PY_MODULE_ADD_CONSTANT(module, CHANNELS_SURROUND71);
	// codec constants
	PY_MODULE_ADD_CONSTANT(module, CODEC_INVALID);
	PY_MODULE_ADD_CONSTANT(module, CODEC_AAC);
	PY_MODULE_ADD_CONSTANT(module, CODEC_AC3);
	PY_MODULE_ADD_CONSTANT(module, CODEC_FLAC);
	PY_MODULE_ADD_CONSTANT(module, CODEC_MP2);
	PY_MODULE_ADD_CONSTANT(module, CODEC_MP3);
	PY_MODULE_ADD_CONSTANT(module, CODEC_PCM);
	PY_MODULE_ADD_CONSTANT(module, CODEC_VORBIS);
	PY_MODULE_ADD_CONSTANT(module, CODEC_OPUS);
	// container constants
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_INVALID);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_AC3);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_FLAC);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_MATROSKA);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_MP2);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_MP3);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_OGG);
	PY_MODULE_ADD_CONSTANT(module, CONTAINER_WAV);
	// distance model constants
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_EXPONENT);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_EXPONENT_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVERSE);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVERSE_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_LINEAR);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_LINEAR_CLAMPED);
	PY_MODULE_ADD_CONSTANT(module, DISTANCE_MODEL_INVALID);
	// format constants
	PY_MODULE_ADD_CONSTANT(module, FORMAT_INVALID);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_FLOAT32);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_FLOAT64);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_INVALID);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S16);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S24);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_S32);
	PY_MODULE_ADD_CONSTANT(module, FORMAT_U8);
	// rate constants
	PY_MODULE_ADD_CONSTANT(module, RATE_INVALID);
	PY_MODULE_ADD_CONSTANT(module, RATE_8000);
	PY_MODULE_ADD_CONSTANT(module, RATE_16000);
	PY_MODULE_ADD_CONSTANT(module, RATE_11025);
	PY_MODULE_ADD_CONSTANT(module, RATE_22050);
	PY_MODULE_ADD_CONSTANT(module, RATE_32000);
	PY_MODULE_ADD_CONSTANT(module, RATE_44100);
	PY_MODULE_ADD_CONSTANT(module, RATE_48000);
	PY_MODULE_ADD_CONSTANT(module, RATE_88200);
	PY_MODULE_ADD_CONSTANT(module, RATE_96000);
	PY_MODULE_ADD_CONSTANT(module, RATE_192000);
	// status constants
	PY_MODULE_ADD_CONSTANT(module, STATUS_INVALID);
	PY_MODULE_ADD_CONSTANT(module, STATUS_PAUSED);
	PY_MODULE_ADD_CONSTANT(module, STATUS_PLAYING);
	PY_MODULE_ADD_CONSTANT(module, STATUS_STOPPED);

	return module;
}

PyObject* AUD_getPythonSound(void* sound)
{
	if(sound)
	{
		Sound* object = (Sound*) Sound_empty();
		if(object)
		{
			object->sound = new std::shared_ptr<ISound>(*reinterpret_cast<std::shared_ptr<ISound>*>(sound));
			return (PyObject *) object;
		}
	}

	return nullptr;
}

void* AUD_getSoundFromPython(PyObject* object)
{
	Sound* sound = checkSound(object);

	if(!sound)
		return nullptr;

	return new std::shared_ptr<ISound>(*reinterpret_cast<std::shared_ptr<ISound>*>(sound->sound));
}
<|endoftext|>