<commit_before>/*
 *   Copyright (c) 2012 - 2016 Kulykov Oleh <info@resident.name>
 *
 *   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 "../include/REMutex.h"

#if defined(HAVE_RECORE_CONFIG_H)
#include "recore_config.h"
#endif

#if defined(RE_HAVE_ASSERT_H)
#include <assert.h>
#endif

#if !defined(__RE_HAVE_THREADS__) && defined(__RE_OS_WINDOWS__)
#include <Windows.h>
#define __RE_THREADING_WINDOWS__ 1
#define __RE_HAVE_THREADS__ 1
#endif

#if !defined(__RE_HAVE_THREADS__) && defined(RE_HAVE_PTHREAD_H)
#include <pthread.h>
#define __RE_THREADING_PTHREAD__ 1
#define __RE_HAVE_THREADS__ 1
#endif

bool REMutex::lock() const
{
#if defined(__RE_THREADING_PTHREAD__)
	if (_m)
	{
		pthread_mutex_t * m = const_cast<pthread_mutex_t *>(static_cast<const pthread_mutex_t *>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = (pthread_mutex_lock(m) == 0);
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#elif defined(__RE_THREADING_WINDOWS__)
	if (_m)
	{
		LPCRITICAL_SECTION m = const_cast<LPCRITICAL_SECTION>(static_cast<const LPCRITICAL_SECTION>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = EnterCriticalSection(m) ? true : false;
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#else
	return false;
#endif
}

bool REMutex::unlock() const
{
#if defined(__RE_THREADING_PTHREAD__)
	if (_m)
	{
		pthread_mutex_t * m = const_cast<pthread_mutex_t *>(static_cast<const pthread_mutex_t *>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = (pthread_mutex_unlock(m) == 0);
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#elif defined(__RE_THREADING_WINDOWS__)
	if (_m)
	{
		LPCRITICAL_SECTION m = const_cast<LPCRITICAL_SECTION>(static_cast<const LPCRITICAL_SECTION>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		LeaveCriticalSection(m);
		return true;
	}
	return false;
#else
	return false;
#endif
}

#if defined(__RE_THREADING_PTHREAD__)
bool remutex_init_recursive_private(pthread_mutex_t * m)
{
	bool isInit = false;
	pthread_mutexattr_t attr;
	if (pthread_mutexattr_init(&attr) == 0)
	{
		if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0)
			isInit = (pthread_mutex_init(m, &attr) == 0);
		pthread_mutexattr_destroy(&attr);
	}
#if defined(RE_HAVE_ASSERT_H)
	assert(isInit);
#endif
	return isInit;
}
#endif

REMutex::REMutex() : _m(NULL)
{
#if defined(__RE_THREADING_PTHREAD__)
	void * m = malloc(sizeof(pthread_mutex_t));
#if defined(RE_HAVE_ASSERT_H)
	assert(m);
#endif
	if (m)
	{
		if (remutex_init_recursive_private((pthread_mutex_t *)m)) _m = m;
		else free(m);
	}
#elif defined(__RE_THREADING_WINDOWS__)
	_m = malloc(sizeof(CRITICAL_SECTION));
#if defined(RE_HAVE_ASSERT_H)
	assert(_m);
#endif
	if (_m) InitializeCriticalSection(static_cast<LPCRITICAL_SECTION>(_m));
#endif
}

REMutex::~REMutex()
{
	if (_m)
	{
#if defined(__RE_THREADING_PTHREAD__)
		pthread_mutex_destroy((pthread_mutex_t *)_m);
#elif defined(__RE_THREADING_WINDOWS__)
		DeleteCriticalSection(static_cast<LPCRITICAL_SECTION>(_m));
#endif
		free(_m);
	}
}

<commit_msg>Move back to trylock<commit_after>/*
 *   Copyright (c) 2012 - 2016 Kulykov Oleh <info@resident.name>
 *
 *   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 "../include/REMutex.h"

#if defined(HAVE_RECORE_CONFIG_H)
#include "recore_config.h"
#endif

#if defined(RE_HAVE_ASSERT_H)
#include <assert.h>
#endif

#if !defined(__RE_HAVE_THREADS__) && defined(__RE_OS_WINDOWS__)
#include <Windows.h>
#define __RE_THREADING_WINDOWS__ 1
#define __RE_HAVE_THREADS__ 1
#endif

#if !defined(__RE_HAVE_THREADS__) && defined(RE_HAVE_PTHREAD_H)
#include <pthread.h>
#define __RE_THREADING_PTHREAD__ 1
#define __RE_HAVE_THREADS__ 1
#endif

bool REMutex::lock() const
{
#if defined(__RE_THREADING_PTHREAD__)
	if (_m)
	{
		pthread_mutex_t * m = const_cast<pthread_mutex_t *>(static_cast<const pthread_mutex_t *>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = (pthread_mutex_lock(m) == 0);
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#elif defined(__RE_THREADING_WINDOWS__)
	if (_m)
	{
		LPCRITICAL_SECTION m = const_cast<LPCRITICAL_SECTION>(static_cast<const LPCRITICAL_SECTION>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = TryEnterCriticalSection(m) ? true : false;
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#else
	return false;
#endif
}

bool REMutex::unlock() const
{
#if defined(__RE_THREADING_PTHREAD__)
	if (_m)
	{
		pthread_mutex_t * m = const_cast<pthread_mutex_t *>(static_cast<const pthread_mutex_t *>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		const bool r = (pthread_mutex_unlock(m) == 0);
#if defined(RE_HAVE_ASSERT_H)
		assert(r);
#endif
		return r;
	}
	return false;
#elif defined(__RE_THREADING_WINDOWS__)
	if (_m)
	{
		LPCRITICAL_SECTION m = const_cast<LPCRITICAL_SECTION>(static_cast<const LPCRITICAL_SECTION>(_m));
#if defined(RE_HAVE_ASSERT_H)
		assert(m);
#endif
		LeaveCriticalSection(m);
		return true;
	}
	return false;
#else
	return false;
#endif
}

#if defined(__RE_THREADING_PTHREAD__)
bool remutex_init_recursive_private(pthread_mutex_t * m)
{
	bool isInit = false;
	pthread_mutexattr_t attr;
	if (pthread_mutexattr_init(&attr) == 0)
	{
		if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0)
			isInit = (pthread_mutex_init(m, &attr) == 0);
		pthread_mutexattr_destroy(&attr);
	}
#if defined(RE_HAVE_ASSERT_H)
	assert(isInit);
#endif
	return isInit;
}
#endif

REMutex::REMutex() : _m(NULL)
{
#if defined(__RE_THREADING_PTHREAD__)
	void * m = malloc(sizeof(pthread_mutex_t));
#if defined(RE_HAVE_ASSERT_H)
	assert(m);
#endif
	if (m)
	{
		if (remutex_init_recursive_private((pthread_mutex_t *)m)) _m = m;
		else free(m);
	}
#elif defined(__RE_THREADING_WINDOWS__)
	_m = malloc(sizeof(CRITICAL_SECTION));
#if defined(RE_HAVE_ASSERT_H)
	assert(_m);
#endif
	if (_m) InitializeCriticalSection(static_cast<LPCRITICAL_SECTION>(_m));
#endif
}

REMutex::~REMutex()
{
	if (_m)
	{
#if defined(__RE_THREADING_PTHREAD__)
		pthread_mutex_destroy((pthread_mutex_t *)_m);
#elif defined(__RE_THREADING_WINDOWS__)
		DeleteCriticalSection(static_cast<LPCRITICAL_SECTION>(_m));
#endif
		free(_m);
	}
}

<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <new>
#include <thread>
#include <mutex>
#include <memory>

template <typename T>
class stack
{
public:
	stack() noexcept;
	~stack() noexcept;
	stack(stack<T> const&)/*strong*/;
	stack& operator=(stack<T> const&)/*strong*/;
	size_t count()const noexcept;
	void push(T const&)/*strong*/;
	auto pop() -> std::shared_ptr<T>/*strong*/;
	bool empty()const noexcept;
private:
	void swap(stack<T>&)noexcept;
	mutable std::mutex mutex_;
	T * array_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
	delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
	std::lock_guard<std::mutex> lock(other.mutex_);
	T new_array = new T [other.array_size_];
	array_size_ = other.array_size_;
	count_ = other.count_;
	array_ = new_array;
	try
	{
		std::copy(other.array_, other.array_ + count_, array_);
	}
	catch( ... )
	{
		std::cerr << "ERROR" << std::endl;
		delete[] array_;
	}
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
	if (&other != this)
		stack(other).swap(*this);
	return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
	std::lock_guard<std::mutex> lock(mutex_);
	return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
	std::lock_guard<std::mutex> lock(mutex_);
	if (empty())
	{
		array_size_ = 1;
		array_ = new T[array_size_]();
	}
	else if (array_size_ == count_)
	{
		try
		{
		        array_size_ *= 2;
		        T * new_array = new T[array_size_]();
		        std::copy(array_, array_ + count_, new_array);
		        delete[] array_;
		        array_ = new_array;
		}
		catch(std::bad_alloc)
	        {
		        std::cerr << "bad_alloc caught" << std::endl;
			throw;
	        }
	}
	array_[count_] = value;
	count_++;
}
template <typename T>
auto stack<T>::pop() -> std::shared_ptr<T>
{
	std::lock_guard<std::mutex> lock(mutex_);
	auto top = std::make_shared<T>(array_[count_ - 1]);
	if (empty())
		throw std::logic_error("Stack is empty");
	--count_;
	return top;
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
	std::lock(mutex_, other.mutex_);
	std::swap(array_, other.array_);
	std::swap(array_size_, other.array_size_);
	std::swap(count_, other.count_);
	mutex_.unlock();
	other.mutex_.unlock();
}
template <typename T>
bool stack<T>::empty()const noexcept
{
	std::lock_guard<std::mutex> lock(mutex_);
	return (count_ == 0);
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
#include <algorithm>
#include <new>
#include <thread>
#include <mutex>
#include <memory>

template <typename T>
class stack
{
public:
	stack() noexcept;
	~stack() noexcept;
	stack(stack<T> const&)/*strong*/;
	stack& operator=(stack<T> const&)/*strong*/;
	size_t count()const noexcept;
	void push(T const&)/*strong*/;
	auto pop() -> std::shared_ptr<T>/*strong*/;
	bool empty()const noexcept;
private:
	void swap(stack<T>&)noexcept;
	mutable std::mutex mutex_;
	T * array_;
	size_t array_size_;
	size_t count_;
};

template <typename T>
stack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
	delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
	std::lock_guard<std::mutex> lock(other.mutex_);
	T new_array = new T [other.array_size_];
	array_size_ = other.array_size_;
	count_ = other.count_;
	array_ = new_array;
	try
	{
		std::copy(other.array_, other.array_ + count_, array_);
	}
	catch( ... )
	{
		std::cerr << "ERROR" << std::endl;
		delete[] array_;
		throw;
	}
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
	if (&other != this)
		stack(other).swap(*this);
	return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
	std::lock_guard<std::mutex> lock(mutex_);
	return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
	std::lock_guard<std::mutex> lock(mutex_);
	if (empty())
	{
		array_size_ = 1;
		array_ = new T[array_size_]();
	}
	else if (array_size_ == count_)
	{
		try
		{
		        array_size_ *= 2;
		        T * new_array = new T[array_size_]();
		        std::copy(array_, array_ + count_, new_array);
		        delete[] array_;
		        array_ = new_array;
		}
		catch(std::bad_alloc)
	        {
		        std::cerr << "bad_alloc caught" << std::endl;
			throw;
	        }
	}
	array_[count_] = value;
	count_++;
}
template <typename T>
auto stack<T>::pop() -> std::shared_ptr<T>
{
	std::lock_guard<std::mutex> lock(mutex_);
	auto top = std::make_shared<T>(array_[count_ - 1]);
	if (empty())
		throw std::logic_error("Stack is empty");
	--count_;
	return top;
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
	std::lock(mutex_, other.mutex_);
	std::swap(array_, other.array_);
	std::swap(array_size_, other.array_size_);
	std::swap(count_, other.count_);
	mutex_.unlock();
	other.mutex_.unlock();
}
template <typename T>
bool stack<T>::empty()const noexcept
{
	std::lock_guard<std::mutex> lock(mutex_);
	return (count_ == 0);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/mouse_cursor_monitor.h"

#include "gtest/gtest.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/mouse_cursor.h"
#include "webrtc/modules/desktop_capture/window_capturer.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

class MouseCursorMonitorTest : public testing::Test,
                               public MouseCursorMonitor::Callback {
 public:
  MouseCursorMonitorTest()
      : position_received_(false) {
  }

  // MouseCursorMonitor::Callback interface
  virtual void OnMouseCursor(MouseCursor* cursor_image) OVERRIDE {
    cursor_image_.reset(cursor_image);
  }

  virtual void OnMouseCursorPosition(MouseCursorMonitor::CursorState state,
                                     const DesktopVector& position) OVERRIDE {
    state_ = state;
    position_ = position;
    position_received_ = true;
  }

 protected:
  scoped_ptr<MouseCursor> cursor_image_;
  MouseCursorMonitor::CursorState state_;
  DesktopVector position_;
  bool position_received_;
};

// TODO(sergeyu): On Mac we need to initialize NSApplication before running the
// tests. Figure out how to do that without breaking other tests in
// modules_unittests and enable these tests on Mac.
// https://code.google.com/p/webrtc/issues/detail?id=2532
//
// Disabled on Windows due to flake, see:
// https://code.google.com/p/webrtc/issues/detail?id=3408
#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
#define MAYBE(x) x
#else
#define MAYBE(x) DISABLED_##x
#endif

// Disabled due to flake, see:
// https://code.google.com/p/webrtc/issues/detail?id=3245
TEST_F(MouseCursorMonitorTest, MAYBE(DISABLED_ON_LINUX(FromScreen))) {
  scoped_ptr<MouseCursorMonitor> capturer(MouseCursorMonitor::CreateForScreen(
      DesktopCaptureOptions::CreateDefault(), webrtc::kFullDesktopScreenId));
  assert(capturer.get());
  capturer->Init(this, MouseCursorMonitor::SHAPE_AND_POSITION);
  capturer->Capture();

  EXPECT_TRUE(cursor_image_.get());
  EXPECT_GE(cursor_image_->hotspot().x(), 0);
  EXPECT_LE(cursor_image_->hotspot().x(),
            cursor_image_->image()->size().width());
  EXPECT_GE(cursor_image_->hotspot().y(), 0);
  EXPECT_LE(cursor_image_->hotspot().y(),
            cursor_image_->image()->size().height());

  EXPECT_TRUE(position_received_);
  EXPECT_EQ(MouseCursorMonitor::INSIDE, state_);
}

TEST_F(MouseCursorMonitorTest, MAYBE(FromWindow)) {
  DesktopCaptureOptions options = DesktopCaptureOptions::CreateDefault();

  // First get list of windows.
  scoped_ptr<WindowCapturer> window_capturer(WindowCapturer::Create(options));

  // If window capturing is not supported then skip this test.
  if (!window_capturer.get())
    return;

  WindowCapturer::WindowList windows;
  EXPECT_TRUE(window_capturer->GetWindowList(&windows));

  // Iterate over all windows and try capturing mouse cursor for each of them.
  for (size_t i = 0; i < windows.size(); ++i) {
    cursor_image_.reset();
    position_received_ = false;

    scoped_ptr<MouseCursorMonitor> capturer(
        MouseCursorMonitor::CreateForWindow(
            DesktopCaptureOptions::CreateDefault(), windows[i].id));
    assert(capturer.get());

    capturer->Init(this, MouseCursorMonitor::SHAPE_AND_POSITION);
    capturer->Capture();

    EXPECT_TRUE(cursor_image_.get());
    EXPECT_TRUE(position_received_);
  }
}

// Make sure that OnMouseCursorPosition() is not called in the SHAPE_ONLY mode.
TEST_F(MouseCursorMonitorTest, MAYBE(ShapeOnly)) {
  scoped_ptr<MouseCursorMonitor> capturer(MouseCursorMonitor::CreateForScreen(
      DesktopCaptureOptions::CreateDefault(), webrtc::kFullDesktopScreenId));
  assert(capturer.get());
  capturer->Init(this, MouseCursorMonitor::SHAPE_ONLY);
  capturer->Capture();

  EXPECT_TRUE(cursor_image_.get());
  EXPECT_FALSE(position_received_);
}

}  // namespace webrtc
<commit_msg>Disable MouseCursorMonitorTest<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/mouse_cursor_monitor.h"

#include "gtest/gtest.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/mouse_cursor.h"
#include "webrtc/modules/desktop_capture/window_capturer.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

class MouseCursorMonitorTest : public testing::Test,
                               public MouseCursorMonitor::Callback {
 public:
  MouseCursorMonitorTest()
      : position_received_(false) {
  }

  // MouseCursorMonitor::Callback interface
  virtual void OnMouseCursor(MouseCursor* cursor_image) OVERRIDE {
    cursor_image_.reset(cursor_image);
  }

  virtual void OnMouseCursorPosition(MouseCursorMonitor::CursorState state,
                                     const DesktopVector& position) OVERRIDE {
    state_ = state;
    position_ = position;
    position_received_ = true;
  }

 protected:
  scoped_ptr<MouseCursor> cursor_image_;
  MouseCursorMonitor::CursorState state_;
  DesktopVector position_;
  bool position_received_;
};

// TODO(sergeyu): On Mac we need to initialize NSApplication before running the
// tests. Figure out how to do that without breaking other tests in
// modules_unittests and enable these tests on Mac.
// https://code.google.com/p/webrtc/issues/detail?id=2532
//
// Disabled on Windows due to flake, see:
// https://code.google.com/p/webrtc/issues/detail?id=3408
// Disabled on Linux due to flake, see:
// https://code.google.com/p/webrtc/issues/detail?id=3245
#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN) && !defined(WEBRTC_LINUX)
#define MAYBE(x) x
#else
#define MAYBE(x) DISABLED_##x
#endif

TEST_F(MouseCursorMonitorTest, MAYBE(FromScreen)) {
  scoped_ptr<MouseCursorMonitor> capturer(MouseCursorMonitor::CreateForScreen(
      DesktopCaptureOptions::CreateDefault(), webrtc::kFullDesktopScreenId));
  assert(capturer.get());
  capturer->Init(this, MouseCursorMonitor::SHAPE_AND_POSITION);
  capturer->Capture();

  EXPECT_TRUE(cursor_image_.get());
  EXPECT_GE(cursor_image_->hotspot().x(), 0);
  EXPECT_LE(cursor_image_->hotspot().x(),
            cursor_image_->image()->size().width());
  EXPECT_GE(cursor_image_->hotspot().y(), 0);
  EXPECT_LE(cursor_image_->hotspot().y(),
            cursor_image_->image()->size().height());

  EXPECT_TRUE(position_received_);
  EXPECT_EQ(MouseCursorMonitor::INSIDE, state_);
}

TEST_F(MouseCursorMonitorTest, MAYBE(FromWindow)) {
  DesktopCaptureOptions options = DesktopCaptureOptions::CreateDefault();

  // First get list of windows.
  scoped_ptr<WindowCapturer> window_capturer(WindowCapturer::Create(options));

  // If window capturing is not supported then skip this test.
  if (!window_capturer.get())
    return;

  WindowCapturer::WindowList windows;
  EXPECT_TRUE(window_capturer->GetWindowList(&windows));

  // Iterate over all windows and try capturing mouse cursor for each of them.
  for (size_t i = 0; i < windows.size(); ++i) {
    cursor_image_.reset();
    position_received_ = false;

    scoped_ptr<MouseCursorMonitor> capturer(
        MouseCursorMonitor::CreateForWindow(
            DesktopCaptureOptions::CreateDefault(), windows[i].id));
    assert(capturer.get());

    capturer->Init(this, MouseCursorMonitor::SHAPE_AND_POSITION);
    capturer->Capture();

    EXPECT_TRUE(cursor_image_.get());
    EXPECT_TRUE(position_received_);
  }
}

// Make sure that OnMouseCursorPosition() is not called in the SHAPE_ONLY mode.
TEST_F(MouseCursorMonitorTest, MAYBE(ShapeOnly)) {
  scoped_ptr<MouseCursorMonitor> capturer(MouseCursorMonitor::CreateForScreen(
      DesktopCaptureOptions::CreateDefault(), webrtc::kFullDesktopScreenId));
  assert(capturer.get());
  capturer->Init(this, MouseCursorMonitor::SHAPE_ONLY);
  capturer->Capture();

  EXPECT_TRUE(cursor_image_.get());
  EXPECT_FALSE(position_received_);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/**********************************************************************/
/* Sopyright 2014 RSF                                                 */
/*                                                                    */
/* 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/LISENSE-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 SONDITIONS OF ANY KIND,       */
/* either express or implied.                                         */
/* See the License for the specific language governing permissions    */
/* and limitations under the License.                                 */
/**********************************************************************/

#ifndef HPP_PARSER_SYNTAX_S_DEFINED
#define HPP_PARSER_SYNTAX_S_DEFINED

namespace parser
{
    struct ExprS
    {
        protected:
            enum class Sugar { numS, plusS, bminusS, multS, divS, ifS };
            const ExprS *l; const ExprS *r; const ExprS *x;

        public:
            const Sugar type;

        protected:
            ExprS(Sugar t,
                const ExprS *l = {},
                const ExprS *r = {},
                const ExprS *x = {}
            )
                : l{l}, r{r}, x{x}, type{t} {}

            virtual ~ExprS() {};

        friend class Desugar;
    };

    struct plusS : public ExprS
    {
        plusS(const ExprS& l, const ExprS& r)
            : ExprS{ExprS::Sugar::plusS, &l, &r} {}
    };

    struct bminusS : public ExprS
    {
        bminusS(const ExprS& l, const ExprS& r)
            : ExprS{ExprS::Sugar::bminusS, &l, &r} {}
    };

    struct multS : public ExprS
    {
        multS(const ExprS& l, const ExprS& r)
            : ExprS{ExprS::Sugar::multS, &l, &r} {}
    };

    struct divS : public ExprS
    {
        divS(const ExprS& l, const ExprS& r)
            : ExprS{ExprS::Sugar::divS, &l, &r} {}
    };

    struct ifS : public ExprS
    {
        ifS(const ExprS& cond, const ExprS& yes)
            : ExprS{ExprS::Sugar::ifS, &cond, &yes} {}
        ifS(const ExprS& cond, const ExprS& yes, const ExprS& no)
            : ExprS{ExprS::Sugar::ifS, &cond, &yes, &no} {}
    };

    class numS : public ExprS
    {
        private:
            long long n;

        public:
            numS(int n)
                : ExprS{ExprS::Sugar::numS}, n{n} {}
            numS(long long n)
                : ExprS{ExprS::Sugar::numS}, n{n} {}

            long long get() const { return this->n; }
    };
}

#endif
<commit_msg>Making destructor public and recursive (deleting a node deletes all subtree wich has this node as radix)<commit_after>/**********************************************************************/
/* Sopyright 2014 RSF                                                 */
/*                                                                    */
/* 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/LISENSE-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 SONDITIONS OF ANY KIND,       */
/* either express or implied.                                         */
/* See the License for the specific language governing permissions    */
/* and limitations under the License.                                 */
/**********************************************************************/

#ifndef HPP_PARSER_SYNTAX_S_DEFINED
#define HPP_PARSER_SYNTAX_S_DEFINED

namespace parser
{
    struct ExprS
    {
        protected:
            enum class Sugar {
                numS, plusS, bminusS, multS, divS, ifS,
                uminusS
            };
            const ExprS *l; const ExprS *r; const ExprS *x;

        public:
            const Sugar type;

            virtual ~ExprS()
            {
                if(l) delete l;
                if(r) delete r;
                if(x) delete x;
            }

        protected:
            ExprS(Sugar t,
                const ExprS *l = {},
                const ExprS *r = {},
                const ExprS *x = {}
            )
                : l{l}, r{r}, x{x}, type{t} {}

        friend class Desugar;
    };

    struct plusS : public ExprS
    {
        plusS(const ExprS *l, const ExprS *r)
            : ExprS{ExprS::Sugar::plusS, l, r} {}
    };

    struct bminusS : public ExprS
    {
        bminusS(const ExprS *l, const ExprS *r)
            : ExprS{ExprS::Sugar::bminusS, l, r} {}
    };

    struct multS : public ExprS
    {
        multS(const ExprS *l, const ExprS *r)
            : ExprS{ExprS::Sugar::multS, l, r} {}
    };

    struct divS : public ExprS
    {
        divS(const ExprS *l, const ExprS *r)
            : ExprS{ExprS::Sugar::divS, l, r} {}
    };

    struct ifS : public ExprS
    {
        ifS(const ExprS *cond, const ExprS *yes)
            : ExprS{ExprS::Sugar::ifS, cond, yes} {}
        ifS(const ExprS *cond, const ExprS *yes, const ExprS *no)
            : ExprS{ExprS::Sugar::ifS, cond, yes, no} {}
    };

    class numS : public ExprS
    {
        private:
            long long n;

        public:
            numS(int n)
                : ExprS{ExprS::Sugar::numS}, n{n} {}
            numS(long long n)
                : ExprS{ExprS::Sugar::numS}, n{n} {}

            long long get() const { return this->n; }
    };

    struct uminusS : public ExprS
    {
        uminusS(const ExprS *l)
            : ExprS{ExprS::Sugar::uminusS, l} {}
    };
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Immo Software
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o 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.
 *
 * o Neither the name of the copyright holder nor the names of its contributors may
 *   be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "card_manager.h"
#include "fsl_sd.h"
#include "fsl_sd_disk.h"
#include "fsl_sdmmc_common.h"

using namespace slab;

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

CardManager::CardManager()
:   _isCardPresent(false)
{
}

void CardManager::init()
{
    // Configure SD host.
    static const sdmmchost_detect_card_t cd = {
        .cdType = kSDMMCHOST_DetectCardByHostDATA3,
        .cdTimeOut_ms = (~0U),
        .cardInserted = nullptr,
        .cardRemoved = nullptr,
        };

    g_sd.host.base = SDHC;
    g_sd.host.sourceClock_Hz = CLOCK_GetFreq(kCLOCK_CoreSysClk);
    g_sd.usrParam.cd = &cd;

    SD_HostInit(&g_sd);
}

//!
bool CardManager::check_presence()
{
    if (_isCardPresent)
    {
        // Skip this check if a transfer is in progress so we don't interrupt it.
        // Read and write transfers continue automaticaly until a StopTransmission
        // command is sent. So sending a SendStatus command during a transfer can
        // cause the response to get mixed up.
        if (!SD_IsTransferring(&g_sd))
        {
            bool response = get_card_status();
            _isCardPresent = response;
        }
    }
    else
    {
        // Attempt to init SD.
        status_t status = SD_CardInit(&g_sd);
        if (status == kStatus_Success)
        {
            _isCardPresent = true;
        }
    }

    return _isCardPresent;
}

bool CardManager::get_card_status()
{
    SDMMCHOST_COMMAND command{0};
    SDMMCHOST_TRANSFER content{0};

    command.index = kSDMMC_SendStatus;
    command.argument = g_sd.relativeAddress << 16U;
    command.responseType = kCARD_ResponseTypeR1;
    command.responseErrorFlags = 0;

    content.command = &command;
    content.data = NULL;

    status_t status = g_sd.host.transfer(g_sd.host.base, &content);

    return (status == kStatus_Success);
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<commit_msg>Fix: some cards caused slews of card detect interrupts.<commit_after>/*
 * Copyright (c) 2017 Immo Software
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o 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.
 *
 * o Neither the name of the copyright holder nor the names of its contributors may
 *   be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "card_manager.h"
#include "fsl_sd.h"
#include "fsl_sd_disk.h"
#include "fsl_sdmmc_common.h"

using namespace slab;

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

CardManager::CardManager()
:   _isCardPresent(false)
{
}

void CardManager::init()
{
    // Configure SD host.
    // Setting card detect to gpio even though we're using command polling to
    // effectively disable the driver's card detect support, which is unreliable.
    static const sdmmchost_detect_card_t cd = {
        .cdType = kSDMMCHOST_DetectCardByGpioCD,
        .cdTimeOut_ms = (~0U),
        .cardInserted = nullptr,
        .cardRemoved = nullptr,
        };

    g_sd.host.base = SDHC;
    g_sd.host.sourceClock_Hz = CLOCK_GetFreq(kCLOCK_CoreSysClk);
    g_sd.usrParam.cd = &cd;

    SD_HostInit(&g_sd);
}

//!
bool CardManager::check_presence()
{
    if (_isCardPresent)
    {
        // Skip this check if a transfer is in progress so we don't interrupt it.
        // Read and write transfers continue automaticaly until a StopTransmission
        // command is sent. So sending a SendStatus command during a transfer can
        // cause the response to get mixed up.
        if (!SD_IsTransferring(&g_sd))
        {
            bool response = get_card_status();
            _isCardPresent = response;
        }
    }
    else
    {
        // Attempt to init SD.
        status_t status = SD_CardInit(&g_sd);
        if (status == kStatus_Success)
        {
            _isCardPresent = true;
        }
    }

    return _isCardPresent;
}

bool CardManager::get_card_status()
{
    SDMMCHOST_COMMAND command{0};
    SDMMCHOST_TRANSFER content{0};

    command.index = kSDMMC_SendStatus;
    command.argument = g_sd.relativeAddress << 16U;
    command.responseType = kCARD_ResponseTypeR1;
    command.responseErrorFlags = 0;

    content.command = &command;
    content.data = NULL;

    status_t status = g_sd.host.transfer(g_sd.host.base, &content);

    return (status == kStatus_Success);
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#pragma once

#ifndef WITHOUT_HSA_BACKEND

namespace roc {

//! Alignment restriciton for the pinned memory
const static size_t PinnedMemoryAlignment = 4 * Ki;

//! Specific defines for images for Dynamic Parallelism
const static uint DeviceQueueMaskSize = 32;

typedef uint HsaDeviceId;

struct AMDDeviceInfo {
  HsaDeviceId hsaDeviceId_;    //!< Machine id
  const char* targetName_;     //!< Target name for compilation
  const char* machineTarget_;  //!< Machine target
  const char* machineTargetLC_;//!< Machine target for LC
  const char* complibTarget_;  //!< Compiler library target name
  uint simdPerCU_;             //!< Number of SIMDs per CU
  uint simdWidth_;             //!< Number of workitems processed per SIMD
  uint simdInstructionWidth_;  //!< Number of instructions processed per SIMD
  uint memChannelBankWidth_;   //!< Memory channel bank width
  uint localMemSizePerCU_;     //!< Local memory size per CU
  uint localMemBanks_;         //!< Number of banks of local memory
  uint gfxipVersion_;          //!< The core engine GFXIP version
  uint pciDeviceId_;           //!< PCIe device id
};

// The device ID must match with the device's index into DeviceInfo
const HsaDeviceId HSA_SPECTRE_ID = 0;
const HsaDeviceId HSA_SPOOKY_ID = 1;
const HsaDeviceId HSA_TONGA_ID = 2;
const HsaDeviceId HSA_CARRIZO_ID = 3;
const HsaDeviceId HSA_ICELAND_ID = 4;
const HsaDeviceId HSA_FIJI_ID = 5;
const HsaDeviceId HSA_HAWAII_ID = 6;
const HsaDeviceId HSA_ELLESMERE_ID = 7;
const HsaDeviceId HSA_BAFFIN_ID = 8;
const HsaDeviceId HSA_VEGA10_ID = 9;
const HsaDeviceId HSA_VEGA10_HBCC_ID = 10;
const HsaDeviceId HSA_RAVEN_ID = 11;
const HsaDeviceId HSA_VEGA12_ID = 12;
const HsaDeviceId HSA_VEGA20_ID = 13;
const HsaDeviceId HSA_ARIEL_ID = 14;
const HsaDeviceId HSA_NAVI10_ID = 15;
const HsaDeviceId HSA_MI100_ID = 16;
const HsaDeviceId HSA_NAVI12_ID = 17;
const HsaDeviceId HSA_NAVI14_ID = 18;
const HsaDeviceId HSA_MI200_ID = 19;
const HsaDeviceId HSA_INVALID_DEVICE_ID = -1;

static const AMDDeviceInfo DeviceInfo[] = {
    //  targetName  machineTarget
    /* TARGET_KAVERI_SPECTRE */ {HSA_SPECTRE_ID, "", "kaveri", "", "Spectre", 4, 16, 1, 256, 64 * Ki,
                                 32, 0, 0},
    /* TARGET_KAVERI_SPOOKY */ {HSA_SPOOKY_ID, "", "kaveri", "", "Spooky", 4, 16, 1, 256, 64 * Ki, 32,
                                0, 0},
    /* TARGET_TONGA */ {HSA_TONGA_ID, "", "tonga", "gfx802", "Tonga", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET_CARRIZO */ {HSA_CARRIZO_ID, "", "carrizo", "gfx801", "Carrizo", 4, 16, 1, 256, 64 * Ki, 32, 0,
                          0},
    /* TARGET_ICELAND */ {HSA_ICELAND_ID, "", "iceland", "gfx802", "Iceland", 4, 16, 1, 256, 64 * Ki, 32, 0,
                          0},
    /* TARGET_FIJI */ {HSA_FIJI_ID, "", "fiji", "gfx803", "Fiji", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET HAWAII */ {HSA_HAWAII_ID, "", "hawaii", "gfx701", "Hawaii", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET ELLESMERE */ {HSA_ELLESMERE_ID, "", "polaris10", "gfx803", "Ellesmere", 4, 16, 1, 256, 64 * Ki,
                            32, 0, 0},
    /* TARGET BAFFIN */ {HSA_BAFFIN_ID, "", "polaris11", "gfx803", "Baffin", 4, 16, 1, 256, 64 * Ki, 32, 0,
                         0},
    /* TARGET VEGA10 */ {HSA_VEGA10_ID, "", "gfx900", "gfx900", "gfx900", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA10_HBCC */ {HSA_VEGA10_HBCC_ID, "", "gfx901", "gfx901", "gfx901", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET RAVEN */ {HSA_RAVEN_ID, "", "gfx902", "gfx902", "gfx902", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA12 */ {HSA_VEGA12_ID, "", "gfx904", "gfx904", "gfx904", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA20 */ {HSA_VEGA20_ID, "", "gfx906", "gfx906", "gfx906", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET ARIEL */ {HSA_ARIEL_ID, "", "gfx1000", "gfx1000", "gfx1000", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI10 */ {HSA_NAVI10_ID, "", "gfx1010", "gfx1010", "gfx1010", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET MI100 */ {HSA_MI100_ID, "", "gfx908", "gfx908", "gfx908", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI12 */ {HSA_NAVI12_ID, "", "gfx1011", "gfx1011", "gfx1011", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI14 */ {HSA_NAVI14_ID, "", "gfx1012", "gfx1012", "gfx1012", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET MI200 */ {HSA_MI200_ID, "", "gfx909", "gfx909", "gfx909", 4, 16, 1, 256, 64 * Ki, 32, 0, 0}
};
}

const uint kMaxAsyncQueues = 8;   // set to match the number of pipes, which is 8
#endif
<commit_msg>P4 to Git Change 2042289 by kjayapra@1_HIPWS_LNX1_PAL on 2019/12/07 06:33:01<commit_after>#pragma once

#ifndef WITHOUT_HSA_BACKEND

namespace roc {

//! Alignment restriciton for the pinned memory
const static size_t PinnedMemoryAlignment = 4 * Ki;

//! Specific defines for images for Dynamic Parallelism
const static uint DeviceQueueMaskSize = 32;

typedef uint HsaDeviceId;

struct AMDDeviceInfo {
  HsaDeviceId hsaDeviceId_;    //!< Machine id
  const char* targetName_;     //!< Target name for compilation
  const char* machineTarget_;  //!< Machine target
  const char* machineTargetLC_;//!< Machine target for LC
  const char* complibTarget_;  //!< Compiler library target name
  uint simdPerCU_;             //!< Number of SIMDs per CU
  uint simdWidth_;             //!< Number of workitems processed per SIMD
  uint simdInstructionWidth_;  //!< Number of instructions processed per SIMD
  uint memChannelBankWidth_;   //!< Memory channel bank width
  uint localMemSizePerCU_;     //!< Local memory size per CU
  uint localMemBanks_;         //!< Number of banks of local memory
  uint gfxipVersion_;          //!< The core engine GFXIP version
  uint pciDeviceId_;           //!< PCIe device id
};

// The device ID must match with the device's index into DeviceInfo
const HsaDeviceId HSA_SPECTRE_ID = 0;
const HsaDeviceId HSA_SPOOKY_ID = 1;
const HsaDeviceId HSA_TONGA_ID = 2;
const HsaDeviceId HSA_CARRIZO_ID = 3;
const HsaDeviceId HSA_ICELAND_ID = 4;
const HsaDeviceId HSA_FIJI_ID = 5;
const HsaDeviceId HSA_HAWAII_ID = 6;
const HsaDeviceId HSA_ELLESMERE_ID = 7;
const HsaDeviceId HSA_BAFFIN_ID = 8;
const HsaDeviceId HSA_VEGA10_ID = 9;
const HsaDeviceId HSA_VEGA10_HBCC_ID = 10;
const HsaDeviceId HSA_RAVEN_ID = 11;
const HsaDeviceId HSA_VEGA12_ID = 12;
const HsaDeviceId HSA_VEGA20_ID = 13;
const HsaDeviceId HSA_ARIEL_ID = 14;
const HsaDeviceId HSA_NAVI10_ID = 15;
const HsaDeviceId HSA_MI100_ID = 16;
const HsaDeviceId HSA_NAVI12_ID = 17;
const HsaDeviceId HSA_NAVI14_ID = 18;
const HsaDeviceId HSA_INVALID_DEVICE_ID = -1;

static const AMDDeviceInfo DeviceInfo[] = {
    //  targetName  machineTarget
    /* TARGET_KAVERI_SPECTRE */ {HSA_SPECTRE_ID, "", "kaveri", "", "Spectre", 4, 16, 1, 256, 64 * Ki,
                                 32, 0, 0},
    /* TARGET_KAVERI_SPOOKY */ {HSA_SPOOKY_ID, "", "kaveri", "", "Spooky", 4, 16, 1, 256, 64 * Ki, 32,
                                0, 0},
    /* TARGET_TONGA */ {HSA_TONGA_ID, "", "tonga", "gfx802", "Tonga", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET_CARRIZO */ {HSA_CARRIZO_ID, "", "carrizo", "gfx801", "Carrizo", 4, 16, 1, 256, 64 * Ki, 32, 0,
                          0},
    /* TARGET_ICELAND */ {HSA_ICELAND_ID, "", "iceland", "gfx802", "Iceland", 4, 16, 1, 256, 64 * Ki, 32, 0,
                          0},
    /* TARGET_FIJI */ {HSA_FIJI_ID, "", "fiji", "gfx803", "Fiji", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET HAWAII */ {HSA_HAWAII_ID, "", "hawaii", "gfx701", "Hawaii", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET ELLESMERE */ {HSA_ELLESMERE_ID, "", "polaris10", "gfx803", "Ellesmere", 4, 16, 1, 256, 64 * Ki,
                            32, 0, 0},
    /* TARGET BAFFIN */ {HSA_BAFFIN_ID, "", "polaris11", "gfx803", "Baffin", 4, 16, 1, 256, 64 * Ki, 32, 0,
                         0},
    /* TARGET VEGA10 */ {HSA_VEGA10_ID, "", "gfx900", "gfx900", "gfx900", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA10_HBCC */ {HSA_VEGA10_HBCC_ID, "", "gfx901", "gfx901", "gfx901", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET RAVEN */ {HSA_RAVEN_ID, "", "gfx902", "gfx902", "gfx902", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA12 */ {HSA_VEGA12_ID, "", "gfx904", "gfx904", "gfx904", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET VEGA20 */ {HSA_VEGA20_ID, "", "gfx906", "gfx906", "gfx906", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET ARIEL */ {HSA_ARIEL_ID, "", "gfx1000", "gfx1000", "gfx1000", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI10 */ {HSA_NAVI10_ID, "", "gfx1010", "gfx1010", "gfx1010", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET MI100 */ {HSA_MI100_ID, "", "gfx908", "gfx908", "gfx908", 4, 16, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI12 */ {HSA_NAVI12_ID, "", "gfx1011", "gfx1011", "gfx1011", 2, 32, 1, 256, 64 * Ki, 32, 0, 0},
    /* TARGET NAVI14 */ {HSA_NAVI14_ID, "", "gfx1012", "gfx1012", "gfx1012", 2, 32, 1, 256, 64 * Ki, 32, 0, 0}
};
}

const uint kMaxAsyncQueues = 8;   // set to match the number of pipes, which is 8
#endif
<|endoftext|>


<commit_before><commit_msg>Delete BinaryHeap.hpp<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2018,
Dan Bethell, Johannes Saam, Vahan Sosoyan.
All rights reserved. See COPYING.txt for more details.
*/

#include "aton_framebuffer.h"
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

const std::string chStr::RGBA = "RGBA",
                  chStr::rgb = "rgb",
                  chStr::depth = "depth",
                  chStr::Z = "Z",
                  chStr::N = "N",
                  chStr::P = "P",
                  chStr::ID = "ID",
                  chStr::_red = ".red",
                  chStr::_green = ".green",
                  chStr::_blue = ".blue",
                  chStr::_X = ".X",
                  chStr::_Y = ".Y",
                  chStr::_Z = ".Z";

// Unpack 1 int to 4
const std::vector<int> unpack_4_int(const int& i)
{
    const int arr[] = {((i % 10000000) / 1000000),
                       ((i % 1000000) / 10000),
                       ((i % 10000) / 100),
                        (i % 100)};

    std::vector<int> out(arr, arr + 4);
    return out;
}

// Lightweight color pixel class
RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; }

float& RenderColor::operator[](int i) { return _val[i]; }

const float& RenderColor::operator[](int i) const { return _val[i]; }

void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; }

// AOVBuffer class
AOVBuffer::AOVBuffer(const unsigned int& width,
                     const unsigned int& height,
                     const int& spp)
{
    const int size = width * height;

    switch (spp)
    {
        case 1: // Float channels
            _float_data.resize(size);
            break;
        case 3: // Color Channels
            _color_data.resize(size);
            break;
        case 4: // Color + Alpha channels
            _color_data.resize(size);
            _float_data.resize(size);
            break;
    }
}

// RenderBuffer class
RenderBuffer::RenderBuffer(const double& currentFrame,
                           const int& w,
                           const int& h,
                           const float& p): _frame(currentFrame),
                                            _width(w),
                                            _height(h),
                                            _pix_aspect(p),
                                            _progress(0),
                                            _time(0),
                                            _ram(0),
                                            _pram(0),
                                            _ready(false),
                                            _fov(0.0f),
                                            _matrix(Matrix4()),
                                            _version_int(0),
                                            _version_str(""),
                                            _samples_str("") {}
// Add new buffer
void RenderBuffer::add_aov(const char* aov,
                           const int& spp)
{
    AOVBuffer buffer(_width, _height, spp);

    _buffers.push_back(buffer);
    _aovs.push_back(aov);
}

// Get writable buffer object
void RenderBuffer::set_aov_pix(const int& b,
                               const int& x,
                               const int& y,
                               const int& spp,
                               const int& c,
                               const float& pix)
{
    AOVBuffer& rb = _buffers[b];
    const unsigned int index = (_width * y) + x;
    if (c < 3 && spp != 1)
        rb._color_data[index][c] = pix;
    else
        rb._float_data[index] = pix;
}

// Get read only buffer object
const float& RenderBuffer::get_aov_pix(const int& b,
                                       const int& x,
                                       const int& y,
                                       const int& c) const
{
    const AOVBuffer& rb = _buffers[b];
    const unsigned int index = (_width * y) + x;
    if (c < 3 && !rb._color_data.empty())
        return rb._color_data[index][c];
    else
        return rb._float_data[index];
}

// Get the current buffer index
int RenderBuffer::get_aov_index(const Channel& z)
{
    int aov_index = 0;
    if (_aovs.size() > 1)
    {
        using namespace chStr;
        const std::string& layer = getLayerName(z);

        std::vector<std::string>::iterator it;
        for(it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (*it == layer)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
            else if (*it == Z && layer == depth)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }

    }
    return aov_index;
}

// Get the current buffer index
int RenderBuffer::get_aov_index(const char* aov_name)
{
    int aov_index = 0;
    if (_aovs.size() > 1)
    {
        std::vector<std::string>::iterator it;
        for(it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (*it == aov_name)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }
    }
    return aov_index;
}

// Get N buffer/aov name name
std::string RenderBuffer::get_aov_name(const int& aov_index)
{
    std::string aov_name = "";

    if(!_aovs.empty())
    {
        try
        {
            aov_name = _aovs.at(aov_index);
        }
        catch (const std::out_of_range& e)
        {
            (void)e;
        }
        catch (...)
        {
            std::cerr << "Unexpected error at getting buffer name" << std::endl;
        }
    }

    return aov_name;
}

// Get last buffer/aov name
bool RenderBuffer::first_aov_name(const char* aovName)
{
    return strcmp(_aovs.front().c_str(), aovName) == 0;
}

// Check if Aovs has been changed
bool RenderBuffer::aovs_changed(const std::vector<std::string>& aovs)
{
    return (aovs != _aovs);
}

// Check if Resolution has been changed
bool RenderBuffer::resolution_changed(const unsigned int& w,
                                      const unsigned int& h)
{
    return (w != _width || h != _height);
}

bool RenderBuffer::camera_changed(const float& fov,
                                  const Matrix4& matrix)
{
    return (_fov != fov || _matrix != matrix);
}

// Resize the containers to match the resolution
void RenderBuffer::set_resolution(const unsigned int& w,
                                  const unsigned int& h)
{
    _width = w;
    _height = h;

    const int size = _width * _height;

    std::vector<AOVBuffer>::iterator it;
    for(it = _buffers.begin(); it != _buffers.end(); ++it)
    {
        if (!it->_color_data.empty())
        {
            RenderColor color;
            std::fill(it->_color_data.begin(), it->_color_data.end(), color);
            it->_color_data.resize(size);
        }
        if (!it->_float_data.empty())
        {
            std::fill(it->_float_data.begin(), it->_float_data.end(), 0.0f);
            it->_float_data.resize(size);
        }
    }
}

// Clear buffers and aovs
void RenderBuffer::clear_all()
{
    _buffers = std::vector<AOVBuffer>();
    _aovs = std::vector<std::string>();
}

// Check if the given buffer/aov name name is exist
bool RenderBuffer::aov_exists(const char* aovName)
{
    return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end();
}

// Resize the buffers
void RenderBuffer::resize(const size_t& s)
{
    _aovs.resize(s);
    _buffers.resize(s);
}

// Set status parameters
void RenderBuffer::set_progress(const long long& progress)
{
    _progress = progress > 100 ? 100 : progress;
}

void RenderBuffer::set_memory(const long long& ram)
{
    _ram = static_cast<int>(ram / 1048576);
    _pram = _ram > _pram ? _ram : _pram;
}
void RenderBuffer::set_time(const int& time,
                            const int& dtime)
{
    _time = dtime > time ? time : time - dtime;
}

// Set Version
void RenderBuffer::set_version(const int& version)
{
    const std::vector<int> ver = unpack_4_int(version);

    _version_str = lexical_cast<string>(ver[0]) + "." +
                   lexical_cast<string>(ver[1]) + "." +
                   lexical_cast<string>(ver[2]) + "." +
                   lexical_cast<string>(ver[3]);
}

// Set Samples
void RenderBuffer::set_samples(std::vector<int> sp)
{
    _samples_str = lexical_cast<string>(sp[0]) + "/" +
                   lexical_cast<string>(sp[1]) + "/" +
                   lexical_cast<string>(sp[2]) + "/" +
                   lexical_cast<string>(sp[3]) + "/" +
                   lexical_cast<string>(sp[4]) + "/" +
                   lexical_cast<string>(sp[5]);
}

void RenderBuffer::set_camera(const float& fov, const Matrix4& matrix)
{
    _fov = fov;
    _matrix = matrix;
}

RenderBuffer* FrameBuffer::get_renderbuffer(double frame)
{
    int index = 0;
    if (_frames.size() > 1)
    {
        int nearFIndex = INT_MIN;
        int minFIndex = INT_MAX;

        std::vector<double>::iterator it;
        for(it = _frames.begin(); it != _frames.end(); ++it)
        {
            if (frame == *it)
            {
                index = static_cast<int>(it - _frames.begin());
                break;
            }
            else if (frame > *it && nearFIndex < *it)
            {
                nearFIndex = static_cast<int>(*it);
                index = static_cast<int>(it - _frames.begin());
                continue;
            }
            else if (*it < minFIndex && nearFIndex == INT_MIN)
            {
                minFIndex = static_cast<int>(*it);
                index = static_cast<int>(it - _frames.begin());
            }
        }
    }

    return &_renderbuffers[index];
}

RenderBuffer* FrameBuffer::add_renderbuffer(DataHeader* dh)
{
        RenderBuffer rb(dh->frame(), dh->xres(), dh->yres(), dh->pixel_aspect());

        _output_name = (boost::format("%s_%d_%s")%dh->output_name()
                                                 %dh->frame()%get_date()).str();

        if (!_frames.empty())
            rb = _renderbuffers.back();

        _frame  = dh->frame();
        _session = dh->session();
        _frames.push_back(dh->frame());
        _renderbuffers.push_back(rb);
        return &_renderbuffers.back();
}

// Udpate RenderBuffer
void FrameBuffer::update_renderbuffer(DataHeader* dh)
{
    _session = dh->session();
    _output_name = (boost::format("%s_%d_%s")%dh->output_name()
                                             %dh->frame()%get_date()).str();
    _frame  = dh->frame();
}

// Clear All Data
void FrameBuffer::clear_all()
{
    _frames = std::vector<double>();
    _renderbuffers = std::vector<RenderBuffer>();
}

// Check if RenderBuffer already exists
bool FrameBuffer::renderbuffer_exists(double frame)
{
    if (!_frames.empty())
        return (std::find(_frames.begin(), _frames.end(), frame) != _frames.end());
    else
        return 0;
}
<commit_msg>Update aton_framebuffer.cpp<commit_after>/*
Copyright (c) 2018,
Dan Bethell, Johannes Saam, Vahan Sosoyan.
All rights reserved. See COPYING.txt for more details.
*/

#include "aton_framebuffer.h"
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

const std::string chStr::RGBA = "RGBA",
                  chStr::rgb = "rgb",
                  chStr::depth = "depth",
                  chStr::Z = "Z",
                  chStr::N = "N",
                  chStr::P = "P",
                  chStr::ID = "ID",
                  chStr::_red = ".red",
                  chStr::_green = ".green",
                  chStr::_blue = ".blue",
                  chStr::_X = ".X",
                  chStr::_Y = ".Y",
                  chStr::_Z = ".Z";

// Unpack 1 int to 4
const std::vector<int> unpack_4_int(const int& i)
{
    const int arr[] = {((i % 10000000) / 1000000),
                       ((i % 1000000) / 10000),
                       ((i % 10000) / 100),
                        (i % 100)};

    std::vector<int> out(arr, arr + 4);
    return out;
}

// Lightweight color pixel class
RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; }

float& RenderColor::operator[](int i) { return _val[i]; }

const float& RenderColor::operator[](int i) const { return _val[i]; }

void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; }

// AOVBuffer class
AOVBuffer::AOVBuffer(const unsigned int& width,
                     const unsigned int& height,
                     const int& spp)
{
    const int size = width * height;

    switch (spp)
    {
        case 1: // Float channels
            _float_data.resize(size);
            break;
        case 3: // Color Channels
            _color_data.resize(size);
            break;
        case 4: // Color + Alpha channels
            _color_data.resize(size);
            _float_data.resize(size);
            break;
    }
}

// RenderBuffer class
RenderBuffer::RenderBuffer(const double& currentFrame,
                           const int& w,
                           const int& h,
                           const float& p): _frame(currentFrame),
                                            _width(w),
                                            _height(h),
                                            _pix_aspect(p),
                                            _progress(0),
                                            _time(0),
                                            _ram(0),
                                            _pram(0),
                                            _ready(false),
                                            _fov(0.0f),
                                            _matrix(Matrix4()),
                                            _version_int(0),
                                            _version_str(""),
                                            _samples_str("") {}
// Add new buffer
void RenderBuffer::add_aov(const char* aov,
                           const int& spp)
{
    AOVBuffer buffer(_width, _height, spp);

    _buffers.push_back(buffer);
    _aovs.push_back(aov);
}

// Get writable buffer object
void RenderBuffer::set_aov_pix(const int& b,
                               const int& x,
                               const int& y,
                               const int& spp,
                               const int& c,
                               const float& pix)
{
    AOVBuffer& rb = _buffers[b];
    const unsigned int index = (_width * y) + x;
    if (c < 3 && spp != 1)
        rb._color_data[index][c] = pix;
    else
        rb._float_data[index] = pix;
}

// Get read only buffer object
const float& RenderBuffer::get_aov_pix(const int& b,
                                       const int& x,
                                       const int& y,
                                       const int& c) const
{
    const AOVBuffer& rb = _buffers[b];
    const unsigned int index = (_width * y) + x;
    if (c < 3 && !rb._color_data.empty())
        return rb._color_data[index][c];
    else
        return rb._float_data[index];
}

// Get the current buffer index
int RenderBuffer::get_aov_index(const Channel& z)
{
    int aov_index = 0;
    if (_aovs.size() > 1)
    {
        using namespace chStr;
        const std::string& layer = getLayerName(z);

        std::vector<std::string>::iterator it;
        for(it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (*it == layer)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
            else if (*it == Z && layer == depth)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }

    }
    return aov_index;
}

// Get the current buffer index
int RenderBuffer::get_aov_index(const char* aov_name)
{
    int aov_index = 0;
    if (_aovs.size() > 1)
    {
        std::vector<std::string>::iterator it;
        for(it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (*it == aov_name)
            {
                aov_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }
    }
    return aov_index;
}

// Get N buffer/aov name name
std::string RenderBuffer::get_aov_name(const int& aov_index)
{
    std::string aov_name = "";

    if(!_aovs.empty())
    {
        try
        {
            aov_name = _aovs.at(aov_index);
        }
        catch (const std::out_of_range& e)
        {
            (void)e;
        }
        catch (...)
        {
            std::cerr << "Unexpected error at getting buffer name" << std::endl;
        }
    }

    return aov_name;
}

// Get last buffer/aov name
bool RenderBuffer::first_aov_name(const char* aovName)
{
    return strcmp(_aovs.front().c_str(), aovName) == 0;
}

// Check if Aovs has been changed
bool RenderBuffer::aovs_changed(const std::vector<std::string>& aovs)
{
    return (aovs != _aovs);
}

// Check if Resolution has been changed
bool RenderBuffer::resolution_changed(const unsigned int& w,
                                      const unsigned int& h)
{
    return (w != _width || h != _height);
}

bool RenderBuffer::camera_changed(const float& fov,
                                  const Matrix4& matrix)
{
    return (_fov != fov || _matrix != matrix);
}

// Resize the containers to match the resolution
void RenderBuffer::set_resolution(const unsigned int& w,
                                  const unsigned int& h)
{
    _width = w;
    _height = h;

    const int size = _width * _height;

    std::vector<AOVBuffer>::iterator it;
    for(it = _buffers.begin(); it != _buffers.end(); ++it)
    {
        if (!it->_color_data.empty())
        {
            RenderColor color;
            std::fill(it->_color_data.begin(), it->_color_data.end(), color);
            it->_color_data.resize(size);
        }
        if (!it->_float_data.empty())
        {
            std::fill(it->_float_data.begin(), it->_float_data.end(), 0.0f);
            it->_float_data.resize(size);
        }
    }
}

// Clear buffers and aovs
void RenderBuffer::clear_all()
{
    _buffers = std::vector<AOVBuffer>();
    _aovs = std::vector<std::string>();
}

// Check if the given buffer/aov name name is exist
bool RenderBuffer::aov_exists(const char* aovName)
{
    return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end();
}

// Resize the buffers
void RenderBuffer::resize(const size_t& s)
{
    _aovs.resize(s);
    _buffers.resize(s);
}

// Set status parameters
void RenderBuffer::set_progress(const long long& progress)
{
    _progress = progress > 100 ? 100 : progress;
}

void RenderBuffer::set_memory(const long long& ram)
{
    _ram = static_cast<int>(ram / 1048576);
    _pram = _ram > _pram ? _ram : _pram;
}
void RenderBuffer::set_time(const int& time,
                            const int& dtime)
{
    _time = dtime > time ? time : time - dtime;
}

// Set Version
void RenderBuffer::set_version(const int& version)
{
    const std::vector<int> ver = unpack_4_int(version);

    _version_str = lexical_cast<string>(ver[0]) + "." +
                   lexical_cast<string>(ver[1]) + "." +
                   lexical_cast<string>(ver[2]) + "." +
                   lexical_cast<string>(ver[3]);
}

// Set Samples
void RenderBuffer::set_samples(std::vector<int> sp)
{
    _samples_str = lexical_cast<string>(sp[0]) + "/" +
                   lexical_cast<string>(sp[1]) + "/" +
                   lexical_cast<string>(sp[2]) + "/" +
                   lexical_cast<string>(sp[3]) + "/" +
                   lexical_cast<string>(sp[4]) + "/" +
                   lexical_cast<string>(sp[5]);
}

void RenderBuffer::set_camera(const float& fov, const Matrix4& matrix)
{
    _fov = fov;
    _matrix = matrix;
}

RenderBuffer* FrameBuffer::get_renderbuffer(double frame)
{
    int index = 0;
    if (_frames.size() > 1)
    {
        int nearFIndex = INT_MIN;
        int minFIndex = INT_MAX;

        std::vector<double>::iterator it;
        for(it = _frames.begin(); it != _frames.end(); ++it)
        {
            if (frame == *it)
            {
                index = static_cast<int>(it - _frames.begin());
                break;
            }
            else if (frame > *it && nearFIndex < *it)
            {
                nearFIndex = static_cast<int>(*it);
                index = static_cast<int>(it - _frames.begin());
                continue;
            }
            else if (*it < minFIndex && nearFIndex == INT_MIN)
            {
                minFIndex = static_cast<int>(*it);
                index = static_cast<int>(it - _frames.begin());
            }
        }
    }

    return &_renderbuffers[index];
}

RenderBuffer* FrameBuffer::add_renderbuffer(DataHeader* dh)
{
        RenderBuffer rb(dh->frame(), dh->xres(), dh->yres(), dh->pixel_aspect());

        _output_name = (boost::format("%s_%d_%s")%dh->output_name()
                                                 %dh->frame()%get_date()).str();

        if (!_frames.empty())
            rb = _renderbuffers.back();

        _frame  = dh->frame();
        _session = dh->session();
        _frames.push_back(dh->frame());
        _renderbuffers.push_back(rb);
        return &_renderbuffers.back();
}

// Udpate RenderBuffer
void FrameBuffer::update_renderbuffer(DataHeader* dh)
{
    _session = dh->session();
    _output_name = (boost::format("%s_%d_%s")%dh->output_name()
                                             %dh->frame()%get_date()).str();
    _frame  = dh->frame();
}

// Clear All Data
void FrameBuffer::clear_all()
{
    _frames = std::vector<double>();
    _renderbuffers = std::vector<RenderBuffer>();
}

// Check if RenderBuffer already exists
bool FrameBuffer::renderbuffer_exists(double frame)
{
    if (!_frames.empty())
        return (std::find(_frames.begin(), _frames.end(), frame) != _frames.end());
    else
        return 0;
}
<|endoftext|>


<commit_before>/*
  Greesound
  Copyright (C) 2015 Grame

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Centre national de création musicale
  11, cours de Verdun Gensoul 69002 Lyon - France

*/

#include <vector>
#include <exception>
#include <iostream>
#include <sstream>

#include <QPushButton>
#include <QCoreApplication>
#include <QVBoxLayout>
#include <QTimer>
#include <QMessageBox>
#include <QSettings>
#include <QQuickView>
#include <QDebug>

#include "osc/OscReceivedElements.h"

#include "Sensors.h"
#include "Tools.h"

using namespace std;
using namespace osc;

#define DEFAULT_ADDRESS "192.168.1.21"
//#define DEFAULT_ADDRESS "192.168.43.88"
#define DEFAULT_PORT 7001

const char* kGreensoundsAddr= "/greensounds";
const char* kButtonsAddr	= "/greensounds/buttons";
const char* kModeAddr		= "/mode";
const char*	kParamBaseAddr	= "/param/";
const char* kSliderBaseAddr	= "/slider/";

//------------------------------------------------------------------------
void Sensors::timerEvent(QTimerEvent * )
{
	if (!fPlay) return;

	if (fSensor->active()) {
		int count = fSensor->count();
		if (count) {
			OSCStream osc;
			osc.start( fSensor->address());
			for (int i=0; i<count; i++)
#ifdef ANDROID
				osc << -fSensor->value(i);
#else
				osc << fSensor->value(i);
#endif
			osc.end();
			fSocket->SendTo(fDestPoint, osc.Data(), osc.Size());
		}
	}

//	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		Sensor* sensor = fSensors[i];
//		if (sensor && sensor->active()) {
//            int count = sensor->count();
//            if (count) {
//				OSCStream osc;
//                osc.start( sensor->address());
//                for (int i=0; i<count; i++)
//                    osc << sensor->value(i);
//                osc.end();
//                fSocket->SendTo(fDestPoint, osc.Data(), osc.Size());
//            }
//		}
//	}
}

//------------------------------------------------------------------------
//void Sensors::initSensors()
//{
//	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		fSensors[i] = new Sensor(i);
//	}
//}

//------------------------------------------------------------------------
bool Sensors::initSensor () // initialises the rotation sensor
{
//	fSensor = new Sensor(Sensor::kRotation);
	fSensor = new Sensor(Sensor::kAccelerometer);
	if (fSensor && fSensor->available()) {
		fSensor->activate(true);
		return true;
	}
	return false;
}

//------------------------------------------------------------------------
Sensors::Sensors()
	: fUIRoot(0), fDestPoint("localhost", DEFAULT_PORT), fIPNum(0), //fListener(this, LISTENING_PORT),
	fConnected(false), fSkipError(false), fPlay(false), fSensor(0), fTimerID(0)
{
//	initSensors();
	fDestination = DEFAULT_ADDRESS;
	fPort = DEFAULT_PORT;
	fDestPoint = IpEndpointName (fDestination.toStdString().c_str(), fPort);
	try {
		fSocket = new UdpSocket();
		if (fSocket) fSocket->allowBroadcast();
		fIPNum = Tools::getIP();
		fIPStr = Tools::ip2string(fIPNum);
		fTimerID = startTimer(10);
	}
	catch(std::exception e) {
		fSocket = 0;
	}
}

//------------------------------------------------------------------------
Sensors::~Sensors()
{
	killTimer(fTimerID);
	delete fSensor;
// 	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		delete fSensors[i];
//	}
}

//------------------------------------------------------------------------
void Sensors::start()		{ fPlay = true; }
void Sensors::stop()		{ fPlay = false;}

//------------------------------------------------------------------------
void Sensors::connect(const char* dst)
{
	destination(dst);
	fConnected = true;
	send (kGreensoundsAddr, Tools::ip2string(ip()).c_str(), "connected");
}

//------------------------------------------------------------------------
unsigned long Sensors::ip() const
{
	return fIPNum;
}

//------------------------------------------------------------------------
unsigned long Sensors::broadcastAddress() const
{
	return (ip() & 0xffffff00) | 0xff;;
}

//------------------------------------------------------------------------
void Sensors::hello() const
{
	if (fSocket) {
		OSCStream p;
		p.start( kGreensoundsAddr );
		p << "hello" << Tools::ip2string(Tools::getIP()).c_str() << LISTENING_PORT;
		p.end();
		unsigned long dest = broadcastAddress ();
		fSocket->SendTo(IpEndpointName(dest, fPort), p.Data(), p.Size());
	}
}

//------------------------------------------------------------------------
void Sensors::start(QObject* o)
{
	fUIRoot = o;
}

//------------------------------------------------------------------------
// Q_INVOKABLE methods
//------------------------------------------------------------------------
//void Sensors::activate(int index, bool state)
//{
//	Sensor* s = fSensors[index];
//	if (s) s->activate(state);
//	else if (index == Sensor::kSensorMax)
//		skipChge(state);
//}
//
//bool Sensors::available(int index)
//{
//	Sensor* s = fSensors[index];
//	if (s) return s->available();
//	return (index == Sensor::kSensorMax);
//}

void Sensors::destination(QString dest)
{
	if (dest.length()) {
		fDestination = dest;
		destchge();
	}
}

void Sensors::port(QString port)
{
	bool converted = false;
	unsigned int p = port.toUInt (&converted);
	if (converted) {
		fPort = p;
		destchge();
	}
}

void Sensors::param(int num, bool state)
{
	stringstream addr;
	addr << kParamBaseAddr << num;
	send (addr.str().c_str(), int(state));
}

void Sensors::slider(int num, float value)
{
	stringstream addr;
	addr << kSliderBaseAddr << num;
	send (addr.str().c_str(), value);
}

void Sensors::pmode(bool state)
{
	send (kModeAddr, state ? 2 : 1);
}

//------------------------------------------------------------------------
//void Sensors::skipChge(int state)
//{
// 	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		Sensor* s = fSensors[i];
//		if (s) s->skipDuplicates (state);
//    }
//}

//------------------------------------------------------------------------
void Sensors::destchge()
{
	fDestPoint = IpEndpointName( destination().toStdString().c_str() , port() );
}
<commit_msg>enabling broadcast API: changed with the latest oscpack<commit_after>/*
  Greesound
  Copyright (C) 2015 Grame

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Centre national de création musicale
  11, cours de Verdun Gensoul 69002 Lyon - France

*/

#include <vector>
#include <exception>
#include <iostream>
#include <sstream>

#include <QPushButton>
#include <QCoreApplication>
#include <QVBoxLayout>
#include <QTimer>
#include <QMessageBox>
#include <QSettings>
#include <QQuickView>
#include <QDebug>

#include "osc/OscReceivedElements.h"

#include "Sensors.h"
#include "Tools.h"

using namespace std;
using namespace osc;

#define DEFAULT_ADDRESS "192.168.1.21"
//#define DEFAULT_ADDRESS "192.168.43.88"
#define DEFAULT_PORT 7001

const char* kGreensoundsAddr= "/greensounds";
const char* kButtonsAddr	= "/greensounds/buttons";
const char* kModeAddr		= "/mode";
const char*	kParamBaseAddr	= "/param/";
const char* kSliderBaseAddr	= "/slider/";

//------------------------------------------------------------------------
void Sensors::timerEvent(QTimerEvent * )
{
	if (!fPlay) return;

	if (fSensor->active()) {
		int count = fSensor->count();
		if (count) {
			OSCStream osc;
			osc.start( fSensor->address());
			for (int i=0; i<count; i++)
#ifdef ANDROID
				osc << -fSensor->value(i);
#else
				osc << fSensor->value(i);
#endif
			osc.end();
			fSocket->SendTo(fDestPoint, osc.Data(), osc.Size());
		}
	}

//	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		Sensor* sensor = fSensors[i];
//		if (sensor && sensor->active()) {
//            int count = sensor->count();
//            if (count) {
//				OSCStream osc;
//                osc.start( sensor->address());
//                for (int i=0; i<count; i++)
//                    osc << sensor->value(i);
//                osc.end();
//                fSocket->SendTo(fDestPoint, osc.Data(), osc.Size());
//            }
//		}
//	}
}

//------------------------------------------------------------------------
//void Sensors::initSensors()
//{
//	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		fSensors[i] = new Sensor(i);
//	}
//}

//------------------------------------------------------------------------
bool Sensors::initSensor () // initialises the rotation sensor
{
//	fSensor = new Sensor(Sensor::kRotation);
	fSensor = new Sensor(Sensor::kAccelerometer);
	if (fSensor && fSensor->available()) {
		fSensor->activate(true);
		return true;
	}
	return false;
}

//------------------------------------------------------------------------
Sensors::Sensors()
	: fUIRoot(0), fDestPoint("localhost", DEFAULT_PORT), fIPNum(0), //fListener(this, LISTENING_PORT),
	fConnected(false), fSkipError(false), fPlay(false), fSensor(0), fTimerID(0)
{
//	initSensors();
	fDestination = DEFAULT_ADDRESS;
	fPort = DEFAULT_PORT;
	fDestPoint = IpEndpointName (fDestination.toStdString().c_str(), fPort);
	try {
		fSocket = new UdpSocket();
		if (fSocket) fSocket->SetEnableBroadcast(true);
		fIPNum = Tools::getIP();
		fIPStr = Tools::ip2string(fIPNum);
		fTimerID = startTimer(10);
	}
	catch(std::exception e) {
		fSocket = 0;
	}
}

//------------------------------------------------------------------------
Sensors::~Sensors()
{
	killTimer(fTimerID);
	delete fSensor;
// 	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		delete fSensors[i];
//	}
}

//------------------------------------------------------------------------
void Sensors::start()		{ fPlay = true; }
void Sensors::stop()		{ fPlay = false;}

//------------------------------------------------------------------------
void Sensors::connect(const char* dst)
{
	destination(dst);
	fConnected = true;
	send (kGreensoundsAddr, Tools::ip2string(ip()).c_str(), "connected");
}

//------------------------------------------------------------------------
unsigned long Sensors::ip() const
{
	return fIPNum;
}

//------------------------------------------------------------------------
unsigned long Sensors::broadcastAddress() const
{
	return (ip() & 0xffffff00) | 0xff;;
}

//------------------------------------------------------------------------
void Sensors::hello() const
{
	if (fSocket) {
		OSCStream p;
		p.start( kGreensoundsAddr );
		p << "hello" << Tools::ip2string(Tools::getIP()).c_str() << LISTENING_PORT;
		p.end();
		unsigned long dest = broadcastAddress ();
		fSocket->SendTo(IpEndpointName(dest, fPort), p.Data(), p.Size());
	}
}

//------------------------------------------------------------------------
void Sensors::start(QObject* o)
{
	fUIRoot = o;
}

//------------------------------------------------------------------------
// Q_INVOKABLE methods
//------------------------------------------------------------------------
//void Sensors::activate(int index, bool state)
//{
//	Sensor* s = fSensors[index];
//	if (s) s->activate(state);
//	else if (index == Sensor::kSensorMax)
//		skipChge(state);
//}
//
//bool Sensors::available(int index)
//{
//	Sensor* s = fSensors[index];
//	if (s) return s->available();
//	return (index == Sensor::kSensorMax);
//}

void Sensors::destination(QString dest)
{
	if (dest.length()) {
		fDestination = dest;
		destchge();
	}
}

void Sensors::port(QString port)
{
	bool converted = false;
	unsigned int p = port.toUInt (&converted);
	if (converted) {
		fPort = p;
		destchge();
	}
}

void Sensors::param(int num, bool state)
{
	stringstream addr;
	addr << kParamBaseAddr << num;
	send (addr.str().c_str(), int(state));
}

void Sensors::slider(int num, float value)
{
	stringstream addr;
	addr << kSliderBaseAddr << num;
	send (addr.str().c_str(), value);
}

void Sensors::pmode(bool state)
{
	send (kModeAddr, state ? 2 : 1);
}

//------------------------------------------------------------------------
//void Sensors::skipChge(int state)
//{
// 	for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) {
//		Sensor* s = fSensors[i];
//		if (s) s->skipDuplicates (state);
//    }
//}

//------------------------------------------------------------------------
void Sensors::destchge()
{
	fDestPoint = IpEndpointName( destination().toStdString().c_str() , port() );
}
<|endoftext|>


<commit_before>#include "Stepper.h"

#ifdef ARDUINO_ARCH_ESP32
#include "esp32-hal-gpio.h"
#else
//#include "core_pins.h"
#endif

const int32_t Stepper::vMaxMax = 300000;   // largest speed possible (steps/s)
const uint32_t Stepper::aMax = 500000;     // speed up to 500kHz within 1 s (steps/s^2)
const uint32_t Stepper::vMaxDefault = 800; // should work with every motor (1 rev/sec in 1/4-step mode)
const uint32_t Stepper::aDefault = 2500;   // reasonably low (~0.5s for reaching the default speed)

Stepper::Stepper(const int _stepPin, const int _dirPin)
    : current(0),  stepPin(_stepPin), dirPin(_dirPin)
{
    pinMode(stepPin, OUTPUT);
    pinMode(dirPin, OUTPUT);

    setStepPinPolarity(HIGH);
    setInverseRotation(false);
    setAcceleration(aDefault);
    setMaxSpeed(vMaxDefault);
}

Stepper &Stepper::setStepPinPolarity(int polarity)
{
    #ifdef TEENSY3
    // Calculate adresses of bitbanded pin-set and pin-clear registers
    uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[stepPin].reg; //GPIO_PDOR
    uint32_t *pinSetReg = (uint32_t *)(pinRegAddr + 4 * 32);              //GPIO_PSOR = GPIO_PDOR + 4
    uint32_t *pinClearReg = (uint32_t *)(pinRegAddr + 8 * 32);            //GPIO_PCOR = GPIO_PDOR + 8
    // Assign registers according to step option
    if (polarity == LOW)
    {
        stepPinActiveReg = pinClearReg;
        stepPinInactiveReg = pinSetReg;
    }
    else
    {
        stepPinActiveReg = pinSetReg;
        stepPinInactiveReg = pinClearReg;
    }
    #else
    this->polarity = polarity;
    #endif
    clearStepPin(); // set step pin to inactive state
    return *this;
}

Stepper &Stepper::setInverseRotation(bool reverse)
{
    #ifdef TEENSY3
    // Calculate adresses of bitbanded pin-set and pin-clear registers
    uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[dirPin].reg; //GPIO_PDOR
    uint32_t *pinSetReg = (uint32_t *)(pinRegAddr + 4 * 32);             //GPIO_PSOR = GPIO_PDOR + 4
    uint32_t *pinClearReg = (uint32_t *)(pinRegAddr + 8 * 32);           //GPIO_PCOR = GPIO_PDOR + 8

    if (reverse)
    {
        dirPinCwReg = pinClearReg;
        dirPinCcwReg = pinSetReg;
    }
    else
    {
        dirPinCwReg = pinSetReg;
        dirPinCcwReg = pinClearReg;
    }
    #else
    this->reverse = reverse;
    #endif
    return *this;
}

Stepper &Stepper::setAcceleration(uint32_t a) // steps/s^2
{
    this->a = std::min(aMax, a);
    return *this;
}

Stepper &Stepper::setMaxSpeed(int32_t speed)
{
    setDir(speed >= 0 ? 1 : -1);
    vMax = std::min(vMaxMax, std::max(-vMaxMax, speed));
    return *this;
}

void Stepper::setTargetAbs(int32_t target)
{
    setTargetRel(target - current);
}

void Stepper::setTargetRel(int32_t delta)
{
    setDir(delta < 0 ? -1 : 1);
    target = current + delta;
    A = std::abs(delta);
}<commit_msg>Added scope to setTargetRel to not mix up with potential overload<commit_after>#include "Stepper.h"

#ifdef ARDUINO_ARCH_ESP32
#include "esp32-hal-gpio.h"
#else
//#include "core_pins.h"
#endif

const int32_t Stepper::vMaxMax = 300000;   // largest speed possible (steps/s)
const uint32_t Stepper::aMax = 500000;     // speed up to 500kHz within 1 s (steps/s^2)
const uint32_t Stepper::vMaxDefault = 800; // should work with every motor (1 rev/sec in 1/4-step mode)
const uint32_t Stepper::aDefault = 2500;   // reasonably low (~0.5s for reaching the default speed)

Stepper::Stepper(const int _stepPin, const int _dirPin)
    : current(0),  stepPin(_stepPin), dirPin(_dirPin)
{
    pinMode(stepPin, OUTPUT);
    pinMode(dirPin, OUTPUT);

    setStepPinPolarity(HIGH);
    setInverseRotation(false);
    setAcceleration(aDefault);
    setMaxSpeed(vMaxDefault);
}

Stepper &Stepper::setStepPinPolarity(int polarity)
{
    #ifdef TEENSY3
    // Calculate adresses of bitbanded pin-set and pin-clear registers
    uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[stepPin].reg; //GPIO_PDOR
    uint32_t *pinSetReg = (uint32_t *)(pinRegAddr + 4 * 32);              //GPIO_PSOR = GPIO_PDOR + 4
    uint32_t *pinClearReg = (uint32_t *)(pinRegAddr + 8 * 32);            //GPIO_PCOR = GPIO_PDOR + 8
    // Assign registers according to step option
    if (polarity == LOW)
    {
        stepPinActiveReg = pinClearReg;
        stepPinInactiveReg = pinSetReg;
    }
    else
    {
        stepPinActiveReg = pinSetReg;
        stepPinInactiveReg = pinClearReg;
    }
    #else
    this->polarity = polarity;
    #endif
    clearStepPin(); // set step pin to inactive state
    return *this;
}

Stepper &Stepper::setInverseRotation(bool reverse)
{
    #ifdef TEENSY3
    // Calculate adresses of bitbanded pin-set and pin-clear registers
    uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[dirPin].reg; //GPIO_PDOR
    uint32_t *pinSetReg = (uint32_t *)(pinRegAddr + 4 * 32);             //GPIO_PSOR = GPIO_PDOR + 4
    uint32_t *pinClearReg = (uint32_t *)(pinRegAddr + 8 * 32);           //GPIO_PCOR = GPIO_PDOR + 8

    if (reverse)
    {
        dirPinCwReg = pinClearReg;
        dirPinCcwReg = pinSetReg;
    }
    else
    {
        dirPinCwReg = pinSetReg;
        dirPinCcwReg = pinClearReg;
    }
    #else
    this->reverse = reverse;
    #endif
    return *this;
}

Stepper &Stepper::setAcceleration(uint32_t a) // steps/s^2
{
    this->a = std::min(aMax, a);
    return *this;
}

Stepper &Stepper::setMaxSpeed(int32_t speed)
{
    setDir(speed >= 0 ? 1 : -1);
    vMax = std::min(vMaxMax, std::max(-vMaxMax, speed));
    return *this;
}

void Stepper::setTargetAbs(int32_t target)
{
    Stepper::setTargetRel(target - current);
}

void Stepper::setTargetRel(int32_t delta)
{
    setDir(delta < 0 ? -1 : 1);
    target = current + delta;
    A = std::abs(delta);
}
<|endoftext|>


<commit_before>#include "Synapse.h"
#include "Network.h"
#include "Neuron.h"
#include <cmath>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

SynapseBase::SynapseBase(Layer* layer, float weight, int delay, ChannelType type)
{
   initialize();
   mLayer = layer;
   mWeight = weight;
   mDelay = delay;
   mType = type;
}

void SynapseBase::initialize()
{
   mC = 0;
}

void SynapseBase::stepIncreaseSTDP(float dt)
{
   if ((mType == EXCITATORY && mLayer->shouldExcitatoryLearn())||
       (mType == INHIBITORY && mLayer->shouldInhibitoryLearn()))
   {
      float t = dt-mDelay;
      if(t >= 0)
         mC += (mLayer->getAP() * std::exp(-t / mLayer->getTaoP()));
      else
         mC -= (mLayer->getAN() * std::exp(t / mLayer->getTaoN()));
   }
}

void SynapseBase::updateWeight()
{
   float d = mLayer->getDAConcentraion();
   //mWeight += (d == -1) ? (0.01f + mC) : mC * (0.002f + d);  //this is izhikevich version but why add constants???
   mWeight += (d == -1) ? mC : mC * d;
   float maxWeight = (mType == EXCITATORY) ?
      mLayer->getExcitatoryMaxWeight() : mLayer->getInhibitoryMaxWeight();
   if (mWeight > maxWeight) mWeight = maxWeight;
   if (mWeight < 0) mWeight = 0;
   mC *= mLayer->getCMultiplier();
   mWeight *= mLayer->getDecayMultiplier();
}

Synapse::Synapse(Layer* layer, Neuron* pre, Neuron* post, ChannelType type, float weight, int delay)
{
   //srand((int)time(0));

   if (weight == -1)
   {
      if (type == EXCITATORY)
         weight = layer->getExcitatoryMinRandWeight() + ((float)rand()/RAND_MAX) *
                  (layer->getExcitatoryMaxRandWeight()-layer->getExcitatoryMinRandWeight());
      else
         weight = layer->getInhibitoryMinRandWeight() + ((float)rand()/RAND_MAX) *
                  (layer->getInhibitoryMaxRandWeight()-layer->getInhibitoryMinRandWeight());
   }

   if (delay == -1)
      delay = (int)std::floor(((float)rand()/RAND_MAX) * (layer->getMaxRandDelay()-layer->getMinRandDelay()) +
         layer->getMinRandDelay() + 0.5);

   initialize();
   mPreNeuron = pre;
   mPostNeuron = post;
   mBase = new SynapseBase(layer, weight, delay, type);
   mID = layer->getNextSynapseID();
   wakeup();
}

Synapse::~Synapse()
{
   if (!mBase->mLayer->getSharedConnectionFlag())
      delete mBase;
}

void Synapse::wakeup()
{
   mTime = mBase->mLayer->getPointerToTime();
   mLogger.set(mBase->mLayer->getAddress(mPreNeuron->getLayerID(), mPreNeuron->getID(),
               mPostNeuron->getLayerID(), mPostNeuron->getID()));
}

void Synapse::initialize()
{
   mLogWeightFlag = false;
   mLastPostSpikeTime = mLastPreSpikeTime = -1000;
}

void Synapse::addSpike()
{
   mLastPreSpikeTime = *mTime;

   if (mBase->mType == EXCITATORY)
      mPostNeuron->addInputCurrent(mLastPreSpikeTime + mBase->mDelay, mBase->mWeight);
   else if (mBase->mType == INHIBITORY)
      mPostNeuron->addInputCurrent(mLastPreSpikeTime + mBase->mDelay, -mBase->mWeight);
   else if (mBase->mType == RESET)
      mPostNeuron->rest(); //should delay be takan into account?

   //TODO: don't give request when learning is turned off!
   if ((mBase->mType == EXCITATORY && mBase->mLayer->shouldExcitatoryLearn()) ||
       (mBase->mType == INHIBITORY && mBase->mLayer->shouldInhibitoryLearn()))
   {
      if (!mBase->mLayer->getSharedConnectionFlag())
      {
         //if (abs(mLastPostSpikeTime - mLastPreSpikeTime) < 20)
         mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
      else /*if (mLastPostSpikeTime > 0)*/
      {
         int postID = mPostNeuron->getID();
         if (mBase->mLayer->mSharedWinnerID == -1 || mBase->mLayer->mSharedWinnerID == postID)
         {
            mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
            mBase->mLayer->mSharedWinnerID = postID;
         }
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
   }
}

void Synapse::setPostSpikeTime()
{
   mLastPostSpikeTime = *mTime;

   if ((mBase->mType == EXCITATORY && mBase->mLayer->shouldExcitatoryLearn()) ||
       (mBase->mType == INHIBITORY && mBase->mLayer->shouldInhibitoryLearn()))
   {
      if (!mBase->mLayer->getSharedConnectionFlag())
      {
         //if (abs(mLastPostSpikeTime - mLastPreSpikeTime) < 20)
         mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
      else /*if (mLastPreSpikeTime > 0)*/
      {
         int postID = mPostNeuron->getID();
         if (mBase->mLayer->mSharedWinnerID == -1 || mBase->mLayer->mSharedWinnerID == postID)
         {
            mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
            mBase->mLayer->mSharedWinnerID = postID;
         }
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
   }
}

inline int Synapse::getPreNeuronID() const
{
   return mPreNeuron->getID();
}

inline int Synapse::getPostNeuronID() const
{
   return mPostNeuron->getID();
}

//void Synapse::addWeightLog(std::string directory)
//{
//   mLogWeightFlag = true;
//   mLogger.set(mBase->mLayer->getAddress(mPreNeuron->getLayerID(), mPreNeuron->getID(), mPostNeuron->getLayerID(),
//      mPostNeuron->getID()), directory);
//}

//void Synapse::logWeight(bool (*pattern)(int))
//{
//   if ((*pattern)(mID))
//      mLogWeightFlag = true;
//}
//
//void Synapse::logWeight(bool (*pattern)(int, int, int, int))
//{
//   if ((*pattern)(mPreNeuron->getLayerID(), mPreNeuron->getID(), mPostNeuron->getLayerID(), mPostNeuron->getID()))
//      mLogWeightFlag = true;
//}

bool Synapse::isFromLayer(int layerIndex)
{
   return layerIndex == mPreNeuron->getLayerID();
}

template <class Archive>
void Synapse::serialize(Archive &ar, const unsigned int version)
{
   ar & mID & mPreNeuron
      & mPostNeuron & mBase;
}

template <class Archive>
void SynapseBase::serialize(Archive &ar, const unsigned int version)
{
   ar & mLayer & mWeight & mDelay
      & mType;
}

template void Synapse::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive &ar, const unsigned int version);
template void Synapse::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive &ar, const unsigned int version);
template void SynapseBase::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive &ar, const unsigned int version);
template void SynapseBase::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive &ar, const unsigned int version);
<commit_msg>* fixed issue #1.<commit_after>#include "Synapse.h"
#include "Network.h"
#include "Neuron.h"
#include <cmath>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

SynapseBase::SynapseBase(Layer* layer, float weight, int delay, ChannelType type)
{
   initialize();
   mLayer = layer;
   mWeight = weight;
   mDelay = delay;
   mType = type;
}

void SynapseBase::initialize()
{
   mC = 0;
}

void SynapseBase::stepIncreaseSTDP(float dt)
{
   if ((mType == EXCITATORY && mLayer->shouldExcitatoryLearn())||
       (mType == INHIBITORY && mLayer->shouldInhibitoryLearn()))
   {
      float t = dt-mDelay;
      if(t >= 0)
         mC += (mLayer->getAP() * std::exp(-t / mLayer->getTaoP()));
      else
         mC -= (mLayer->getAN() * std::exp(t / mLayer->getTaoN()));
   }
}

void SynapseBase::updateWeight()
{
   float d = mLayer->getDAConcentraion();
   //mWeight += (d == -1) ? (0.01f + mC) : mC * (0.002f + d);  //this is izhikevich version but why add constants???
   mWeight += (d == -1) ? mC : mC * d;
   float maxWeight = (mType == EXCITATORY) ?
      mLayer->getExcitatoryMaxWeight() : mLayer->getInhibitoryMaxWeight();
   if (mWeight > maxWeight) mWeight = maxWeight;
   if (mWeight < 0) mWeight = 0;
   mC *= mLayer->getCMultiplier();
   mWeight *= mLayer->getDecayMultiplier();
}

Synapse::Synapse(Layer* layer, Neuron* pre, Neuron* post, ChannelType type, float weight, int delay)
{
   //srand((int)time(0));

   if (weight == -1)
   {
      if (type == EXCITATORY)
         weight = layer->getExcitatoryMinRandWeight() + ((float)rand()/RAND_MAX) *
                  (layer->getExcitatoryMaxRandWeight()-layer->getExcitatoryMinRandWeight());
      else
         weight = layer->getInhibitoryMinRandWeight() + ((float)rand()/RAND_MAX) *
                  (layer->getInhibitoryMaxRandWeight()-layer->getInhibitoryMinRandWeight());
   }

   if (delay == -1)
      delay = (int)std::floor(((float)rand()/RAND_MAX) * (layer->getMaxRandDelay()-layer->getMinRandDelay()) +
         layer->getMinRandDelay() + 0.5);

   initialize();
   mPreNeuron = pre;
   mPostNeuron = post;
   mBase = new SynapseBase(layer, weight, delay, type);
   mID = layer->getNextSynapseID();
   wakeup();
}

Synapse::~Synapse()
{
   if (!mBase->mLayer->getSharedConnectionFlag())
      delete mBase;
}

void Synapse::wakeup()
{
   mTime = mBase->mLayer->getPointerToTime();
   mLogger.set(mBase->mLayer->getAddress(mPreNeuron->getLayerID(), mPreNeuron->getID(),
               mPostNeuron->getLayerID(), mPostNeuron->getID()));
}

void Synapse::initialize()
{
   mLogWeightFlag = false;
   mLastPostSpikeTime = mLastPreSpikeTime = -1000;
}

void Synapse::addSpike()
{
   mLastPreSpikeTime = *mTime;

   if (mBase->mType == EXCITATORY)
      mPostNeuron->addInputCurrent(mLastPreSpikeTime + mBase->mDelay, mBase->mWeight);
   else if (mBase->mType == INHIBITORY)
      mPostNeuron->addInputCurrent(mLastPreSpikeTime + mBase->mDelay, -mBase->mWeight);
   else if (mBase->mType == RESET)
      mPostNeuron->rest(); //should delay be takan into account?

   //TODO: don't give request when learning is turned off!
   if ((mBase->mType == EXCITATORY && mBase->mLayer->shouldExcitatoryLearn()) ||
       (mBase->mType == INHIBITORY && mBase->mLayer->shouldInhibitoryLearn()))
   {
      if (!mBase->mLayer->getSharedConnectionFlag())
      {
         //if (abs(mLastPostSpikeTime - mLastPreSpikeTime) < 20)
         mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
      else /*if (mLastPostSpikeTime > 0)*/
      {
         int postID = mPostNeuron->getID();
         if (mBase->mLayer->mSharedWinnerID == -1 || mBase->mLayer->mSharedWinnerID == postID)
         {
            mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
            mBase->mLayer->mSharedWinnerID = postID;
         }
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
   }
}

void Synapse::setPostSpikeTime()
{
   mLastPostSpikeTime = *mTime;

   if ((mBase->mType == EXCITATORY && mBase->mLayer->shouldExcitatoryLearn()) ||
       (mBase->mType == INHIBITORY && mBase->mLayer->shouldInhibitoryLearn()))
   {
      if (!mBase->mLayer->getSharedConnectionFlag())
      {
         //if (abs(mLastPostSpikeTime - mLastPreSpikeTime) < 20)
         mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
      else /*if (mLastPreSpikeTime > 0)*/
      {
         int postID = mPostNeuron->getID();
         if (mBase->mLayer->mSharedWinnerID == -1 || mBase->mLayer->mSharedWinnerID == postID)
         {
            mBase->stepIncreaseSTDP(mLastPostSpikeTime - mLastPreSpikeTime);
            mBase->mLayer->mSharedWinnerID = postID;
         }
         //mLastPreSpikeTime = mLastPostSpikeTime = -1000;
      }
   }
}

int Synapse::getPreNeuronID() const
{
   return mPreNeuron->getID();
}

int Synapse::getPostNeuronID() const
{
   return mPostNeuron->getID();
}

//void Synapse::addWeightLog(std::string directory)
//{
//   mLogWeightFlag = true;
//   mLogger.set(mBase->mLayer->getAddress(mPreNeuron->getLayerID(), mPreNeuron->getID(), mPostNeuron->getLayerID(),
//      mPostNeuron->getID()), directory);
//}

//void Synapse::logWeight(bool (*pattern)(int))
//{
//   if ((*pattern)(mID))
//      mLogWeightFlag = true;
//}
//
//void Synapse::logWeight(bool (*pattern)(int, int, int, int))
//{
//   if ((*pattern)(mPreNeuron->getLayerID(), mPreNeuron->getID(), mPostNeuron->getLayerID(), mPostNeuron->getID()))
//      mLogWeightFlag = true;
//}

bool Synapse::isFromLayer(int layerIndex)
{
   return layerIndex == mPreNeuron->getLayerID();
}

template <class Archive>
void Synapse::serialize(Archive &ar, const unsigned int version)
{
   ar & mID & mPreNeuron
      & mPostNeuron & mBase;
}

template <class Archive>
void SynapseBase::serialize(Archive &ar, const unsigned int version)
{
   ar & mLayer & mWeight & mDelay
      & mType;
}

template void Synapse::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive &ar, const unsigned int version);
template void Synapse::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive &ar, const unsigned int version);
template void SynapseBase::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive &ar, const unsigned int version);
template void SynapseBase::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive &ar, const unsigned int version);
<|endoftext|>