<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/audio/tray_volume.h"

#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "base/utf_string_conversions.h"
#include "grit/ui_resources.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/slider.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"

namespace ash {
namespace internal {

namespace {
const int kVolumeImageWidth = 44;
const int kVolumeImageHeight = 44;
const int kVolumeLevel = 5;
}

namespace tray {

class VolumeButton : public views::ToggleImageButton {
 public:
  explicit VolumeButton(views::ButtonListener* listener)
      : views::ToggleImageButton(listener),
        image_index_(-1) {
    image_ = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
        IDR_AURA_UBER_TRAY_VOLUME_LEVELS);
    Update();
  }

  virtual ~VolumeButton() {}

  void Update() {
    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    int level = static_cast<int>(delegate->GetVolumeLevel() * 100);
    int image_index = level / (100 / kVolumeLevel);
    if (level > 0 && image_index == 0)
      ++image_index;
    if (level == 100)
      image_index = kVolumeLevel - 1;
    else if (image_index == kVolumeLevel - 1)
      --image_index;
    if (image_index != image_index_) {
      SkIRect region = SkIRect::MakeXYWH(0, image_index * kVolumeImageHeight,
          kVolumeImageWidth, kVolumeImageHeight);
      SkBitmap bitmap;
      image_.ToSkBitmap()->extractSubset(&bitmap, region);
      SetImage(views::CustomButton::BS_NORMAL, &bitmap);
      image_index_ = image_index;
    }
    SchedulePaint();
  }

 private:
  // Overridden from views::View.
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    views::ToggleImageButton::OnPaint(canvas);

    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    if (!delegate->IsAudioMuted())
      return;

    SkPaint paint;
    paint.setColor(SkColorSetARGB(63, 0, 0, 0));
    paint.setStrokeWidth(SkIntToScalar(3));
    canvas->sk_canvas()->drawLine(SkIntToScalar(width() - 10),
        SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(height() - 10),
        paint);
  }

  gfx::Image image_;
  int image_index_;

  DISALLOW_COPY_AND_ASSIGN(VolumeButton);
};

class VolumeView : public views::View,
                   public views::ButtonListener,
                   public views::SliderListener {
 public:
  VolumeView() {
    SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
          0, 0, 5));

    icon_ = new VolumeButton(this);
    AddChildView(icon_);

    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    slider_ = new views::Slider(this, views::Slider::HORIZONTAL);
    slider_->SetValue(delegate->GetVolumeLevel());
    slider_->set_border(views::Border::CreateEmptyBorder(0, 0, 0, 20));
    AddChildView(slider_);
  }

  virtual ~VolumeView() {}

  void SetVolumeLevel(float percent) {
    slider_->SetValue(percent);
  }

 private:
  // Overridden from views::ButtonListener.
  virtual void ButtonPressed(views::Button* sender,
                             const views::Event& event) OVERRIDE {
    CHECK(sender == icon_);
    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    delegate->SetAudioMuted(!delegate->IsAudioMuted());
  }

  // Overridden from views:SliderListener.
  virtual void SliderValueChanged(views::Slider* sender,
                                  float value,
                                  float old_value,
                                  views::SliderChangeReason reason) OVERRIDE {
    if (reason == views::VALUE_CHANGED_BY_USER)
      ash::Shell::GetInstance()->tray_delegate()->SetVolumeLevel(value);
    icon_->Update();
  }

  VolumeButton* icon_;
  views::Slider* slider_;

  DISALLOW_COPY_AND_ASSIGN(VolumeView);
};

}  // namespace tray

TrayVolume::TrayVolume() {
}

TrayVolume::~TrayVolume() {
}

views::View* TrayVolume::CreateTrayView(user::LoginStatus status) {
  return NULL;
}

views::View* TrayVolume::CreateDefaultView(user::LoginStatus status) {
  volume_view_.reset(new tray::VolumeView);
  return volume_view_.get();
}

views::View* TrayVolume::CreateDetailedView(user::LoginStatus status) {
  volume_view_.reset(new tray::VolumeView);
  return volume_view_.get();
}

void TrayVolume::DestroyTrayView() {
}

void TrayVolume::DestroyDefaultView() {
  volume_view_.reset();
}

void TrayVolume::DestroyDetailedView() {
  volume_view_.reset();
}

void TrayVolume::OnVolumeChanged(float percent) {
  if (volume_view_.get()) {
    volume_view_->SetVolumeLevel(percent);
    return;
  }

  PopupDetailedView(kTrayPopupAutoCloseDelayInSeconds, false);
}

}  // namespace internal
}  // namespace ash
<commit_msg>ash: Update the volume icon when audio is muted/unmuted.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/audio/tray_volume.h"

#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "base/utf_string_conversions.h"
#include "grit/ui_resources.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/slider.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"

namespace ash {
namespace internal {

namespace {
const int kVolumeImageWidth = 44;
const int kVolumeImageHeight = 44;
const int kVolumeLevel = 5;
}

namespace tray {

class VolumeButton : public views::ToggleImageButton {
 public:
  explicit VolumeButton(views::ButtonListener* listener)
      : views::ToggleImageButton(listener),
        image_index_(-1) {
    image_ = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
        IDR_AURA_UBER_TRAY_VOLUME_LEVELS);
    Update();
  }

  virtual ~VolumeButton() {}

  void Update() {
    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    int level = static_cast<int>(delegate->GetVolumeLevel() * 100);
    int image_index = level / (100 / kVolumeLevel);
    if (level > 0 && image_index == 0)
      ++image_index;
    if (level == 100)
      image_index = kVolumeLevel - 1;
    else if (image_index == kVolumeLevel - 1)
      --image_index;
    if (image_index != image_index_) {
      SkIRect region = SkIRect::MakeXYWH(0, image_index * kVolumeImageHeight,
          kVolumeImageWidth, kVolumeImageHeight);
      SkBitmap bitmap;
      image_.ToSkBitmap()->extractSubset(&bitmap, region);
      SetImage(views::CustomButton::BS_NORMAL, &bitmap);
      image_index_ = image_index;
    }
    SchedulePaint();
  }

 private:
  // Overridden from views::View.
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    views::ToggleImageButton::OnPaint(canvas);

    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    if (!delegate->IsAudioMuted())
      return;

    SkPaint paint;
    paint.setColor(SkColorSetARGB(63, 0, 0, 0));
    paint.setStrokeWidth(SkIntToScalar(3));
    canvas->sk_canvas()->drawLine(SkIntToScalar(width() - 10),
        SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(height() - 10),
        paint);
  }

  gfx::Image image_;
  int image_index_;

  DISALLOW_COPY_AND_ASSIGN(VolumeButton);
};

class VolumeView : public views::View,
                   public views::ButtonListener,
                   public views::SliderListener {
 public:
  VolumeView() {
    SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
          0, 0, 5));

    icon_ = new VolumeButton(this);
    AddChildView(icon_);

    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    slider_ = new views::Slider(this, views::Slider::HORIZONTAL);
    slider_->SetValue(delegate->GetVolumeLevel());
    slider_->set_border(views::Border::CreateEmptyBorder(0, 0, 0, 20));
    AddChildView(slider_);
  }

  virtual ~VolumeView() {}

  void SetVolumeLevel(float percent) {
    slider_->SetValue(percent);
    // It is possible that the volume was (un)muted, but the actual volume level
    // did not change. In that case, setting the value of the slider won't
    // trigger a repaint. So explicitly trigger a repaint.
    icon_->SchedulePaint();
  }

 private:
  // Overridden from views::ButtonListener.
  virtual void ButtonPressed(views::Button* sender,
                             const views::Event& event) OVERRIDE {
    CHECK(sender == icon_);
    ash::SystemTrayDelegate* delegate =
        ash::Shell::GetInstance()->tray_delegate();
    delegate->SetAudioMuted(!delegate->IsAudioMuted());
  }

  // Overridden from views:SliderListener.
  virtual void SliderValueChanged(views::Slider* sender,
                                  float value,
                                  float old_value,
                                  views::SliderChangeReason reason) OVERRIDE {
    if (reason == views::VALUE_CHANGED_BY_USER)
      ash::Shell::GetInstance()->tray_delegate()->SetVolumeLevel(value);
    icon_->Update();
  }

  VolumeButton* icon_;
  views::Slider* slider_;

  DISALLOW_COPY_AND_ASSIGN(VolumeView);
};

}  // namespace tray

TrayVolume::TrayVolume() {
}

TrayVolume::~TrayVolume() {
}

views::View* TrayVolume::CreateTrayView(user::LoginStatus status) {
  return NULL;
}

views::View* TrayVolume::CreateDefaultView(user::LoginStatus status) {
  volume_view_.reset(new tray::VolumeView);
  return volume_view_.get();
}

views::View* TrayVolume::CreateDetailedView(user::LoginStatus status) {
  volume_view_.reset(new tray::VolumeView);
  return volume_view_.get();
}

void TrayVolume::DestroyTrayView() {
}

void TrayVolume::DestroyDefaultView() {
  volume_view_.reset();
}

void TrayVolume::DestroyDetailedView() {
  volume_view_.reset();
}

void TrayVolume::OnVolumeChanged(float percent) {
  if (volume_view_.get()) {
    volume_view_->SetVolumeLevel(percent);
    return;
  }

  PopupDetailedView(kTrayPopupAutoCloseDelayInSeconds, false);
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

extern "C" {
	void vTickISR(void);
	void vSoftwareInterruptISR(void);
};

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;
}

extern "C" {

	void vApplicationMallocFailedHook( void )
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook( void )
	{
		/// volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook( void )
	{
	}

	void vAssertCalled( void )
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	void vApplicationSetupTimerInterrupt( void )
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
		}
	}

	void vTask2(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<commit_msg>Update: 2 LED for GR-KAEDE<commit_after>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M, RX72M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"

#include "common/format.hpp"
#include "common/input.hpp"

#include "FreeRTOS.h"
#include "task.h"

// RX64Mで、GR-KAEDE の場合有効にする
#define GR_KAEDE

extern "C" {
	void vTickISR(void);
	void vSoftwareInterruptISR(void);
};

namespace {

/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX72M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
#ifdef GR_KAEDE
	typedef device::PORT<device::PORTC, device::bitpos::B1> LED;
	typedef device::PORT<device::PORTC, device::bitpos::B0> LED2;
#else
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#endif
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX63T)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif

	typedef device::cmt_io<device::CMT0> CMT;
	CMT			cmt_;
}

extern "C" {

	void vApplicationMallocFailedHook( void )
	{
		/* Called if a call to pvPortMalloc() fails because there is insufficient
		free memory available in the FreeRTOS heap.  pvPortMalloc() is called
		internally by FreeRTOS API functions that create tasks, queues, software
		timers, and semaphores.  The size of the FreeRTOS heap is set by the
		configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
	{
		( void ) pcTaskName;
		( void ) pxTask;

		/* Run time stack overflow checking is performed if
		configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
		function is called if a stack overflow is detected. */
		taskDISABLE_INTERRUPTS();
		for( ;; );
	}

	void vApplicationIdleHook( void )
	{
		/// volatile size_t xFreeHeapSpace;

		/* This is just a trivial example of an idle hook.  It is called on each
		cycle of the idle task.  It must *NOT* attempt to block.  In this case the
		idle task just queries the amount of FreeRTOS heap that remains.  See the
		memory management section on the http://www.FreeRTOS.org web site for memory
		management options.  If there is a lot of heap memory free then the
		configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
		RAM. */
///		xFreeHeapSpace = xPortGetFreeHeapSize();

		/* Remove compiler warning about xFreeHeapSpace being set but never used. */
///		( void ) xFreeHeapSpace;
	}

	void vApplicationTickHook( void )
	{
	}

	void vAssertCalled( void )
	{
		volatile unsigned long ul = 0;

		taskENTER_CRITICAL();
		{
			/* Use the debugger to set ul to a non-zero value in order to step out
			of this function to determine why it was called. */
			while( ul == 0 )
			{
				portNOP();
			}
		}
		taskEXIT_CRITICAL();
	}

	void vApplicationSetupTimerInterrupt( void )
	{
		uint8_t intr = configKERNEL_INTERRUPT_PRIORITY;
		cmt_.start(configTICK_RATE_HZ, intr, vTickISR);

		device::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);
		device::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);
	}
};

namespace {

	void vTask1(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
			LED::P = !LED::P();
			vTaskExitCritical();
			vTaskDelay(500 / portTICK_PERIOD_MS);
		}
	}

	void vTask2(void *pvParameters)
	{
		while(1) {
			vTaskEnterCritical();
#ifdef GR_KAEDE
			LED2::P = !LED2::P();
#else
			LED::P = !LED::P();
#endif
			vTaskExitCritical();
			vTaskDelay(100 / portTICK_PERIOD_MS);
		}
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	LED::OUTPUT();  // LED ポートを出力に設定
	LED::P = 1;		// Off
#ifdef GR_KAEDE
	LED2::OUTPUT();
	LED2::P = 1;
#endif

	{
		uint32_t stack_size = 512;
		void* param = nullptr;
		uint32_t prio = 1;
		xTaskCreate(vTask1, "Task1", stack_size, param, prio, nullptr);
		xTaskCreate(vTask2, "Task2", stack_size, param, prio, nullptr);
	}

	vTaskStartScheduler();

	// タスクスケジューラーが正常なら実行されない
	while(1) {
		utils::delay::milli_second(250);
		LED::P = !LED::P();
		utils::delay::milli_second(250);
		LED::P = !LED::P();
	}
}
<|endoftext|>


<commit_before>#include <ruby.h>
#include <ruby/encoding.h>
#include "unicode.h"

MediaInfoDLL::String value_to_ansi_string(VALUE s)
{
  rb_encoding* enc = rb_enc_find("ANSI");
  VALUE exported = rb_str_export_to_enc(s, enc);
  return MediaInfoDLL::String(StringValueCStr(exported));
}

VALUE ansi_string_to_value(MediaInfoDLL::String s)
{
  return rb_external_str_new_with_enc(s.c_str(), s.length(), rb_enc_find("ANSI"));
}
<commit_msg>Encoding conversion for Rubinius<commit_after>#include <ruby.h>
#include <ruby/encoding.h>
#include "unicode.h"

MediaInfoDLL::String value_to_ansi_string(VALUE s)
{
  rb_encoding* enc = rb_enc_find("ANSI");
  VALUE exported = rb_str_export_to_enc(s, enc);
  return MediaInfoDLL::String(StringValueCStr(exported));
}

VALUE ansi_string_to_value(MediaInfoDLL::String s)
{
#ifdef RBX_RUBY_VERSION
  return rb_external_str_new_with_enc(s.c_str(), s.length(), rb_enc_find("ANSI"));
#else
  return rb_external_str_new_with_enc(s.c_str(), s.length(), rb_ascii8bit_encoding());
#endif
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-Forward, Andrew "Art" Clarke
 *
 * This file is part of Humble Video.
 *
 * Humble Video is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Humble Video is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Humble Video.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <io/humble/ferry/HumbleException.h>
#include <io/humble/ferry/Logger.h>

#include <io/humble/video/MediaPictureResamplerImpl.h>
#include <io/humble/video/MediaPictureImpl.h>
#include <io/humble/video/Rational.h>
#include <io/humble/video/Property.h>
#include <io/humble/video/VideoExceptions.h>

VS_LOG_SETUP(VS_CPP_PACKAGE);

using namespace io::humble::ferry;

namespace io { namespace humble { namespace video
{

MediaPictureResamplerImpl :: MediaPictureResamplerImpl()
{
  mIHeight = 0;
  mIWidth = 0;
  mOHeight = 0;
  mOWidth = 0;
  mIPixelFmt = PixelFormat::PIX_FMT_NONE;
  mOPixelFmt = PixelFormat::PIX_FMT_NONE;
  mContext = 0;
  mState = STATE_INITED;
}

MediaPictureResamplerImpl :: ~MediaPictureResamplerImpl()
{
  if (mContext)
    sws_freeContext(mContext);
  mContext = 0;
}

int32_t
MediaPictureResamplerImpl :: getInputHeight()
{
  return mIHeight;
}

int32_t
MediaPictureResamplerImpl :: getInputWidth()
{
  return mIWidth;
}

int32_t
MediaPictureResamplerImpl :: getOutputHeight()
{
  return mOHeight;
}

int32_t
MediaPictureResamplerImpl :: getOutputWidth()
{
  return mOWidth;
}

PixelFormat::Type
MediaPictureResamplerImpl :: getInputFormat()
{
  return mIPixelFmt;
}

PixelFormat::Type
MediaPictureResamplerImpl :: getOutputFormat()
{
  return mOPixelFmt;
}

void
MediaPictureResamplerImpl::open() {
  mState = STATE_OPENED;
}
void
MediaPictureResamplerImpl :: resample(MediaPicture* pOutFrame, MediaPicture* pInFrame)
{
  int32_t retval = -1;
  if (mState != STATE_OPENED) {
    VS_THROW(HumbleRuntimeError("open() must be called before resample is attempted"));
  }
  MediaPictureImpl* outFrame = dynamic_cast<MediaPictureImpl*>(pOutFrame);
  MediaPictureImpl* inFrame  = dynamic_cast<MediaPictureImpl*>(pInFrame);
  if (!outFrame)
    VS_THROW(HumbleInvalidArgument("invalid output frame"));
  if (outFrame->getHeight() != mOHeight)
    VS_THROW(HumbleInvalidArgument("output frame height does not match expected value"));
  if (outFrame->getWidth() != mOWidth)
    VS_THROW(HumbleInvalidArgument("output frame width does not match expected value"));
  if (outFrame->getFormat() != mOPixelFmt)
    VS_THROW(HumbleInvalidArgument("output frame pixel format does not match expected value"));

  if (!inFrame)
    VS_THROW(HumbleInvalidArgument("invalid input frame"));

  if (inFrame->getHeight() != mIHeight)
    VS_THROW(HumbleInvalidArgument("input frame height does not match expected value"));
  if (inFrame->getWidth() != mIWidth)
    VS_THROW(HumbleInvalidArgument("input frame width does not match expected value"));
  if (inFrame->getFormat() != mIPixelFmt)
    VS_THROW(HumbleInvalidArgument("input frame pixel format does not match expected value"));
  if (!inFrame->isComplete())
    VS_THROW(HumbleRuntimeError("incoming frame doesn't have complete data"));

  outFrame->setComplete(false);
  AVFrame *outAVFrame = outFrame->getCtx();

  AVFrame *inAVFrame = inFrame->getCtx();

  retval = sws_scale(mContext, inAVFrame->data, inAVFrame->linesize, 0,
      mIHeight, outAVFrame->data, outAVFrame->linesize);

  FfmpegException::check(retval, "Error while resampling. ");

  RefPointer<Rational> timeBase = inFrame->getTimeBase();
  outFrame->setTimeBase(timeBase.value());
  outFrame->setQuality(inFrame->getQuality());
  outFrame->setComplete(retval >= 0);

}

MediaPictureResamplerImpl*
MediaPictureResamplerImpl :: make(
    int32_t outputWidth, int32_t outputHeight,
    PixelFormat::Type outputFmt,
    int32_t inputWidth, int32_t inputHeight,
    PixelFormat::Type inputFmt,
    int32_t flags)
{
  RefPointer<MediaPictureResamplerImpl> retval = 0;
  if (outputWidth <= 0)
    VS_THROW(HumbleInvalidArgument("invalid output width"));
  if (outputHeight <= 0)
    VS_THROW(HumbleInvalidArgument("invalid output height"));
  if (outputFmt == PixelFormat::PIX_FMT_NONE)
    VS_THROW(HumbleInvalidArgument("cannot set output pixel format to none"));
  if (inputWidth <= 0)
    VS_THROW(HumbleInvalidArgument("invalid input width"));
  if (inputHeight <= 0)
    VS_THROW(HumbleInvalidArgument("invalid input height"));
  if (inputFmt == PixelFormat::PIX_FMT_NONE)
    VS_THROW(HumbleInvalidArgument("cannot set input pixel format to none"));

  retval = MediaPictureResamplerImpl::make();
  retval->mOHeight = outputHeight;
  retval->mOWidth = outputWidth;
  retval->mOPixelFmt = outputFmt;

  retval->mIHeight = inputHeight;
  retval->mIWidth = inputWidth;
  retval->mIPixelFmt = inputFmt;

  if (inputWidth < outputWidth)
    // We're upscaling
    flags |= SWS_BICUBIC;
  else
    // We're downscaling
    flags |= SWS_AREA;

  retval->mContext = sws_getCachedContext(
      0, // cached context
      retval->mIWidth, // src width
      retval->mIHeight, // src height
      (enum AVPixelFormat)retval->mIPixelFmt, // src pixel type
      retval->mOWidth, // dst width
      retval->mOHeight, // dst height
      (enum AVPixelFormat)retval->mOPixelFmt, // dst pixel type
      flags, // Flags
      0, // Source Filter
      0, // Destination Filter
      0 // An array of parameters for filters
  );
  if (!retval->mContext) {
    VS_THROW(HumbleRuntimeError("could not allocate an image rescaler"));
  }

  return retval.get();
}

}}}
<commit_msg>propagate timestamps<commit_after>/*
 * Copyright (c) 2013-Forward, Andrew "Art" Clarke
 *
 * This file is part of Humble Video.
 *
 * Humble Video is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Humble Video is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Humble Video.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <io/humble/ferry/HumbleException.h>
#include <io/humble/ferry/Logger.h>

#include <io/humble/video/MediaPictureResamplerImpl.h>
#include <io/humble/video/MediaPictureImpl.h>
#include <io/humble/video/Rational.h>
#include <io/humble/video/Property.h>
#include <io/humble/video/VideoExceptions.h>

VS_LOG_SETUP(VS_CPP_PACKAGE);

using namespace io::humble::ferry;

namespace io { namespace humble { namespace video
{

MediaPictureResamplerImpl :: MediaPictureResamplerImpl()
{
  mIHeight = 0;
  mIWidth = 0;
  mOHeight = 0;
  mOWidth = 0;
  mIPixelFmt = PixelFormat::PIX_FMT_NONE;
  mOPixelFmt = PixelFormat::PIX_FMT_NONE;
  mContext = 0;
  mState = STATE_INITED;
}

MediaPictureResamplerImpl :: ~MediaPictureResamplerImpl()
{
  if (mContext)
    sws_freeContext(mContext);
  mContext = 0;
}

int32_t
MediaPictureResamplerImpl :: getInputHeight()
{
  return mIHeight;
}

int32_t
MediaPictureResamplerImpl :: getInputWidth()
{
  return mIWidth;
}

int32_t
MediaPictureResamplerImpl :: getOutputHeight()
{
  return mOHeight;
}

int32_t
MediaPictureResamplerImpl :: getOutputWidth()
{
  return mOWidth;
}

PixelFormat::Type
MediaPictureResamplerImpl :: getInputFormat()
{
  return mIPixelFmt;
}

PixelFormat::Type
MediaPictureResamplerImpl :: getOutputFormat()
{
  return mOPixelFmt;
}

void
MediaPictureResamplerImpl::open() {
  mState = STATE_OPENED;
}
void
MediaPictureResamplerImpl :: resample(MediaPicture* pOutFrame, MediaPicture* pInFrame)
{
  int32_t retval = -1;
  if (mState != STATE_OPENED) {
    VS_THROW(HumbleRuntimeError("open() must be called before resample is attempted"));
  }
  MediaPictureImpl* outFrame = dynamic_cast<MediaPictureImpl*>(pOutFrame);
  MediaPictureImpl* inFrame  = dynamic_cast<MediaPictureImpl*>(pInFrame);
  if (!outFrame)
    VS_THROW(HumbleInvalidArgument("invalid output frame"));
  if (outFrame->getHeight() != mOHeight)
    VS_THROW(HumbleInvalidArgument("output frame height does not match expected value"));
  if (outFrame->getWidth() != mOWidth)
    VS_THROW(HumbleInvalidArgument("output frame width does not match expected value"));
  if (outFrame->getFormat() != mOPixelFmt)
    VS_THROW(HumbleInvalidArgument("output frame pixel format does not match expected value"));

  if (!inFrame)
    VS_THROW(HumbleInvalidArgument("invalid input frame"));

  if (inFrame->getHeight() != mIHeight)
    VS_THROW(HumbleInvalidArgument("input frame height does not match expected value"));
  if (inFrame->getWidth() != mIWidth)
    VS_THROW(HumbleInvalidArgument("input frame width does not match expected value"));
  if (inFrame->getFormat() != mIPixelFmt)
    VS_THROW(HumbleInvalidArgument("input frame pixel format does not match expected value"));
  if (!inFrame->isComplete())
    VS_THROW(HumbleRuntimeError("incoming frame doesn't have complete data"));

  outFrame->setComplete(false);
  AVFrame *outAVFrame = outFrame->getCtx();

  AVFrame *inAVFrame = inFrame->getCtx();

  retval = sws_scale(mContext, inAVFrame->data, inAVFrame->linesize, 0,
      mIHeight, outAVFrame->data, outAVFrame->linesize);

  FfmpegException::check(retval, "Error while resampling. ");

  outFrame->setTimeStamp(inFrame->getTimeStamp());

  RefPointer<Rational> timeBase = inFrame->getTimeBase();
  outFrame->setTimeBase(timeBase.value());

  outFrame->setQuality(inFrame->getQuality());
  outFrame->setComplete(retval >= 0);

}

MediaPictureResamplerImpl*
MediaPictureResamplerImpl :: make(
    int32_t outputWidth, int32_t outputHeight,
    PixelFormat::Type outputFmt,
    int32_t inputWidth, int32_t inputHeight,
    PixelFormat::Type inputFmt,
    int32_t flags)
{
  RefPointer<MediaPictureResamplerImpl> retval = 0;
  if (outputWidth <= 0)
    VS_THROW(HumbleInvalidArgument("invalid output width"));
  if (outputHeight <= 0)
    VS_THROW(HumbleInvalidArgument("invalid output height"));
  if (outputFmt == PixelFormat::PIX_FMT_NONE)
    VS_THROW(HumbleInvalidArgument("cannot set output pixel format to none"));
  if (inputWidth <= 0)
    VS_THROW(HumbleInvalidArgument("invalid input width"));
  if (inputHeight <= 0)
    VS_THROW(HumbleInvalidArgument("invalid input height"));
  if (inputFmt == PixelFormat::PIX_FMT_NONE)
    VS_THROW(HumbleInvalidArgument("cannot set input pixel format to none"));

  retval = MediaPictureResamplerImpl::make();
  retval->mOHeight = outputHeight;
  retval->mOWidth = outputWidth;
  retval->mOPixelFmt = outputFmt;

  retval->mIHeight = inputHeight;
  retval->mIWidth = inputWidth;
  retval->mIPixelFmt = inputFmt;

  if (inputWidth < outputWidth)
    // We're upscaling
    flags |= SWS_BICUBIC;
  else
    // We're downscaling
    flags |= SWS_AREA;

  retval->mContext = sws_getCachedContext(
      0, // cached context
      retval->mIWidth, // src width
      retval->mIHeight, // src height
      (enum AVPixelFormat)retval->mIPixelFmt, // src pixel type
      retval->mOWidth, // dst width
      retval->mOHeight, // dst height
      (enum AVPixelFormat)retval->mOPixelFmt, // dst pixel type
      flags, // Flags
      0, // Source Filter
      0, // Destination Filter
      0 // An array of parameters for filters
  );
  if (!retval->mContext) {
    VS_THROW(HumbleRuntimeError("could not allocate an image rescaler"));
  }

  return retval.get();
}

}}}
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP
#define IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP

#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_receiver_data.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_sender_data.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/locking_policy.hpp"
#include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp"

#include <cstdint>

namespace iox
{
namespace popo
{
struct ClientChunkDistributorConfig
{
    static constexpr uint32_t MAX_QUEUES = 1;
    static constexpr uint64_t MAX_HISTORY_CAPACITY = 1; // could be 0, but problem for the container then
};

struct ServerChunkDistributorConfig
{
    static constexpr uint32_t MAX_QUEUES = MAX_CLIENTS_PER_SERVER;
    static constexpr uint64_t MAX_HISTORY_CAPACITY = 1; // could be 0, but problem for the container then
};

struct ClientChunkQueueConfig
{
    static constexpr uint64_t MAX_QUEUE_CAPACITY = MAX_RESPONSE_QUEUE_CAPACITY;
};

struct ServerChunkQueueConfig
{
    static constexpr uint64_t MAX_QUEUE_CAPACITY = MAX_REQUEST_QUEUE_CAPACITY;
};

using ClientChunkQueueData_t = ChunkQueueData<ClientChunkQueueConfig, ThreadSafePolicy>;

using ServerChunkQueueData_t = ChunkQueueData<ServerChunkQueueConfig, ThreadSafePolicy>;

using ClientChunkDistributorData_t =
    ChunkDistributorData<ClientChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ServerChunkQueueData_t>>;

using ServerChunkDistributorData_t =
    ChunkDistributorData<ServerChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ClientChunkQueueData_t>>;

using ClientChunkReceiverData_t = ChunkReceiverData<MAX_RESPONSES_PROCESSED_SIMULTANEOUSLY, ClientChunkQueueData_t>;

using ServerChunkReceiverData_t = ChunkReceiverData<MAX_REQUESTS_PROCESSED_SIMULTANEOUSLY, ServerChunkQueueData_t>;

using ClientChunkSenderData_t = ChunkSenderData<MAX_REQUESTS_ALLOCATED_SIMULTANEOUSLY, ClientChunkDistributorData_t>;

using ServerChunkSenderData_t = ChunkSenderData<MAX_RESPONSES_ALLOCATED_SIMULTANEOUSLY, ServerChunkDistributorData_t>;

class RequestHeader
{
  public:
    explicit RequestHeader(cxx::not_null<ClientChunkQueueData_t* const> chunkQueueDataPtr) noexcept
        : m_responseQueue(chunkQueueDataPtr)
    {
    }

    RequestHeader(const RequestHeader& other) = delete;
    RequestHeader& operator=(const RequestHeader&) = delete;
    RequestHeader(RequestHeader&& rhs) = default;
    RequestHeader& operator=(RequestHeader&& rhs) = default;
    virtual ~RequestHeader() = default;

    void setSequenceNumber(const int64_t sequenceNumber) noexcept
    {
        m_sequenceNumber = sequenceNumber;
    }
    void setFireAndForget(const bool fireAndForget) noexcept
    {
        m_isFireAndForget = fireAndForget;
    }

    mepoo::ChunkHeader* getChunkHeader() const noexcept
    {
        /// todo
        return nullptr;
    }
    void* getPayload() noexcept
    {
        /// todo
        return nullptr;
    }

  private:
    int64_t m_sequenceNumber{0};
    bool m_isFireAndForget{false};
    const relative_ptr<ClientChunkQueueData_t> m_responseQueue;
};

class ResponseHeader
{
  public:
    ResponseHeader(cxx::not_null<ClientChunkQueueData_t* const> chunkQueueDataPtr, const int64_t sequenceNumber) noexcept
        : m_sequenceNumber(sequenceNumber)
        , m_destinationQueue(chunkQueueDataPtr)
    {
    }

    ResponseHeader(const ResponseHeader& other) = delete;
    ResponseHeader& operator=(const ResponseHeader&) = delete;
    ResponseHeader(ResponseHeader&& rhs) = default;
    ResponseHeader& operator=(ResponseHeader&& rhs) = default;
    virtual ~ResponseHeader() = default;

    void setServerError(bool serverError) noexcept
    {
        m_hasServerError = serverError;
    }

    const mepoo::ChunkHeader* getChunkHeader() const noexcept
    {
        /// todo
        return nullptr;
    }
    const void* getPayload() const noexcept
    {
        /// todo
        return nullptr;
    }

    int64_t getSequenceNumber() const noexcept
    {
        return m_sequenceNumber;
    }

    bool hasServerError() const noexcept
    {
        return m_hasServerError;
    }

  private:
    const int64_t m_sequenceNumber{0};
    bool m_hasServerError{false};
    const relative_ptr<ClientChunkQueueData_t> m_destinationQueue;
};

} // namespace popo
} // namespace iox

#endif // IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP
<commit_msg>iox-#27-1: request and response header should be moveable<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP
#define IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP

#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_receiver_data.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_sender_data.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/locking_policy.hpp"
#include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp"

#include <cstdint>

namespace iox
{
namespace popo
{
struct ClientChunkDistributorConfig
{
    static constexpr uint32_t MAX_QUEUES = 1;
    static constexpr uint64_t MAX_HISTORY_CAPACITY = 1; // could be 0, but problem for the container then
};

struct ServerChunkDistributorConfig
{
    static constexpr uint32_t MAX_QUEUES = MAX_CLIENTS_PER_SERVER;
    static constexpr uint64_t MAX_HISTORY_CAPACITY = 1; // could be 0, but problem for the container then
};

struct ClientChunkQueueConfig
{
    static constexpr uint64_t MAX_QUEUE_CAPACITY = MAX_RESPONSE_QUEUE_CAPACITY;
};

struct ServerChunkQueueConfig
{
    static constexpr uint64_t MAX_QUEUE_CAPACITY = MAX_REQUEST_QUEUE_CAPACITY;
};

using ClientChunkQueueData_t = ChunkQueueData<ClientChunkQueueConfig, ThreadSafePolicy>;

using ServerChunkQueueData_t = ChunkQueueData<ServerChunkQueueConfig, ThreadSafePolicy>;

using ClientChunkDistributorData_t =
    ChunkDistributorData<ClientChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ServerChunkQueueData_t>>;

using ServerChunkDistributorData_t =
    ChunkDistributorData<ServerChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ClientChunkQueueData_t>>;

using ClientChunkReceiverData_t = ChunkReceiverData<MAX_RESPONSES_PROCESSED_SIMULTANEOUSLY, ClientChunkQueueData_t>;

using ServerChunkReceiverData_t = ChunkReceiverData<MAX_REQUESTS_PROCESSED_SIMULTANEOUSLY, ServerChunkQueueData_t>;

using ClientChunkSenderData_t = ChunkSenderData<MAX_REQUESTS_ALLOCATED_SIMULTANEOUSLY, ClientChunkDistributorData_t>;

using ServerChunkSenderData_t = ChunkSenderData<MAX_RESPONSES_ALLOCATED_SIMULTANEOUSLY, ServerChunkDistributorData_t>;

class RequestHeader
{
  public:
    explicit RequestHeader(cxx::not_null<ClientChunkQueueData_t* const> chunkQueueDataPtr) noexcept
        : m_responseQueue(chunkQueueDataPtr)
    {
    }

    RequestHeader(const RequestHeader& other) = delete;
    RequestHeader& operator=(const RequestHeader&) = delete;
    RequestHeader(RequestHeader&& rhs) = default;
    RequestHeader& operator=(RequestHeader&& rhs) = default;
    virtual ~RequestHeader() = default;

    void setSequenceNumber(const int64_t sequenceNumber) noexcept
    {
        m_sequenceNumber = sequenceNumber;
    }
    void setFireAndForget(const bool fireAndForget) noexcept
    {
        m_isFireAndForget = fireAndForget;
    }

    mepoo::ChunkHeader* getChunkHeader() const noexcept
    {
        /// todo
        return nullptr;
    }
    void* getPayload() noexcept
    {
        /// todo
        return nullptr;
    }

  private:
    int64_t m_sequenceNumber{0};
    bool m_isFireAndForget{false};
    relative_ptr<ClientChunkQueueData_t> m_responseQueue;
};

class ResponseHeader
{
  public:
    ResponseHeader(cxx::not_null<ClientChunkQueueData_t* const> chunkQueueDataPtr, const int64_t sequenceNumber) noexcept
        : m_sequenceNumber(sequenceNumber)
        , m_destinationQueue(chunkQueueDataPtr)
    {
    }

    ResponseHeader(const ResponseHeader& other) = delete;
    ResponseHeader& operator=(const ResponseHeader&) = delete;
    ResponseHeader(ResponseHeader&& rhs) = default;
    ResponseHeader& operator=(ResponseHeader&& rhs) = default;
    virtual ~ResponseHeader() = default;

    void setServerError(bool serverError) noexcept
    {
        m_hasServerError = serverError;
    }

    const mepoo::ChunkHeader* getChunkHeader() const noexcept
    {
        /// todo
        return nullptr;
    }
    const void* getPayload() const noexcept
    {
        /// todo
        return nullptr;
    }

    int64_t getSequenceNumber() const noexcept
    {
        return m_sequenceNumber;
    }

    bool hasServerError() const noexcept
    {
        return m_hasServerError;
    }

  private:
    int64_t m_sequenceNumber{0};
    bool m_hasServerError{false};
    relative_ptr<ClientChunkQueueData_t> m_destinationQueue;
};

} // namespace popo
} // namespace iox

#endif // IOX_POSH_POPO_PORTS_CLIENT_SERVER_PORT_TYPES_HPP
<|endoftext|>


<commit_before>#ifndef __CONTROLLER_HPP
#define __CONTROLLER_HPP

#ifndef __ODRIVE_MAIN_H
#error "This file should not be included directly. Include odrive_main.h instead."
#endif

class Controller : public ODriveIntf::ControllerIntf {
public:
    typedef struct {
        uint32_t index = 0;
        float cogging_map[3600];
        bool pre_calibrated = false;
        bool calib_anticogging = false;
        float calib_pos_threshold = 1.0f;
        float calib_vel_threshold = 1.0f;
        float cogging_ratio = 1.0f;
        bool anticogging_enabled = true;
    } Anticogging_t;

    struct Config_t {
        ControlMode control_mode = CONTROL_MODE_POSITION_CONTROL;  //see: ControlMode_t
        InputMode input_mode = INPUT_MODE_PASSTHROUGH;             //see: InputMode_t
        float pos_gain = 20.0f;                                    // [(turn/s) / turn]
        float vel_gain = 1.0f / 6.0f;                              // [Nm/(turn/s)]
        // float vel_gain = 0.2f / 200.0f,              // [Nm/(rad/s)] <sensorless example>
        float vel_integrator_gain = 2.0f / 6.0f;    // [Nm/(turn/s * s)]
        float vel_limit = 2.0f;                     // [turn/s] Infinity to disable.
        float vel_limit_tolerance = 1.2f;           // ratio to vel_lim. Infinity to disable.
        float vel_ramp_rate = 1.0f;                 // [(turn/s) / s]
        float torque_ramp_rate = 0.01f;           // Nm / sec
        bool circular_setpoints = false;
        float circular_setpoint_range = 1.0f;  // Circular range when circular_setpoints is true. [turn]
        float inertia = 0.0f;                         // [A/(count/s^2)]
        float input_filter_bandwidth = 2.0f;          // [1/s]
        float homing_speed = 0.25f;                 // [turn/s]
        Anticogging_t anticogging;
        float gain_scheduling_width = 10.0f;
        bool enable_gain_scheduling = false;
        bool enable_vel_limit = true;
        bool enable_overspeed_error = true;
        bool enable_current_mode_vel_limit = true;  // enable velocity limit in current control mode (requires a valid velocity estimator)
        uint8_t axis_to_mirror = -1;
        float mirror_ratio = 1.0f;
        uint8_t load_encoder_axis = -1;  // default depends on Axis number and is set in load_configuration()

        // custom setters
        Controller* parent;
        void set_input_filter_bandwidth(float value) { input_filter_bandwidth = value; parent->update_filter_gains(); }
    };

    explicit Controller(Config_t& config);
    void reset();
    void set_error(Error error);

    void input_pos_updated();
    bool select_encoder(size_t encoder_num);

    // Trajectory-Planned control
    void move_to_pos(float goal_point);
    void move_incremental(float displacement, bool from_goal_point);

    // TODO: make this more similar to other calibration loops
    void start_anticogging_calibration();
    bool anticogging_calibration(float pos_estimate, float vel_estimate);

    void update_filter_gains();
    bool update(float* torque_setpoint);

    Config_t& config_;
    Axis* axis_ = nullptr; // set by Axis constructor

    Error error_ = ERROR_NONE;

    float* pos_estimate_linear_ = nullptr;
    float* pos_estimate_circular_ = nullptr;
    bool* pos_estimate_valid_src_ = nullptr;
    float* vel_estimate_src_ = nullptr;
    bool* vel_estimate_valid_src_ = nullptr;
    float* pos_wrap_src_ = nullptr;

    float pos_setpoint_ = 0.0f; // [turns]
    float vel_setpoint_ = 0.0f; // [turn/s]
    // float vel_setpoint = 800.0f; <sensorless example>
    float vel_integrator_torque_ = 0.0f;    // [Nm]
    float torque_setpoint_ = 0.0f;  // [Nm]

    float input_pos_ = 0.0f;     // [turns]
    float input_vel_ = 0.0f;     // [turn/s]
    float input_torque_ = 0.0f;  // [Nm]
    float input_filter_kp_ = 0.0f;
    float input_filter_ki_ = 0.0f;

    bool input_pos_updated_ = false;

    bool trajectory_done_ = true;

    bool anticogging_valid_ = false;

    // custom setters
    void set_input_pos(float value) { input_pos_ = value; input_pos_updated(); }

};

#endif // __CONTROLLER_HPP
<commit_msg>Also add _src in header<commit_after>#ifndef __CONTROLLER_HPP
#define __CONTROLLER_HPP

#ifndef __ODRIVE_MAIN_H
#error "This file should not be included directly. Include odrive_main.h instead."
#endif

class Controller : public ODriveIntf::ControllerIntf {
public:
    typedef struct {
        uint32_t index = 0;
        float cogging_map[3600];
        bool pre_calibrated = false;
        bool calib_anticogging = false;
        float calib_pos_threshold = 1.0f;
        float calib_vel_threshold = 1.0f;
        float cogging_ratio = 1.0f;
        bool anticogging_enabled = true;
    } Anticogging_t;

    struct Config_t {
        ControlMode control_mode = CONTROL_MODE_POSITION_CONTROL;  //see: ControlMode_t
        InputMode input_mode = INPUT_MODE_PASSTHROUGH;             //see: InputMode_t
        float pos_gain = 20.0f;                                    // [(turn/s) / turn]
        float vel_gain = 1.0f / 6.0f;                              // [Nm/(turn/s)]
        // float vel_gain = 0.2f / 200.0f,              // [Nm/(rad/s)] <sensorless example>
        float vel_integrator_gain = 2.0f / 6.0f;    // [Nm/(turn/s * s)]
        float vel_limit = 2.0f;                     // [turn/s] Infinity to disable.
        float vel_limit_tolerance = 1.2f;           // ratio to vel_lim. Infinity to disable.
        float vel_ramp_rate = 1.0f;                 // [(turn/s) / s]
        float torque_ramp_rate = 0.01f;           // Nm / sec
        bool circular_setpoints = false;
        float circular_setpoint_range = 1.0f;  // Circular range when circular_setpoints is true. [turn]
        float inertia = 0.0f;                         // [A/(count/s^2)]
        float input_filter_bandwidth = 2.0f;          // [1/s]
        float homing_speed = 0.25f;                 // [turn/s]
        Anticogging_t anticogging;
        float gain_scheduling_width = 10.0f;
        bool enable_gain_scheduling = false;
        bool enable_vel_limit = true;
        bool enable_overspeed_error = true;
        bool enable_current_mode_vel_limit = true;  // enable velocity limit in current control mode (requires a valid velocity estimator)
        uint8_t axis_to_mirror = -1;
        float mirror_ratio = 1.0f;
        uint8_t load_encoder_axis = -1;  // default depends on Axis number and is set in load_configuration()

        // custom setters
        Controller* parent;
        void set_input_filter_bandwidth(float value) { input_filter_bandwidth = value; parent->update_filter_gains(); }
    };

    explicit Controller(Config_t& config);
    void reset();
    void set_error(Error error);

    void input_pos_updated();
    bool select_encoder(size_t encoder_num);

    // Trajectory-Planned control
    void move_to_pos(float goal_point);
    void move_incremental(float displacement, bool from_goal_point);

    // TODO: make this more similar to other calibration loops
    void start_anticogging_calibration();
    bool anticogging_calibration(float pos_estimate, float vel_estimate);

    void update_filter_gains();
    bool update(float* torque_setpoint);

    Config_t& config_;
    Axis* axis_ = nullptr; // set by Axis constructor

    Error error_ = ERROR_NONE;

    float* pos_estimate_linear_src_ = nullptr;
    float* pos_estimate_circular_src_ = nullptr;
    bool* pos_estimate_valid_src_ = nullptr;
    float* vel_estimate_src_ = nullptr;
    bool* vel_estimate_valid_src_ = nullptr;
    float* pos_wrap_src_ = nullptr;

    float pos_setpoint_ = 0.0f; // [turns]
    float vel_setpoint_ = 0.0f; // [turn/s]
    // float vel_setpoint = 800.0f; <sensorless example>
    float vel_integrator_torque_ = 0.0f;    // [Nm]
    float torque_setpoint_ = 0.0f;  // [Nm]

    float input_pos_ = 0.0f;     // [turns]
    float input_vel_ = 0.0f;     // [turn/s]
    float input_torque_ = 0.0f;  // [Nm]
    float input_filter_kp_ = 0.0f;
    float input_filter_ki_ = 0.0f;

    bool input_pos_updated_ = false;

    bool trajectory_done_ = true;

    bool anticogging_valid_ = false;

    // custom setters
    void set_input_pos(float value) { input_pos_ = value; input_pos_updated(); }

};

#endif // __CONTROLLER_HPP
<|endoftext|>


<commit_before>
#include "config.h"

// system
#include <iostream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/parametertree.hh>

// dune-helper-tools
#include <dune/helper-tools/common/parametertree.hh>

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[helper-tools.grid.provider.cube]" << std::endl;
    file << "level = 2" << std::endl;
    file << "visualize.grid = rb_grid_provider_cube_grid" << std::endl;
    file << "visualize.msGrid = rb_grid_provider_cube_msGrid" << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);
    // parameter
    const std::string filename = "continuous_galerkin.param";
    ensureParamFile(filename);
    Dune::ParameterTree paramTree = Dune::HelperTools::Common::ParameterTree::init(argc, argv, filename);
    paramTree.report();

    // done
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples.elliptic.continuous_galerkin] added grid provider<commit_after>
#include "config.h"

// system
#include <iostream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/parametertree.hh>

// dune-helper-tools
#include <dune/helper-tools/common/parametertree.hh>
#include <dune/helper-tools/grid/provider/cube.hh>

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[helper-tools.grid.provider.cube]" << std::endl;
    file << "level = 2" << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);
    // parameter
    const std::string filename = "continuous_galerkin.param";
    ensureParamFile(filename);
    Dune::ParameterTree paramTree = Dune::HelperTools::Common::ParameterTree::init(argc, argv, filename);
    // grid
    typedef Dune::HelperTools::Grid::Provider::UnitCube< Dune::GridSelector::GridType > GridProviderType;
    GridProviderType gridProvider(paramTree);
    typedef GridProviderType::GridType GridType;
    GridType& grid = gridProvider.grid();

    // done
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * 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 "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "StdDmaIndication.h"
#include "GeneratedTypes.h"
#include "HdmiDisplayRequestProxy.h"
#include "HdmiDisplayIndicationWrapper.h"
#include "HdmiInternalIndicationWrapper.h"
#include "HdmiInternalRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <sys/mman.h>
#include <ctype.h>
#include "i2chdmi.h"
#include "edid.h"

#define FRAME_COUNT 2
#define MAX_PIXEL 256
#define INCREMENT_PIXEL 2

static HdmiInternalRequestProxy *hdmiInternal;
static HdmiDisplayRequestProxy *device;
static DmaConfigProxy *dma;
static PortalAlloc *portalAlloc[FRAME_COUNT];
static unsigned int ref_srcAlloc[FRAME_COUNT];
static int *dataptr[FRAME_COUNT];
static int frame_index;
static int nlines = 1080;
static int npixels = 1920;
static int fbsize = nlines*npixels*4;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s: ", prefix);
    for (int i = 0; i < 16; i++)
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
    fprintf(stderr, "\n");
}

static void *thread_routine(void *data)
{
    fprintf(stderr, "Calling portalExec\n");
    portalExec(0);
    fprintf(stderr, "portalExec returned ???\n");
    return data;
}

static int corner[] = {0, -1, 0xf00f, 0x0fff};
static int corner_index;
static void fill_pixels(int offset)
{
    int *ptr = dataptr[frame_index];
    for (int line = 0; line < nlines; line++)
      for (int pixel = 0; pixel < npixels; pixel++) {
	int v = ((((MAX_PIXEL *  line) /  nlines)+offset) % MAX_PIXEL) << 16
	       | ((((MAX_PIXEL * pixel) / npixels)+offset) % MAX_PIXEL);
        if (!v)
            v = 1;
        if (line < 20 && pixel < 20)
            v = corner[(corner_index+0) % 4];
        if (line < 30 && pixel > npixels - 40)
            v = corner[(corner_index+1) % 4];
        if (line > nlines - 20 && pixel < 20)
            v = corner[(corner_index+2) % 4];
        if (line > nlines - 30 && pixel > npixels - 40)
            v = corner[(corner_index+3) % 4];
        if (line < 20 && pixel % 20 < 2)
            v = corner[(corner_index+0) % 4];
        if (line % 30 < 2 && pixel > npixels - 40)
            v = corner[(corner_index+1) % 4];
	ptr[line * npixels + pixel] = v;
      }
    corner_index = offset/16;
    dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);
    device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);
    hdmiInternal->setTestPattern(0);
    hdmiInternal->waitForVsync(0);
    frame_index = 1 - frame_index;
}

static int synccount = 0;
static long long totalcount;
static int number;
class HdmiIndication : public HdmiInternalIndicationWrapper {
public:
    HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}
  virtual void vsync ( uint64_t v, uint32_t w ) {
      static int base = 0;

totalcount += v;
number += w;
      fill_pixels(base);
base += INCREMENT_PIXEL;
      if (synccount++ >= 20) {
          synccount = 0;
uint32_t zeros = v & 0xffffffff, pix = v >> 32;
          fprintf(stderr, "[%s] v %llx pix=%x:%d. zero=%x:%d. w=%x:%d.\n", __FUNCTION__,v,pix,pix,zeros,zeros,w,w);
      }
    }
};
class DisplayIndication : public HdmiDisplayIndicationWrapper {
public:
    DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}
    virtual void transferStarted ( uint32_t v ) {
      fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
    }
    virtual void transferFinished ( uint32_t v ) {
      fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
    }
    virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {
	fprintf(stderr, "[%s:%d] count=%d cycles=%d sumcycles=%lld avgcycles=%f\n", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles / count);
    }
};

int main(int argc, const char **argv)
{
    PortalPoller *poller = 0;
    DmaIndicationWrapper *dmaIndication;

    poller = new PortalPoller();
    device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);
    dma = new DmaConfigProxy(IfcNames_DmaConfig);
    dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
    HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);
    HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);
    hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);

    // read out monitor EDID from ADV7511
    struct edid edid;
    init_i2c_hdmi();
    int i2cfd = open("/dev/i2c-0", O_RDWR);
    fprintf(stderr, "Monitor EDID:\n");
    for (int i = 0; i < 256; i++) {
      edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);
      fprintf(stderr, " %02x", edid.raw[i]);
      if ((i % 16) == 15) {
	fprintf(stderr, " ");
	for (int j = i-15; j <= i; j++) {
	  unsigned char c = edid.raw[j];
	  fprintf(stderr, "%c", (isprint(c) && isascii(c)) ? c : '.');
	}
	fprintf(stderr, "\n");
      }
    }
    close(i2cfd);
    parseEdid(edid);

    device->stopFrameBuffer();

    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&thread, &attr, thread_routine, 0);

    int status;
    status = poller->setClockFrequency(0, 100000000, 0);

    for (int i = 0; i < 4; i++) {
      int pixclk = (long)edid.timing[i].pixclk * 10000;
      if ((pixclk > 0) && (pixclk < 170000000)) {
	nlines = edid.timing[i].nlines;    // number of visible lines
	npixels = edid.timing[i].npixels;
	int vblank = edid.timing[i].blines; // number of blanking lines
	int hblank = edid.timing[i].bpixels;
	int vsyncoff = edid.timing[i].vsyncoff; // number of lines in FrontPorch (within blanking)
	int hsyncoff = edid.timing[i].hsyncoff;
	int vsyncwidth = edid.timing[i].vsyncwidth; // width of Sync (within blanking)
	int hsyncwidth = edid.timing[i].hsyncwidth;

	fprintf(stderr, "lines %d, pixels %d, vblank %d, hblank %d, vwidth %d, hwidth %d\n",
             nlines, npixels, vblank, hblank, vsyncwidth, hsyncwidth);
	fprintf(stderr, "Using pixclk %d calc_pixclk %d npixels %d nlines %d\n",
		pixclk,
		60l * (long)(hblank + npixels) * (long)(vblank + nlines),
		npixels, nlines);
	status = poller->setClockFrequency(1, pixclk, 0);
hblank--; // needed on zc702
	hdmiInternal->setDeLine(vsyncoff,           // End of FrontPorch
                                vsyncoff+vsyncwidth,// End of Sync
                                vblank,             // Start of Visible (start of BackPorch)
                                vblank + nlines, vblank + nlines / 2); // End
        hdmiInternal->setDePixel(hsyncoff,
                                hsyncoff+hsyncwidth, hblank,
                                hblank + npixels, hblank + npixels / 2);
	break;
      }
    }

    fbsize = nlines*npixels*4;

    for (int i = 0; i < FRAME_COUNT; i++) {
        int err = dma->alloc(fbsize, &portalAlloc[i]);
        dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);
        memset(dataptr[i], i ? 0xff : 0, fbsize);
        fprintf(stderr, "calling dma->reference\n");
        ref_srcAlloc[i] = dma->reference(portalAlloc[i]);
    }

    fprintf(stderr, "first mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
    sleep(3);
    fprintf(stderr, "Starting frame buffer ref=%d...", ref_srcAlloc[0]);
    fill_pixels(0);
    fprintf(stderr, "done\n");
    while (1) {
      fprintf(stderr, "mem_stats=%10u\n", dma->show_mem_stats(ChannelType_Read));
      sleep(1);
    }
}
<commit_msg>remove warnings about '%lld'<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * 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 "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "StdDmaIndication.h"
#include "GeneratedTypes.h"
#include "HdmiDisplayRequestProxy.h"
#include "HdmiDisplayIndicationWrapper.h"
#include "HdmiInternalIndicationWrapper.h"
#include "HdmiInternalRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <ctype.h>
#include "i2chdmi.h"
#include "edid.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#define FRAME_COUNT 2
#define MAX_PIXEL 256
#define INCREMENT_PIXEL 2

static HdmiInternalRequestProxy *hdmiInternal;
static HdmiDisplayRequestProxy *device;
static DmaConfigProxy *dma;
static PortalAlloc *portalAlloc[FRAME_COUNT];
static unsigned int ref_srcAlloc[FRAME_COUNT];
static int *dataptr[FRAME_COUNT];
static int frame_index;
static int nlines = 1080;
static int npixels = 1920;
static int fbsize = nlines*npixels*4;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s: ", prefix);
    for (int i = 0; i < 16; i++)
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
    fprintf(stderr, "\n");
}

static void *thread_routine(void *data)
{
    fprintf(stderr, "Calling portalExec\n");
    portalExec(0);
    fprintf(stderr, "portalExec returned ???\n");
    return data;
}

static int corner[] = {0, -1, 0xf00f, 0x0fff};
static int corner_index;
static void fill_pixels(int offset)
{
    int *ptr = dataptr[frame_index];
    for (int line = 0; line < nlines; line++)
      for (int pixel = 0; pixel < npixels; pixel++) {
	int v = ((((MAX_PIXEL *  line) /  nlines)+offset) % MAX_PIXEL) << 16
	       | ((((MAX_PIXEL * pixel) / npixels)+offset) % MAX_PIXEL);
        if (!v)
            v = 1;
        if (line < 20 && pixel < 20)
            v = corner[(corner_index+0) % 4];
        if (line < 30 && pixel > npixels - 40)
            v = corner[(corner_index+1) % 4];
        if (line > nlines - 20 && pixel < 20)
            v = corner[(corner_index+2) % 4];
        if (line > nlines - 30 && pixel > npixels - 40)
            v = corner[(corner_index+3) % 4];
        if (line < 20 && pixel % 20 < 2)
            v = corner[(corner_index+0) % 4];
        if (line % 30 < 2 && pixel > npixels - 40)
            v = corner[(corner_index+1) % 4];
	ptr[line * npixels + pixel] = v;
      }
    corner_index = offset/16;
    dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);
    device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);
    hdmiInternal->setTestPattern(0);
    hdmiInternal->waitForVsync(0);
    frame_index = 1 - frame_index;
}

static int synccount = 0;
static long long totalcount;
static int number;
class HdmiIndication : public HdmiInternalIndicationWrapper {
public:
    HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}
  virtual void vsync ( uint64_t v, uint32_t w ) {
      static int base = 0;

totalcount += v;
number += w;
      fill_pixels(base);
base += INCREMENT_PIXEL;
      if (synccount++ >= 20) {
          synccount = 0;
uint32_t zeros = v & 0xffffffff, pix = v >> 32;
          fprintf(stderr, "[%s] v %"PRIx64" pix=%x:%d. zero=%x:%d. w=%x:%d.\n", __FUNCTION__,v,pix,pix,zeros,zeros,w,w);
      }
    }
};
class DisplayIndication : public HdmiDisplayIndicationWrapper {
public:
    DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}
    virtual void transferStarted ( uint32_t v ) {
      fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
    }
    virtual void transferFinished ( uint32_t v ) {
      fprintf(stderr, "[%s:%d] v=%d\n", __FUNCTION__, __LINE__, v);
    }
    virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {
	fprintf(stderr, "[%s:%d] count=%d cycles=%d sumcycles=%"PRIx64" avgcycles=%f\n", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles / count);
    }
};

int main(int argc, const char **argv)
{
    PortalPoller *poller = 0;
    DmaIndicationWrapper *dmaIndication;

    poller = new PortalPoller();
    device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);
    dma = new DmaConfigProxy(IfcNames_DmaConfig);
    dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
    HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);
    HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);
    hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);

    // read out monitor EDID from ADV7511
    struct edid edid;
    init_i2c_hdmi();
    int i2cfd = open("/dev/i2c-0", O_RDWR);
    fprintf(stderr, "Monitor EDID:\n");
    for (int i = 0; i < 256; i++) {
      edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);
      fprintf(stderr, " %02x", edid.raw[i]);
      if ((i % 16) == 15) {
	fprintf(stderr, " ");
	for (int j = i-15; j <= i; j++) {
	  unsigned char c = edid.raw[j];
	  fprintf(stderr, "%c", (isprint(c) && isascii(c)) ? c : '.');
	}
	fprintf(stderr, "\n");
      }
    }
    close(i2cfd);
    parseEdid(edid);

    device->stopFrameBuffer();

    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&thread, &attr, thread_routine, 0);

    int status;
    status = poller->setClockFrequency(0, 100000000, 0);

    for (int i = 0; i < 4; i++) {
      int pixclk = (long)edid.timing[i].pixclk * 10000;
      if ((pixclk > 0) && (pixclk < 170000000)) {
	nlines = edid.timing[i].nlines;    // number of visible lines
	npixels = edid.timing[i].npixels;
	int vblank = edid.timing[i].blines; // number of blanking lines
	int hblank = edid.timing[i].bpixels;
	int vsyncoff = edid.timing[i].vsyncoff; // number of lines in FrontPorch (within blanking)
	int hsyncoff = edid.timing[i].hsyncoff;
	int vsyncwidth = edid.timing[i].vsyncwidth; // width of Sync (within blanking)
	int hsyncwidth = edid.timing[i].hsyncwidth;

	fprintf(stderr, "lines %d, pixels %d, vblank %d, hblank %d, vwidth %d, hwidth %d\n",
             nlines, npixels, vblank, hblank, vsyncwidth, hsyncwidth);
	fprintf(stderr, "Using pixclk %d calc_pixclk %ld npixels %d nlines %d\n",
		pixclk,
		60l * (long)(hblank + npixels) * (long)(vblank + nlines),
		npixels, nlines);
	status = poller->setClockFrequency(1, pixclk, 0);
hblank--; // needed on zc702
	hdmiInternal->setDeLine(vsyncoff,           // End of FrontPorch
                                vsyncoff+vsyncwidth,// End of Sync
                                vblank,             // Start of Visible (start of BackPorch)
                                vblank + nlines, vblank + nlines / 2); // End
        hdmiInternal->setDePixel(hsyncoff,
                                hsyncoff+hsyncwidth, hblank,
                                hblank + npixels, hblank + npixels / 2);
	break;
      }
    }

    fbsize = nlines*npixels*4;

    for (int i = 0; i < FRAME_COUNT; i++) {
        int err = dma->alloc(fbsize, &portalAlloc[i]);
        dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);
        memset(dataptr[i], i ? 0xff : 0, fbsize);
        fprintf(stderr, "calling dma->reference\n");
        ref_srcAlloc[i] = dma->reference(portalAlloc[i]);
    }

    fprintf(stderr, "first mem_stats=%"PRIx64"\n", dma->show_mem_stats(ChannelType_Read));
    sleep(3);
    fprintf(stderr, "Starting frame buffer ref=%d...", ref_srcAlloc[0]);
    fill_pixels(0);
    fprintf(stderr, "done\n");
    while (1) {
      fprintf(stderr, "mem_stats=%"PRIx64"\n", dma->show_mem_stats(ChannelType_Read));
      sleep(1);
    }
}
<|endoftext|>


<commit_before>#include "SteamAudio.hpp"

SteamAudio::SteamAudio() {
    context = nullptr;
    environmentalRenderer = nullptr;
}

SteamAudio::SteamAudio(IPLContext * context, IPLhandle * environment) {

}

SteamAudio::~SteamAudio() {
    if(context != nullptr)
        delete context;
}

void SteamAudio::Process(IPLAudioBuffer input, IPLVector3 * playerPos, IPLVector3 * playerDir, IPLVector3 * playerUp, IPLVector3 * sourcePos, float sourceRadius) {
    // Direct Processing

    // Indirect Processing

    //MixAudio(direct, indirect)

    processedBuffers.push_back(input);

}

void SteamAudio::GetFinalMix(IPLAudioBuffer* finalBuf, uint32_t* numSamples) {
    // No audio is playing, return emptiness, let SoundManager figure it out.
    if (processedBuffers.size() == 0) {
        *numSamples = 0;
        finalBuf = nullptr;
        return;
    }

    // Move the buffers into an array (needed for steam audios mixing)
    IPLAudioBuffer* buffers = new IPLAudioBuffer[processedBuffers.size()];
    for (int i = 0; i < processedBuffers.size(); i++) {
        buffers[i] = processedBuffers[i];
    }

    finalBuf->format = buffers[0].format;
    finalBuf->interleavedBuffer = new float[buffers[0].numSamples];
    finalBuf->numSamples = buffers[0].numSamples;
    iplMixAudioBuffers(processedBuffers.size(), buffers, *finalBuf);
    *numSamples = finalBuf->numSamples;

    // Clean up
    for (IPLAudioBuffer buf : processedBuffers) {
        if (buf.interleavedBuffer != nullptr)
            delete[] buf.interleavedBuffer;
    }
    processedBuffers.clear();
}
<commit_msg>Fix signed/unsigned comparison<commit_after>#include "SteamAudio.hpp"

SteamAudio::SteamAudio() {
    context = nullptr;
    environmentalRenderer = nullptr;
}

SteamAudio::SteamAudio(IPLContext * context, IPLhandle * environment) {

}

SteamAudio::~SteamAudio() {
    if(context != nullptr)
        delete context;
}

void SteamAudio::Process(IPLAudioBuffer input, IPLVector3 * playerPos, IPLVector3 * playerDir, IPLVector3 * playerUp, IPLVector3 * sourcePos, float sourceRadius) {
    // Direct Processing

    // Indirect Processing

    //MixAudio(direct, indirect)

    processedBuffers.push_back(input);

}

void SteamAudio::GetFinalMix(IPLAudioBuffer* finalBuf, uint32_t* numSamples) {
    // No audio is playing, return emptiness, let SoundManager figure it out.
    if (processedBuffers.size() == 0) {
        *numSamples = 0;
        finalBuf = nullptr;
        return;
    }

    // Move the buffers into an array (needed for steam audios mixing)
    IPLAudioBuffer* buffers = new IPLAudioBuffer[processedBuffers.size()];
    for (std::size_t i = 0; i < processedBuffers.size(); i++) {
        buffers[i] = processedBuffers[i];
    }

    finalBuf->format = buffers[0].format;
    finalBuf->interleavedBuffer = new float[buffers[0].numSamples];
    finalBuf->numSamples = buffers[0].numSamples;
    iplMixAudioBuffers(processedBuffers.size(), buffers, *finalBuf);
    *numSamples = finalBuf->numSamples;

    // Clean up
    for (IPLAudioBuffer buf : processedBuffers) {
        if (buf.interleavedBuffer != nullptr)
            delete[] buf.interleavedBuffer;
    }
    processedBuffers.clear();
}
<|endoftext|>


<commit_before>#ifdef __WIN32__
#include <winsock2.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include "network.h"
#include "handler.h"
#include "logging.h"

Network::Network()
{
	sd.listen = -1;
	_errno = 0;
#ifdef __WIN32__
	WSADATA wsa;
	if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
		_errno = WSAGetLastError();
#endif
}

void Network::close()
{
	if (sd.listen != -1)
		::close(sd.listen);
	for (auto h: handlers) {
		h->thread()->join();
		delete h->thread();
		delete h;
	}
}

bool Network::listen()
{
	// Listening on IPv6 will also bind to IPv4 (see flag IPV6_V6ONLY)
	sd.listen = listen6();
	return sd.listen != -1;
}

int Network::listen4()
{
	int flag = 1;
	_errno = 0;
	int sd = ::socket(AF_INET, SOCK_STREAM, 0);
	if (sd == -1) {
		logger->warn("Cannot create IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) == -1) {
		logger->warn("Cannot configure IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(struct sockaddr_in));
	addr.sin_family = AF_INET;
	addr.sin_port = nport();
	addr.sin_addr.s_addr = naddr();
	if (::bind(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		logger->warn("Cannot bind IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (::listen(sd, 16) == -1) {
		logger->warn("Cannot listen on IPv4: {}", strerror(getErrno()));
		goto close;
	}
	return sd;

close:
	if (sd != -1)
		::close(sd);
	_errno = getErrno();
	return -1;
}

int Network::listen6()
{
	int flag = 1;
	_errno = 0;
	int sd = ::socket(AF_INET6, SOCK_STREAM, 0);
	if (sd == -1) {
		logger->warn("Cannot create IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) == -1) {
		logger->warn("Cannot configure IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	struct sockaddr_in6 addr;
	memset(&addr, 0, sizeof(struct sockaddr_in6));
	addr.sin6_family = AF_INET6;
	addr.sin6_port = nport();
	addr.sin6_addr = naddr6();
	if (::bind(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		logger->warn("Cannot bind IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (::listen(sd, 16) == -1) {
		logger->warn("Cannot listen on IPv6: {}", strerror(getErrno()));
		goto close;
	}
	return sd;

close:
	if (sd != -1)
		::close(sd);
	_errno = getErrno();
	return -1;
}

bool Network::process()
{
	logger->info("Network processing started");
	while (true) {
		int s = accept(sd.listen, NULL, 0);
		if (s < 0)
			goto error;
		int flags = 1;
		setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
				(const char *)&flags, sizeof(flags));
		// Start handler process
		Handler *h = new Handler(s, rand());
		std::thread *th = new std::thread(Handler::threadFunc, h);
		h->thread(th);
		handlers.insert(h);
		gc();
	}
	return true;
error:
	_errno = getErrno();
	return false;
}

void Network::gc()
{
	for (auto it = handlers.begin(); it != handlers.end();) {
		auto tmpit = it++;
		if ((*tmpit)->closed()) {
			(*tmpit)->thread()->join();
			delete (*tmpit)->thread();
			delete (*tmpit);
			handlers.erase(tmpit);
		}
	}
}

std::string Network::host(uint32_t addr, uint16_t port)
{
	std::stringstream ss;
	ss << (addr & 0xff) << '.' << ((addr >> 8) & 0xff) << '.'
		<< ((addr >> 16) & 0xff) << '.' << ((addr >> 24) & 0xff)
		<< ':' << ntohs(port);
	return ss.str();
}

std::string Network::saddrtostr(struct sockaddr_in *addr)
{
	return host(addr->sin_addr.s_addr, addr->sin_port);
}

int Network::getErrno()
{
#ifdef __WIN32__
	int e;
	_get_errno(&e);
	return e;
#else
	return errno;
#endif
}
<commit_msg>network: Listening on IPv4 for Windows<commit_after>#ifdef __WIN32__
#include <winsock2.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include "network.h"
#include "handler.h"
#include "logging.h"

Network::Network()
{
	sd.listen = -1;
	_errno = 0;
#ifdef __WIN32__
	WSADATA wsa;
	if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
		_errno = WSAGetLastError();
#endif
}

void Network::close()
{
	if (sd.listen != -1)
		::close(sd.listen);
	for (auto h: handlers) {
		h->thread()->join();
		delete h->thread();
		delete h;
	}
}

bool Network::listen()
{
#ifdef __WIN32__
	sd.listen = listen4();
#else
	// Listening on IPv6 will also bind to IPv4 (see flag IPV6_V6ONLY)
	sd.listen = listen6();
#endif
	return sd.listen != -1;
}

int Network::listen4()
{
	int flag = 1;
	_errno = 0;
	int sd = ::socket(AF_INET, SOCK_STREAM, 0);
	if (sd == -1) {
		logger->warn("Cannot create IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) == -1) {
		logger->warn("Cannot configure IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(struct sockaddr_in));
	addr.sin_family = AF_INET;
	addr.sin_port = nport();
	addr.sin_addr.s_addr = naddr();
	if (::bind(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		logger->warn("Cannot bind IPv4 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (::listen(sd, 16) == -1) {
		logger->warn("Cannot listen on IPv4: {}", strerror(getErrno()));
		goto close;
	}
	return sd;

close:
	if (sd != -1)
		::close(sd);
	_errno = getErrno();
	return -1;
}

int Network::listen6()
{
	int flag = 1;
	_errno = 0;
	int sd = ::socket(AF_INET6, SOCK_STREAM, 0);
	if (sd == -1) {
		logger->warn("Cannot create IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (const char *)&flag, sizeof(int)) == -1) {
		logger->warn("Cannot configure IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	struct sockaddr_in6 addr;
	memset(&addr, 0, sizeof(struct sockaddr_in6));
	addr.sin6_family = AF_INET6;
	addr.sin6_port = nport();
	addr.sin6_addr = naddr6();
	if (::bind(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		logger->warn("Cannot bind IPv6 socket: {}", strerror(getErrno()));
		goto close;
	}
	if (::listen(sd, 16) == -1) {
		logger->warn("Cannot listen on IPv6: {}", strerror(getErrno()));
		goto close;
	}
	return sd;

close:
	if (sd != -1)
		::close(sd);
	_errno = getErrno();
	return -1;
}

bool Network::process()
{
	logger->info("Network processing started");
	while (true) {
		int s = accept(sd.listen, NULL, 0);
		if (s < 0)
			goto error;
		int flags = 1;
		setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
				(const char *)&flags, sizeof(flags));
		// Start handler process
		Handler *h = new Handler(s, rand());
		std::thread *th = new std::thread(Handler::threadFunc, h);
		h->thread(th);
		handlers.insert(h);
		gc();
	}
	return true;
error:
	_errno = getErrno();
	return false;
}

void Network::gc()
{
	for (auto it = handlers.begin(); it != handlers.end();) {
		auto tmpit = it++;
		if ((*tmpit)->closed()) {
			(*tmpit)->thread()->join();
			delete (*tmpit)->thread();
			delete (*tmpit);
			handlers.erase(tmpit);
		}
	}
}

std::string Network::host(uint32_t addr, uint16_t port)
{
	std::stringstream ss;
	ss << (addr & 0xff) << '.' << ((addr >> 8) & 0xff) << '.'
		<< ((addr >> 16) & 0xff) << '.' << ((addr >> 24) & 0xff)
		<< ':' << ntohs(port);
	return ss.str();
}

std::string Network::saddrtostr(struct sockaddr_in *addr)
{
	return host(addr->sin_addr.s_addr, addr->sin_port);
}

int Network::getErrno()
{
#ifdef __WIN32__
	int e;
	_get_errno(&e);
	return e;
#else
	return errno;
#endif
}
<|endoftext|>