<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/window_capturer.h"

#include <assert.h>

#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/win/window_capture_utils.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

namespace {

typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);

// Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if
// error occurs.
std::string Utf16ToUtf8(const WCHAR* str) {
  int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1,
                                     NULL, 0, NULL, NULL);
  if (len_utf8 <= 0)
    return std::string();
  std::string result(len_utf8, '\0');
  int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1,
                               &*(result.begin()), len_utf8, NULL, NULL);
  if (rv != len_utf8)
    assert(false);

  return result;
}

BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {
  WindowCapturer::WindowList* list =
      reinterpret_cast<WindowCapturer::WindowList*>(param);

  // Skip windows that are invisible, minimized, have no title, or are owned,
  // unless they have the app window style set.
  int len = GetWindowTextLength(hwnd);
  HWND owner = GetWindow(hwnd, GW_OWNER);
  LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
  if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||
      (owner && !(exstyle & WS_EX_APPWINDOW))) {
    return TRUE;
  }

  // Skip the Program Manager window and the Start button.
  const size_t kClassLength = 256;
  WCHAR class_name[kClassLength];
  GetClassName(hwnd, class_name, kClassLength);
  // Skip Program Manager window and the Start button. This is the same logic
  // that's used in Win32WindowPicker in libjingle. Consider filtering other
  // windows as well (e.g. toolbars).
  if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0)
    return TRUE;

  WindowCapturer::Window window;
  window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);

  const size_t kTitleLength = 500;
  WCHAR window_title[kTitleLength];
  // Truncate the title if it's longer than kTitleLength.
  GetWindowText(hwnd, window_title, kTitleLength);
  window.title = Utf16ToUtf8(window_title);

  // Skip windows when we failed to convert the title or it is empty.
  if (window.title.empty())
    return TRUE;

  list->push_back(window);

  return TRUE;
}

class WindowCapturerWin : public WindowCapturer {
 public:
  WindowCapturerWin();
  virtual ~WindowCapturerWin();

  // WindowCapturer interface.
  virtual bool GetWindowList(WindowList* windows) OVERRIDE;
  virtual bool SelectWindow(WindowId id) OVERRIDE;
  virtual bool BringSelectedWindowToFront() OVERRIDE;

  // DesktopCapturer interface.
  virtual void Start(Callback* callback) OVERRIDE;
  virtual void Capture(const DesktopRegion& region) OVERRIDE;

 private:
  bool IsAeroEnabled();

  Callback* callback_;

  // HWND and HDC for the currently selected window or NULL if window is not
  // selected.
  HWND window_;

  // dwmapi.dll is used to determine if desktop compositing is enabled.
  HMODULE dwmapi_library_;
  DwmIsCompositionEnabledFunc is_composition_enabled_func_;

  DesktopSize previous_size_;

  DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);
};

WindowCapturerWin::WindowCapturerWin()
    : callback_(NULL),
      window_(NULL) {
  // Try to load dwmapi.dll dynamically since it is not available on XP.
  dwmapi_library_ = LoadLibrary(L"dwmapi.dll");
  if (dwmapi_library_) {
    is_composition_enabled_func_ =
        reinterpret_cast<DwmIsCompositionEnabledFunc>(
            GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled"));
    assert(is_composition_enabled_func_);
  } else {
    is_composition_enabled_func_ = NULL;
  }
}

WindowCapturerWin::~WindowCapturerWin() {
  if (dwmapi_library_)
    FreeLibrary(dwmapi_library_);
}

bool WindowCapturerWin::IsAeroEnabled() {
  BOOL result = FALSE;
  if (is_composition_enabled_func_)
    is_composition_enabled_func_(&result);
  return result != FALSE;
}

bool WindowCapturerWin::GetWindowList(WindowList* windows) {
  WindowList result;
  LPARAM param = reinterpret_cast<LPARAM>(&result);
  if (!EnumWindows(&WindowsEnumerationHandler, param))
    return false;
  windows->swap(result);
  return true;
}

bool WindowCapturerWin::SelectWindow(WindowId id) {
  HWND window = reinterpret_cast<HWND>(id);
  if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))
    return false;
  window_ = window;
  previous_size_.set(0, 0);
  return true;
}

bool WindowCapturerWin::BringSelectedWindowToFront() {
  if (!window_)
    return false;

  if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))
    return false;

  return SetForegroundWindow(window_) != 0;
}

void WindowCapturerWin::Start(Callback* callback) {
  assert(!callback_);
  assert(callback);

  callback_ = callback;
}

void WindowCapturerWin::Capture(const DesktopRegion& region) {
  if (!window_) {
    LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  // Stop capturing if the window has been closed or hidden.
  if (!IsWindow(window_) || !IsWindowVisible(window_)) {
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  DesktopRect original_rect;
  DesktopRect cropped_rect;
  if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {
    LOG(LS_WARNING) << "Failed to get window info: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  HDC window_dc = GetWindowDC(window_);
  if (!window_dc) {
    LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(
      cropped_rect.size(), NULL, window_dc));
  if (!frame.get()) {
    ReleaseDC(window_, window_dc);
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  HDC mem_dc = CreateCompatibleDC(window_dc);
  HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());
  BOOL result = FALSE;

  // When desktop composition (Aero) is enabled each window is rendered to a
  // private buffer allowing BitBlt() to get the window content even if the
  // window is occluded. PrintWindow() is slower but lets rendering the window
  // contents to an off-screen device context when Aero is not available.
  // PrintWindow() is not supported by some applications.
  //
  // If Aero is enabled, we prefer BitBlt() because it's faster and avoids
  // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may
  // render occluding windows on top of the desired window.
  //
  // When composition is enabled the DC returned by GetWindowDC() doesn't always
  // have window frame rendered correctly. Windows renders it only once and then
  // caches the result between captures. We hack it around by calling
  // PrintWindow() whenever window size changes, including the first time of
  // capturing - it somehow affects what we get from BitBlt() on the subsequent
  // captures.

  if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {
    result = PrintWindow(window_, mem_dc, 0);
  }

  // Aero is enabled or PrintWindow() failed, use BitBlt.
  if (!result) {
    result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),
                    window_dc,
                    cropped_rect.left() - original_rect.left(),
                    cropped_rect.top() - original_rect.top(),
                    SRCCOPY);
  }

  SelectObject(mem_dc, previous_object);
  DeleteDC(mem_dc);
  ReleaseDC(window_, window_dc);

  previous_size_ = frame->size();

  frame->mutable_updated_region()->SetRect(
      DesktopRect::MakeSize(frame->size()));

  if (!result) {
    LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed.";
    frame.reset();
  }

  callback_->OnCaptureCompleted(frame.release());
}

}  // namespace

// static
WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {
  return new WindowCapturerWin();
}

}  // namespace webrtc
<commit_msg>Remove trailing null character from std::string<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/window_capturer.h"

#include <assert.h>

#include "webrtc/base/win32.h"
#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/win/window_capture_utils.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

namespace {

typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);

BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {
  WindowCapturer::WindowList* list =
      reinterpret_cast<WindowCapturer::WindowList*>(param);

  // Skip windows that are invisible, minimized, have no title, or are owned,
  // unless they have the app window style set.
  int len = GetWindowTextLength(hwnd);
  HWND owner = GetWindow(hwnd, GW_OWNER);
  LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
  if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||
      (owner && !(exstyle & WS_EX_APPWINDOW))) {
    return TRUE;
  }

  // Skip the Program Manager window and the Start button.
  const size_t kClassLength = 256;
  WCHAR class_name[kClassLength];
  GetClassName(hwnd, class_name, kClassLength);
  // Skip Program Manager window and the Start button. This is the same logic
  // that's used in Win32WindowPicker in libjingle. Consider filtering other
  // windows as well (e.g. toolbars).
  if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0)
    return TRUE;

  WindowCapturer::Window window;
  window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);

  const size_t kTitleLength = 500;
  WCHAR window_title[kTitleLength];
  // Truncate the title if it's longer than kTitleLength.
  GetWindowText(hwnd, window_title, kTitleLength);
  window.title = rtc::ToUtf8(window_title);

  // Skip windows when we failed to convert the title or it is empty.
  if (window.title.empty())
    return TRUE;

  list->push_back(window);

  return TRUE;
}

class WindowCapturerWin : public WindowCapturer {
 public:
  WindowCapturerWin();
  virtual ~WindowCapturerWin();

  // WindowCapturer interface.
  virtual bool GetWindowList(WindowList* windows) OVERRIDE;
  virtual bool SelectWindow(WindowId id) OVERRIDE;
  virtual bool BringSelectedWindowToFront() OVERRIDE;

  // DesktopCapturer interface.
  virtual void Start(Callback* callback) OVERRIDE;
  virtual void Capture(const DesktopRegion& region) OVERRIDE;

 private:
  bool IsAeroEnabled();

  Callback* callback_;

  // HWND and HDC for the currently selected window or NULL if window is not
  // selected.
  HWND window_;

  // dwmapi.dll is used to determine if desktop compositing is enabled.
  HMODULE dwmapi_library_;
  DwmIsCompositionEnabledFunc is_composition_enabled_func_;

  DesktopSize previous_size_;

  DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);
};

WindowCapturerWin::WindowCapturerWin()
    : callback_(NULL),
      window_(NULL) {
  // Try to load dwmapi.dll dynamically since it is not available on XP.
  dwmapi_library_ = LoadLibrary(L"dwmapi.dll");
  if (dwmapi_library_) {
    is_composition_enabled_func_ =
        reinterpret_cast<DwmIsCompositionEnabledFunc>(
            GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled"));
    assert(is_composition_enabled_func_);
  } else {
    is_composition_enabled_func_ = NULL;
  }
}

WindowCapturerWin::~WindowCapturerWin() {
  if (dwmapi_library_)
    FreeLibrary(dwmapi_library_);
}

bool WindowCapturerWin::IsAeroEnabled() {
  BOOL result = FALSE;
  if (is_composition_enabled_func_)
    is_composition_enabled_func_(&result);
  return result != FALSE;
}

bool WindowCapturerWin::GetWindowList(WindowList* windows) {
  WindowList result;
  LPARAM param = reinterpret_cast<LPARAM>(&result);
  if (!EnumWindows(&WindowsEnumerationHandler, param))
    return false;
  windows->swap(result);
  return true;
}

bool WindowCapturerWin::SelectWindow(WindowId id) {
  HWND window = reinterpret_cast<HWND>(id);
  if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))
    return false;
  window_ = window;
  previous_size_.set(0, 0);
  return true;
}

bool WindowCapturerWin::BringSelectedWindowToFront() {
  if (!window_)
    return false;

  if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))
    return false;

  return SetForegroundWindow(window_) != 0;
}

void WindowCapturerWin::Start(Callback* callback) {
  assert(!callback_);
  assert(callback);

  callback_ = callback;
}

void WindowCapturerWin::Capture(const DesktopRegion& region) {
  if (!window_) {
    LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  // Stop capturing if the window has been closed or hidden.
  if (!IsWindow(window_) || !IsWindowVisible(window_)) {
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  DesktopRect original_rect;
  DesktopRect cropped_rect;
  if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {
    LOG(LS_WARNING) << "Failed to get window info: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  HDC window_dc = GetWindowDC(window_);
  if (!window_dc) {
    LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError();
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(
      cropped_rect.size(), NULL, window_dc));
  if (!frame.get()) {
    ReleaseDC(window_, window_dc);
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  HDC mem_dc = CreateCompatibleDC(window_dc);
  HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());
  BOOL result = FALSE;

  // When desktop composition (Aero) is enabled each window is rendered to a
  // private buffer allowing BitBlt() to get the window content even if the
  // window is occluded. PrintWindow() is slower but lets rendering the window
  // contents to an off-screen device context when Aero is not available.
  // PrintWindow() is not supported by some applications.
  //
  // If Aero is enabled, we prefer BitBlt() because it's faster and avoids
  // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may
  // render occluding windows on top of the desired window.
  //
  // When composition is enabled the DC returned by GetWindowDC() doesn't always
  // have window frame rendered correctly. Windows renders it only once and then
  // caches the result between captures. We hack it around by calling
  // PrintWindow() whenever window size changes, including the first time of
  // capturing - it somehow affects what we get from BitBlt() on the subsequent
  // captures.

  if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {
    result = PrintWindow(window_, mem_dc, 0);
  }

  // Aero is enabled or PrintWindow() failed, use BitBlt.
  if (!result) {
    result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),
                    window_dc,
                    cropped_rect.left() - original_rect.left(),
                    cropped_rect.top() - original_rect.top(),
                    SRCCOPY);
  }

  SelectObject(mem_dc, previous_object);
  DeleteDC(mem_dc);
  ReleaseDC(window_, window_dc);

  previous_size_ = frame->size();

  frame->mutable_updated_region()->SetRect(
      DesktopRect::MakeSize(frame->size()));

  if (!result) {
    LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed.";
    frame.reset();
  }

  callback_->OnCaptureCompleted(frame.release());
}

}  // namespace

// static
WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {
  return new WindowCapturerWin();
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
	int a[] = {1, 2, 4, 5, 6};

	int size = sizeof(a)/sizeof(a[0]);
	int x1 = a[0], x2 = 1;
	for (int i = 1; i < size; ++i)
	{
		x1 ^= a[i];
	}
	for (int i = 2; i <= size + 1; ++i)
	{
		x2 ^= i;
	}
	cout<<(x1^x2)<<endl;

	return 0;
}<commit_msg>two approaches :sunglasses:<commit_after>#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
	int a[] = {1, 2, 4, 5, 6};

	int size = sizeof(a)/sizeof(a[0]);
	/* APPROACH 1*/
	// int x1 = a[0], x2 = 1;
	// for (int i = 1; i < size; ++i)
	// {
	// 	x1 ^= a[i];
	// }
	// for (int i = 2; i <= size + 1; ++i)
	// {
	// 	x2 ^= i;
	// }
	// cout<<(x1^x2)<<endl;

	/* APPROACH 2*/

	int sum = (size+1)*(size +2)/2;
	int temp = 0;

	for (int i = 0; i < size; ++i)
	{
		temp += a[i];
	}
	cout<<sum - temp;

	return 0;
}<|endoftext|>


<commit_before>//
//  Video.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 14/04/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "Video.hpp"

using namespace AppleII::Video;

namespace {

struct ScaledByteFiller {
	ScaledByteFiller() {
		VideoBase::setup_tables();
	}
} throwaway;

}

VideoBase::VideoBase() :
	crt_(new Outputs::CRT::CRT(455, 1, Outputs::CRT::DisplayType::NTSC60, 1)) {

	// Set a composite sampling function that assumes 1bpp input, and uses just 7 bits per byte.
	crt_->set_composite_sampling_function(
		"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)"
		"{"
			"uint texValue = texture(sampler, coordinate).r;"
			"texValue <<= int(icoordinate.x) % 7;"
			"return float(texValue & 64u);"
		"}");
	crt_->set_integer_coordinate_multiplier(7.0f);

	// Show only the centre 75% of the TV frame.
	crt_->set_video_signal(Outputs::CRT::VideoSignal::Composite);
	crt_->set_visible_area(Outputs::CRT::Rect(0.115f, 0.117f, 0.77f, 0.77f));
}

Outputs::CRT::CRT *VideoBase::get_crt() {
	return crt_.get();
}

uint16_t VideoBase::scaled_byte[256];
uint16_t VideoBase::low_resolution_patterns[2][16];

void VideoBase::setup_tables() {
	for(int c = 0; c < 128; ++c) {
		const uint16_t value =
			((c & 0x01) ? 0x0003 : 0x0000) |
			((c & 0x02) ? 0x000c : 0x0000) |
			((c & 0x04) ? 0x0030 : 0x0000) |
			((c & 0x08) ? 0x0140 : 0x0000) |
			((c & 0x10) ? 0x0600 : 0x0000) |
			((c & 0x20) ? 0x1800 : 0x0000) |
			((c & 0x40) ? 0x6000 : 0x0000);

		uint8_t *const table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);
		table_entry[0] = static_cast<uint8_t>(value >> 8);
		table_entry[1] = static_cast<uint8_t>(value & 0xff);
	}
	for(int c = 128; c < 256; ++c) {
		uint8_t *const source_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c & 0x7f]);
		uint8_t *const destination_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);

		destination_table_entry[0] = static_cast<uint8_t>(source_table_entry[0] >> 1);
		destination_table_entry[1] = static_cast<uint8_t>((source_table_entry[1] >> 1) | ((source_table_entry[0]&1) << 6));
	}

	for(int c = 0; c < 16; ++c) {
		// Produce the whole 28-bit pattern that would cover two bytes.
		int pattern = 0;
		for(int l = 0; l < 7; ++l) {
			pattern <<= 4;
			pattern |= c;
		}

		// Pack that 28-bit pattern into the appropriate look-up tables.
		uint8_t *const left_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[0][c]);
		uint8_t *const right_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[1][c]);
		left_entry[0] = static_cast<uint8_t>(pattern >> 21);
		left_entry[1] = static_cast<uint8_t>(pattern >> 14);
		right_entry[0] = static_cast<uint8_t>(pattern >> 7);
		right_entry[1] = static_cast<uint8_t>(pattern);
	}

	printf("");
}

void VideoBase::set_graphics_mode() {
	use_graphics_mode_ = true;
}

void VideoBase::set_text_mode() {
	use_graphics_mode_ = false;
}

void VideoBase::set_mixed_mode(bool mixed_mode) {
	mixed_mode_ = mixed_mode;
}

void VideoBase::set_video_page(int page) {
	video_page_ = page;
}

void VideoBase::set_low_resolution() {
	graphics_mode_ = GraphicsMode::LowRes;
}

void VideoBase::set_high_resolution() {
	graphics_mode_ = GraphicsMode::HighRes;
}

void VideoBase::set_character_rom(const std::vector<uint8_t> &character_rom) {
	character_rom_ = character_rom;
}
<commit_msg>Reverses bit order of graphics stream; apparently the ROM is backwards.<commit_after>//
//  Video.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 14/04/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "Video.hpp"

using namespace AppleII::Video;

namespace {

struct ScaledByteFiller {
	ScaledByteFiller() {
		VideoBase::setup_tables();
	}
} throwaway;

}

VideoBase::VideoBase() :
	crt_(new Outputs::CRT::CRT(455, 1, Outputs::CRT::DisplayType::NTSC60, 1)) {

	// Set a composite sampling function that assumes 1bpp input, and uses just 7 bits per byte.
	crt_->set_composite_sampling_function(
		"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)"
		"{"
			"uint texValue = texture(sampler, coordinate).r;"
			"texValue >>= int(icoordinate.x) % 7;"
			"return float(texValue & 1u);"
		"}");
	crt_->set_integer_coordinate_multiplier(7.0f);

	// Show only the centre 75% of the TV frame.
	crt_->set_video_signal(Outputs::CRT::VideoSignal::Composite);
	crt_->set_visible_area(Outputs::CRT::Rect(0.115f, 0.117f, 0.77f, 0.77f));
}

Outputs::CRT::CRT *VideoBase::get_crt() {
	return crt_.get();
}

uint16_t VideoBase::scaled_byte[256];
uint16_t VideoBase::low_resolution_patterns[2][16];

void VideoBase::setup_tables() {
	for(int c = 0; c < 128; ++c) {
		const uint16_t value =
			((c & 0x01) ? 0x0003 : 0x0000) |
			((c & 0x02) ? 0x000c : 0x0000) |
			((c & 0x04) ? 0x0030 : 0x0000) |
			((c & 0x08) ? 0x0140 : 0x0000) |
			((c & 0x10) ? 0x0600 : 0x0000) |
			((c & 0x20) ? 0x1800 : 0x0000) |
			((c & 0x40) ? 0x6000 : 0x0000);

		uint8_t *const table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);
		table_entry[0] = static_cast<uint8_t>(value & 0xff);
		table_entry[1] = static_cast<uint8_t>(value >> 8);
	}
	for(int c = 128; c < 256; ++c) {
		uint8_t *const source_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c & 0x7f]);
		uint8_t *const destination_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);

		destination_table_entry[0] = static_cast<uint8_t>(source_table_entry[0] << 1);
		destination_table_entry[1] = static_cast<uint8_t>((source_table_entry[1] << 1) | (source_table_entry[0] >> 6));
	}

	for(int c = 0; c < 16; ++c) {
		// Produce the whole 28-bit pattern that would cover two columns.
		const int reversed_c = ((c&0x1) ? 0x8 : 0x0) | ((c&0x2) ? 0x4 : 0x0) | ((c&0x4) ? 0x2 : 0x0) | ((c&0x8) ? 0x1 : 0x0);
		int pattern = 0;
		for(int l = 0; l < 7; ++l) {
			pattern <<= 4;
			pattern |= reversed_c;
		}

		// Pack that 28-bit pattern into the appropriate look-up tables.
		uint8_t *const left_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[0][c]);
		uint8_t *const right_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[1][c]);
		left_entry[0] = static_cast<uint8_t>(pattern);;
		left_entry[1] = static_cast<uint8_t>(pattern >> 7);
		right_entry[0] = static_cast<uint8_t>(pattern >> 14);
		right_entry[1] = static_cast<uint8_t>(pattern >> 21);
	}

	printf("");
}

void VideoBase::set_graphics_mode() {
	use_graphics_mode_ = true;
}

void VideoBase::set_text_mode() {
	use_graphics_mode_ = false;
}

void VideoBase::set_mixed_mode(bool mixed_mode) {
	mixed_mode_ = mixed_mode;
}

void VideoBase::set_video_page(int page) {
	video_page_ = page;
}

void VideoBase::set_low_resolution() {
	graphics_mode_ = GraphicsMode::LowRes;
}

void VideoBase::set_high_resolution() {
	graphics_mode_ = GraphicsMode::HighRes;
}

void VideoBase::set_character_rom(const std::vector<uint8_t> &character_rom) {
	character_rom_ = character_rom;
	for(auto &byte : character_rom_) {
		byte =
			((byte & 0x40) ? 0x01 : 0x00) |
			((byte & 0x20) ? 0x02 : 0x00) |
			((byte & 0x10) ? 0x04 : 0x00) |
			((byte & 0x08) ? 0x08 : 0x00) |
			((byte & 0x04) ? 0x10 : 0x00) |
			((byte & 0x02) ? 0x20 : 0x00) |
			((byte & 0x01) ? 0x40 : 0x00) |
			(byte & 0x80);
	}
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Tobias Leibner

//# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
//# define DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING 1

#include "main.hxx"

#if HAVE_DUNE_GRID
# if HAVE_ALUGRID
#   include <dune/grid/alugrid.hh>
# endif
# include <dune/grid/yaspgrid.hh>

# include <dune/stuff/common/type_utils.hh>
# include <dune/stuff/grid/periodicview.hh>
# include <dune/stuff/grid/provider/interface.hh>
# include <dune/stuff/grid/provider/cube.hh>

using namespace Dune;
using namespace Stuff;

# define YASPGRIDS \
    YaspGrid< 1 > \
  , YaspGrid< 2 > \
  , YaspGrid< 3 >

# if HAVE_ALUGRID
#   define ALUCUBEGRIDS \
    ALUGrid< 2, 2, cube, nonconforming > \
  , ALUGrid< 3, 3, cube, nonconforming >

#   define ALUSIMPLEXGRIDS \
    ALUGrid< 2, 2, simplex, conforming > \
  , ALUGrid< 3, 3, simplex, conforming >
# endif // HAVE_ALUGRID

template< class GridImp >
struct PeriodicViewTestCube
    : public testing::Test
{
  typedef GridImp                                                       GridType;
  typedef typename GridType::ctype                                      ctype;
  typedef typename GridType::template Codim< 0 >::Geometry              GeometryType;
  typedef Dune::Stuff::Grid::Providers::template Cube< GridType >       GridProviderType;
  typedef typename GridType::LeafGridView                               GridViewType;
  typedef typename GridViewType::IndexSet                               IndexSet;
  typedef typename Dune::Stuff::Grid::template PeriodicGridView< GridViewType >      PeriodicGridViewType;
  typedef typename PeriodicGridViewType::template Codim< 0 >::Entity    EntityType;
  typedef typename PeriodicGridViewType::template Codim< 0 >::Iterator  EntityIteratorType;
  typedef typename Dune::Stuff::Grid::template PeriodicIntersectionIterator< GridViewType >   PeriodicIntersectionIteratorType;
  typedef typename Dune::Stuff::Grid::template PeriodicIntersection< GridViewType >           PeriodicIntersectionType;
  typedef typename GridViewType::CollectiveCommunication  CollectiveCommunication;
  static const size_t dimDomain = GridViewType::dimension;

  void check(const bool is_simplex) {
    const bool is_cube = !is_simplex;
    GridProviderType grid_provider = *(GridProviderType::create());
    const std::shared_ptr< const GridType > grid = grid_provider.grid_ptr();
    const GridViewType grid_view = grid->leafGridView();
    const GridViewType& grid_view_ref = grid_view;

    std::bitset< dimDomain > periodic_directions;
    //create PeriodicGridviewType that actually is not periodic
    const PeriodicGridViewType non_periodic_grid_view(grid_view_ref, periodic_directions);
    //create PeriodicGridviewType that is periodic only in x-direction
    periodic_directions[0] = 1;
    const PeriodicGridViewType partially_periodic_grid_view(grid_view_ref, periodic_directions);
    //create PeriodicGridviewType that is periodic only in all directions
    periodic_directions.set();
    const PeriodicGridViewType fully_periodic_grid_view(grid_view_ref, periodic_directions);

    std::vector< const PeriodicGridViewType* > periodic_grid_view_vector(3);
    periodic_grid_view_vector[0] = &non_periodic_grid_view;
    periodic_grid_view_vector[1] = &partially_periodic_grid_view;
    periodic_grid_view_vector[2] = &fully_periodic_grid_view;

    for (size_t variant = 0; variant <= 2; ++variant) {
      const PeriodicGridViewType periodic_grid_view = *(periodic_grid_view_vector[variant]);

      // check interface
      const GridType& DUNE_UNUSED(test_grid) = periodic_grid_view.grid();
      const IndexSet& DUNE_UNUSED(test_indexSet) = periodic_grid_view.indexSet();
      const int codim0_size = periodic_grid_view.size(0);
      EXPECT_EQ(codim0_size, grid_view.size(0));
      if (dimDomain == 1)
        EXPECT_EQ(codim0_size, int(8));
      if (dimDomain == 2 && is_cube)
        EXPECT_EQ(codim0_size, int(8*8));
      if (dimDomain == 2 && is_simplex)
        EXPECT_EQ(codim0_size, int(2*8*8));
      if (dimDomain == 3 && is_cube)
        EXPECT_EQ(codim0_size, int(8*8*8));
      if (dimDomain == 3 && is_simplex)
        EXPECT_EQ(codim0_size, int(6*8*8*8));
      EXPECT_EQ(periodic_grid_view.size(Dune::cube), grid_view.size(Dune::cube));
      EXPECT_EQ(periodic_grid_view.size(Dune::simplex), grid_view.size(Dune::simplex));
      EXPECT_EQ(periodic_grid_view.overlapSize(0), grid_view.overlapSize(0));
      EXPECT_EQ(periodic_grid_view.overlapSize(1), grid_view.overlapSize(1));
      EXPECT_EQ(periodic_grid_view.ghostSize(0), grid_view.ghostSize(0));
      EXPECT_EQ(periodic_grid_view.ghostSize(1), grid_view.ghostSize(1));
      const CollectiveCommunication& DUNE_UNUSED(test_comm) = periodic_grid_view.comm();

      size_t neighbor_count = 0;
      size_t boundary_count = 0;
      size_t periodic_count = 0;
      // iterate over all entities
      const EntityIteratorType it_end = periodic_grid_view.template end< 0 >();
      for (EntityIteratorType it = periodic_grid_view.template begin< 0 >(); it != it_end; ++it) {
        const EntityType& entity = *it;
        EXPECT_TRUE(periodic_grid_view.contains(entity));
        // iterate over all intersections on current entity
        const PeriodicIntersectionIteratorType i_it_end = periodic_grid_view.iend(entity);
        for (PeriodicIntersectionIteratorType i_it = periodic_grid_view.ibegin(entity); i_it != i_it_end; ++i_it) {
          const PeriodicIntersectionType& intersection = *i_it;
          if (intersection.neighbor()) {
            ++neighbor_count;
            const auto outside = *(intersection.outside());
            //find corresponding intersection in outside
            const auto index_in_outside = intersection.indexInOutside();
            const PeriodicIntersectionType* intersection_in_outside = periodic_grid_view.ibegin(outside).operator->();
            const PeriodicIntersectionIteratorType i_it_outside_end = periodic_grid_view.iend(outside);
            for (PeriodicIntersectionIteratorType i_it_outside = periodic_grid_view.ibegin(outside); i_it_outside != i_it_outside_end; ++i_it_outside) {
              const PeriodicIntersectionType* outside_intersection = i_it_outside.operator->();
              if (outside_intersection->indexInInside() == index_in_outside) {
                intersection_in_outside = outside_intersection;
              }
            }
            // check outside_intersection coords
            const auto coords_in_outside = intersection.geometryInOutside().center();
            const auto coords_in_outside_2 = intersection_in_outside->geometryInInside().center();
            EXPECT_TRUE(Dune::Stuff::Common::FloatCmp::eq(coords_in_outside, coords_in_outside_2));
            // check global intersection coords in periodic case
            const auto global_intersection_coords = intersection.geometry().center();
            const auto global_outside_intersection_coords = (*intersection_in_outside).geometry().center();
            size_t coord_difference_count = 0;
            size_t differing_coordinate;
            for (size_t ii = 0; ii < dimDomain; ++ii) {
              if (Dune::Stuff::Common::FloatCmp::ne(global_outside_intersection_coords[ii], global_intersection_coords[ii])) {
                ++coord_difference_count;
                differing_coordinate = ii;
              }
            }
            if (intersection.is_periodic()) {
              EXPECT_EQ(size_t(1), coord_difference_count);
              EXPECT_TRUE((Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(1)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(0)))
                          || (Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(0)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(1))));
              ++periodic_count;
              if (variant == 1)
                EXPECT_EQ(size_t(0), differing_coordinate);
            }
          }
          if (intersection.boundary()) {
            ++boundary_count;
            EXPECT_FALSE(intersection.is_periodic());
            EXPECT_FALSE(intersection.neighbor());
          }
        }
      }

      if (dimDomain == 1) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*7),neighbor_count);
          EXPECT_EQ(size_t(2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*7+2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*7+2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2), periodic_count);
        }
      }
      if (dimDomain == 2 && is_cube) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*8*7),neighbor_count);
          EXPECT_EQ(size_t(2*8*2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8),neighbor_count);
          EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);
          EXPECT_EQ(size_t(2*8), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8*2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*8*2), periodic_count);
        }
      }
      if (dimDomain == 2 && is_simplex) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(2*8*2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);
          EXPECT_EQ(size_t(2*8), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8*2 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*8*2), periodic_count);
        }
      }
      if (dimDomain == 3 && is_cube) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*3*7*64),neighbor_count);
          EXPECT_EQ(size_t(6*64), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*3*7*64 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(6*64 - 2*64), boundary_count);
          EXPECT_EQ(size_t(2*64), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*3*7*64 + 6*64),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(6*64), periodic_count);
        }
      }
      if (dimDomain == 3 && is_simplex) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(2*6*64), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*2*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(2*6*64 - 2*2*64), boundary_count);
          EXPECT_EQ(size_t(2*2*64), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*6*64), periodic_count);
        }
      }
    }
  }
};

template< class GridImp >
struct PeriodicViewTestSimplex
  : public PeriodicViewTestCube< GridImp >
{};

typedef testing::Types< YASPGRIDS
# if HAVE_ALUGRID
                      , ALUCUBEGRIDS
# endif
                      > CubeGridTypes;

typedef testing::Types<
# if HAVE_ALUGRID
                        ALUSIMPLEXGRIDS
# endif
                      > SimplexGridTypes;

TYPED_TEST_CASE(PeriodicViewTestCube, CubeGridTypes);
TYPED_TEST(PeriodicViewTestCube, checkcube)
{
  this->check(false);
}

TYPED_TEST_CASE(PeriodicViewTestSimplex, SimplexGridTypes);
TYPED_TEST(PeriodicViewTestSimplex, checksimplex)
{
  this->check(true);
}

#else // HAVE_DUNE_GRID

TEST(DISABLED_CubeGridProvider, is_default_creatable) {}
TEST(DISABLED_CubeGridProvider, fulfills_const_interface) {}
TEST(DISABLED_CubeGridProvider, is_visualizable) {}

#endif // HAVE_DUNE_GRID

<commit_msg>[test.grid_periodicview] get intersection by value<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Tobias Leibner

//# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
//# define DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING 1

#include "main.hxx"

#if HAVE_DUNE_GRID
# if HAVE_ALUGRID
#   include <dune/grid/alugrid.hh>
# endif
# include <dune/grid/yaspgrid.hh>

# include <dune/stuff/common/type_utils.hh>
# include <dune/stuff/grid/periodicview.hh>
# include <dune/stuff/grid/provider/interface.hh>
# include <dune/stuff/grid/provider/cube.hh>

using namespace Dune;
using namespace Stuff;

# define YASPGRIDS \
    YaspGrid< 1 > \
  , YaspGrid< 2 > \
  , YaspGrid< 3 >

# if HAVE_ALUGRID
#   define ALUCUBEGRIDS \
    ALUGrid< 2, 2, cube, nonconforming > \
  , ALUGrid< 3, 3, cube, nonconforming >

#   define ALUSIMPLEXGRIDS \
    ALUGrid< 2, 2, simplex, conforming > \
  , ALUGrid< 3, 3, simplex, conforming >
# endif // HAVE_ALUGRID

template< class GridImp >
struct PeriodicViewTestCube
    : public testing::Test
{
  typedef GridImp                                                       GridType;
  typedef typename GridType::ctype                                      ctype;
  typedef typename GridType::template Codim< 0 >::Geometry              GeometryType;
  typedef Dune::Stuff::Grid::Providers::template Cube< GridType >       GridProviderType;
  typedef typename GridType::LeafGridView                               GridViewType;
  typedef typename GridViewType::IndexSet                               IndexSet;
  typedef typename Dune::Stuff::Grid::template PeriodicGridView< GridViewType >      PeriodicGridViewType;
  typedef typename PeriodicGridViewType::template Codim< 0 >::Entity    EntityType;
  typedef typename PeriodicGridViewType::template Codim< 0 >::Iterator  EntityIteratorType;
  typedef typename Dune::Stuff::Grid::template PeriodicIntersectionIterator< GridViewType >   PeriodicIntersectionIteratorType;
  typedef typename Dune::Stuff::Grid::template PeriodicIntersection< GridViewType >           PeriodicIntersectionType;
  typedef typename GridViewType::CollectiveCommunication  CollectiveCommunication;
  static const size_t dimDomain = GridViewType::dimension;

  void check(const bool is_simplex) {
    const bool is_cube = !is_simplex;
    GridProviderType grid_provider = *(GridProviderType::create());
    const std::shared_ptr< const GridType > grid = grid_provider.grid_ptr();
    const GridViewType grid_view = grid->leafGridView();
    const GridViewType& grid_view_ref = grid_view;

    std::bitset< dimDomain > periodic_directions;
    //create PeriodicGridviewType that actually is not periodic
    const PeriodicGridViewType non_periodic_grid_view(grid_view_ref, periodic_directions);
    //create PeriodicGridviewType that is periodic only in x-direction
    periodic_directions[0] = 1;
    const PeriodicGridViewType partially_periodic_grid_view(grid_view_ref, periodic_directions);
    //create PeriodicGridviewType that is periodic only in all directions
    periodic_directions.set();
    const PeriodicGridViewType fully_periodic_grid_view(grid_view_ref, periodic_directions);

    std::vector< const PeriodicGridViewType* > periodic_grid_view_vector(3);
    periodic_grid_view_vector[0] = &non_periodic_grid_view;
    periodic_grid_view_vector[1] = &partially_periodic_grid_view;
    periodic_grid_view_vector[2] = &fully_periodic_grid_view;

    for (size_t variant = 0; variant <= 2; ++variant) {
      const PeriodicGridViewType periodic_grid_view = *(periodic_grid_view_vector[variant]);

      // check interface
      const GridType& DUNE_UNUSED(test_grid) = periodic_grid_view.grid();
      const IndexSet& DUNE_UNUSED(test_indexSet) = periodic_grid_view.indexSet();
      const int codim0_size = periodic_grid_view.size(0);
      EXPECT_EQ(codim0_size, grid_view.size(0));
      if (dimDomain == 1)
        EXPECT_EQ(codim0_size, int(8));
      if (dimDomain == 2 && is_cube)
        EXPECT_EQ(codim0_size, int(8*8));
      if (dimDomain == 2 && is_simplex)
        EXPECT_EQ(codim0_size, int(2*8*8));
      if (dimDomain == 3 && is_cube)
        EXPECT_EQ(codim0_size, int(8*8*8));
      if (dimDomain == 3 && is_simplex)
        EXPECT_EQ(codim0_size, int(6*8*8*8));
      EXPECT_EQ(periodic_grid_view.size(Dune::cube), grid_view.size(Dune::cube));
      EXPECT_EQ(periodic_grid_view.size(Dune::simplex), grid_view.size(Dune::simplex));
      EXPECT_EQ(periodic_grid_view.overlapSize(0), grid_view.overlapSize(0));
      EXPECT_EQ(periodic_grid_view.overlapSize(1), grid_view.overlapSize(1));
      EXPECT_EQ(periodic_grid_view.ghostSize(0), grid_view.ghostSize(0));
      EXPECT_EQ(periodic_grid_view.ghostSize(1), grid_view.ghostSize(1));
      const CollectiveCommunication& DUNE_UNUSED(test_comm) = periodic_grid_view.comm();

      size_t neighbor_count = 0;
      size_t boundary_count = 0;
      size_t periodic_count = 0;
      // iterate over all entities
      const EntityIteratorType it_end = periodic_grid_view.template end< 0 >();
      for (EntityIteratorType it = periodic_grid_view.template begin< 0 >(); it != it_end; ++it) {
        const EntityType& entity = *it;
        EXPECT_TRUE(periodic_grid_view.contains(entity));
        // iterate over all intersections on current entity
        const PeriodicIntersectionIteratorType i_it_end = periodic_grid_view.iend(entity);
        for (PeriodicIntersectionIteratorType i_it = periodic_grid_view.ibegin(entity); i_it != i_it_end; ++i_it) {
          const PeriodicIntersectionType& intersection = *i_it;
          if (intersection.neighbor()) {
            ++neighbor_count;
            const auto outside = *(intersection.outside());
            //find corresponding intersection in outside
            const auto index_in_outside = intersection.indexInOutside();
            PeriodicIntersectionType intersection_in_outside = *(periodic_grid_view.ibegin(outside).operator->());
            const PeriodicIntersectionIteratorType i_it_outside_end = periodic_grid_view.iend(outside);
            for (PeriodicIntersectionIteratorType i_it_outside = periodic_grid_view.ibegin(outside); i_it_outside != i_it_outside_end; ++i_it_outside) {
              const PeriodicIntersectionType* outside_intersection = i_it_outside.operator->();
              if (outside_intersection->indexInInside() == index_in_outside) {
                intersection_in_outside = *outside_intersection;
              }
            }
            // check outside_intersection coords
            const auto coords_in_outside = intersection.geometryInOutside().center();
            const auto coords_in_outside_2 = intersection_in_outside.geometryInInside().center();
            EXPECT_TRUE(Dune::Stuff::Common::FloatCmp::eq(coords_in_outside, coords_in_outside_2));
            // check global intersection coords in periodic case
            const auto global_intersection_coords = intersection.geometry().center();
            const auto global_outside_intersection_coords = intersection_in_outside.geometry().center();
            size_t coord_difference_count = 0;
            size_t differing_coordinate;
            for (size_t ii = 0; ii < dimDomain; ++ii) {
              if (Dune::Stuff::Common::FloatCmp::ne(global_outside_intersection_coords[ii], global_intersection_coords[ii])) {
                ++coord_difference_count;
                differing_coordinate = ii;
              }
            }
            if (intersection.is_periodic()) {
              EXPECT_EQ(size_t(1), coord_difference_count);
              EXPECT_TRUE((Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(1)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(0)))
                          || (Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(0)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(1))));
              ++periodic_count;
              if (variant == 1)
                EXPECT_EQ(size_t(0), differing_coordinate);
            }
          }
          if (intersection.boundary()) {
            ++boundary_count;
            EXPECT_FALSE(intersection.is_periodic());
            EXPECT_FALSE(intersection.neighbor());
          }
        }
      }

      if (dimDomain == 1) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*7),neighbor_count);
          EXPECT_EQ(size_t(2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*7+2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*7+2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2), periodic_count);
        }
      }
      if (dimDomain == 2 && is_cube) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*8*7),neighbor_count);
          EXPECT_EQ(size_t(2*8*2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8),neighbor_count);
          EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);
          EXPECT_EQ(size_t(2*8), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8*2),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*8*2), periodic_count);
        }
      }
      if (dimDomain == 2 && is_simplex) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(2*8*2), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);
          EXPECT_EQ(size_t(2*8), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*8*7 + 2*8*2 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*8*2), periodic_count);
        }
      }
      if (dimDomain == 3 && is_cube) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*3*7*64),neighbor_count);
          EXPECT_EQ(size_t(6*64), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*3*7*64 + 2*64),neighbor_count);
          EXPECT_EQ(size_t(6*64 - 2*64), boundary_count);
          EXPECT_EQ(size_t(2*64), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*3*7*64 + 6*64),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(6*64), periodic_count);
        }
      }
      if (dimDomain == 3 && is_simplex) {
        if (variant == 0) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(2*6*64), boundary_count);
          EXPECT_EQ(size_t(0), periodic_count);
        }
        if (variant == 1) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*2*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(2*6*64 - 2*2*64), boundary_count);
          EXPECT_EQ(size_t(2*2*64), periodic_count);
        }
        if (variant == 2) {
          EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*64 + 2*6*8*8*8),neighbor_count);
          EXPECT_EQ(size_t(0), boundary_count);
          EXPECT_EQ(size_t(2*6*64), periodic_count);
        }
      }
    }
  }
};

template< class GridImp >
struct PeriodicViewTestSimplex
  : public PeriodicViewTestCube< GridImp >
{};

typedef testing::Types< YASPGRIDS
# if HAVE_ALUGRID
                      , ALUCUBEGRIDS
# endif
                      > CubeGridTypes;

typedef testing::Types<
# if HAVE_ALUGRID
                        ALUSIMPLEXGRIDS
# endif
                      > SimplexGridTypes;

TYPED_TEST_CASE(PeriodicViewTestCube, CubeGridTypes);
TYPED_TEST(PeriodicViewTestCube, checkcube)
{
  this->check(false);
}

TYPED_TEST_CASE(PeriodicViewTestSimplex, SimplexGridTypes);
TYPED_TEST(PeriodicViewTestSimplex, checksimplex)
{
  this->check(true);
}

#else // HAVE_DUNE_GRID

TEST(DISABLED_CubeGridProvider, is_default_creatable) {}
TEST(DISABLED_CubeGridProvider, fulfills_const_interface) {}
TEST(DISABLED_CubeGridProvider, is_visualizable) {}

#endif // HAVE_DUNE_GRID

<|endoftext|>


<commit_before><commit_msg>Override AudioManager::MakeAudioInputStream() in NullAudioManager.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2014 Robert Böhm
//
// 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 "LoopingThread.hpp"

LoopingThread::LoopingThread() : thread(nullptr), scheduledCallbacks() {

}

LoopingThread::~LoopingThread() {
  if (this->thread) {
    delete this->thread;
  }
}

void LoopingThread::runCallbacks() {
  this->callbacksMutex.lock();
  if (this->scheduledCallbacks.size() > 0) {
    std::vector<std::function<void()>> currentCallbacks = std::move(this->scheduledCallbacks);
    this->scheduledCallbacks.clear();
    this->callbacksMutex.unlock();
    for (auto callback : currentCallbacks) {
      callback();
    }
  } else {
    this->callbacksMutex.unlock();
  }
}

void LoopingThread::run() {
  for (;;) {
    // This is to allow for new callbacks to be scheduled from within a callback
    this->runCallbacks();

    // Run the tick
    if (!this->tick()) {
      break;
    }
  }

  // Run pending callbacks, this might result in an infinite loop if there are more
  // callbacks scheduled from within scheduled callbacks
  this->callbacksMutex.lock();
  while (this->scheduledCallbacks.size() > 0) {
    this->callbacksMutex.unlock();
    this->runCallbacks();
    this->callbacksMutex.lock();
  }
  this->callbacksMutex.unlock();
}

void LoopingThread::scheduleCallback(std::function<void()> callback) {
  this->callbacksMutex.lock();
  this->scheduledCallbacks.push_back(callback);
  this->callbacksMutex.unlock();
}

void LoopingThread::start() {
  if (!this->thread) {
    this->thread = new std::thread(&LoopingThread::run, this);
  }
}

void LoopingThread::join() {
  if (this->thread && this->thread->joinable()) {
    this->thread->join();
  }
}
<commit_msg>Move comment to proper location.<commit_after>// Copyright (c) 2014 Robert Böhm
//
// 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 "LoopingThread.hpp"

LoopingThread::LoopingThread() : thread(nullptr), scheduledCallbacks() {

}

LoopingThread::~LoopingThread() {
  if (this->thread) {
    delete this->thread;
  }
}

void LoopingThread::runCallbacks() {
  this->callbacksMutex.lock();
  if (this->scheduledCallbacks.size() > 0) {
    // This is to allow for new callbacks to be scheduled from within a callback
    std::vector<std::function<void()>> currentCallbacks = std::move(this->scheduledCallbacks);
    this->scheduledCallbacks.clear();
    this->callbacksMutex.unlock();
    for (auto callback : currentCallbacks) {
      callback();
    }
  } else {
    this->callbacksMutex.unlock();
  }
}

void LoopingThread::run() {
  for (;;) {
    this->runCallbacks();

    // Run the tick
    if (!this->tick()) {
      break;
    }
  }

  // Run pending callbacks, this might result in an infinite loop if there are more
  // callbacks scheduled from within scheduled callbacks
  this->callbacksMutex.lock();
  while (this->scheduledCallbacks.size() > 0) {
    this->callbacksMutex.unlock();
    this->runCallbacks();
    this->callbacksMutex.lock();
  }
  this->callbacksMutex.unlock();
}

void LoopingThread::scheduleCallback(std::function<void()> callback) {
  this->callbacksMutex.lock();
  this->scheduledCallbacks.push_back(callback);
  this->callbacksMutex.unlock();
}

void LoopingThread::start() {
  if (!this->thread) {
    this->thread = new std::thread(&LoopingThread::run, this);
  }
}

void LoopingThread::join() {
  if (this->thread && this->thread->joinable()) {
    this->thread->join();
  }
}
<|endoftext|>


<commit_before>/**
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "CppSound.hpp"

#include <cstdio>
#include <cstring>

CppSound::CppSound() : Csound(),
                       go(false),
                       isCompiled(false),
                       isPerforming(false),
                       spoutSize(0)
{
  SetHostData((CSOUND *)0);
}

CppSound::~CppSound()
{
}

int CppSound::compile(int argc, char **argv_)
{
  Message("BEGAN CppSound::compile(%d, %p)...\n", argc, argv_);
  go = false;
  int returnValue = Compile(argc, argv_);
  spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT);
  if(returnValue)
    {
      isCompiled = false;
    }
  else
    {
      const char *outfilename = GetOutputFileName();
      if (outfilename) {
        renderedSoundfile = outfilename;
      }
      isCompiled = true;
      go = true;
    }
  Message("ENDED CppSound::compile.\n");
  return returnValue;
}

int CppSound::compile()
{
  Message("BEGAN CppSound::compile()...\n");
  if(getCommand().length() <= 0)
    {
      Message("No Csound command.\n");
      return 0;
    }
  scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));
  int returnValue = compile(args.size(), &argv.front());
  Message("ENDED CppSound::compile.\n");
  return returnValue;
}

int CppSound::perform(int argc, char **argv_)
{
  double beganAt = double(clock()) / double(CLOCKS_PER_SEC);
  isCompiled = false;
  go = false;
  Message("BEGAN CppSound::perform(%d, %p)...\n", argc, argv_);
  if(argc <= 0)
    {
      Message("ENDED CppSound::perform without compiling or performing.\n");
      return 0;
    }
  int result = compile(argc, argv_);
  if(result == -1)
    {
      return result;
    }
  for(result = 0; (result == 0) && go; )
    {
      result = PerformKsmps();
    }
  cleanup();
  double endedAt = double(clock()) / double(CLOCKS_PER_SEC);
  double elapsed = endedAt - beganAt;
  Message("Elapsed time = %f seconds.\n", elapsed);
  Message("ENDED CppSound::perform.\n");
  isCompiled = false;
  isPerforming = false;
  return 1;
}

int CppSound::perform()
{
  int returnValue = 0;
  std::string command = getCommand();
  if(command.find("-") == 0)
    {
      const char *argv_[] = {"csound", getFilename().c_str(), 0};
      returnValue = perform(2, (char **)argv_);
    }
  else
    {
      scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));
      returnValue = perform(args.size(), &argv.front());
    }
  return returnValue;
}

void CppSound::stop()
{
  Message("RECEIVED CppSound::stop...\n");
  isCompiled = false;
  isPerforming = false;
  go = false;
  Stop();
}

CSOUND *CppSound::getCsound()
{
  return csound;
}

int CppSound::performKsmps(bool absolute)
{
  if(absolute){
    return PerformKsmpsAbsolute();
  }
  else {
    return PerformKsmps();
  }
}

void CppSound::cleanup()
{
  Cleanup();
  Reset();
}

size_t CppSound::getSpoutSize() const
{
  return spoutSize;
}

std::string CppSound::getOutputSoundfileName() const
{
  return renderedSoundfile;
}

void CppSound::inputMessage(const char *istatement)
{
  InputMessage(istatement);
}

void CppSound::write(const char *text)
{
  Message("%s", text);
}

long CppSound::getThis()
{
  return (long) this;
}

CsoundFile *CppSound::getCsoundFile()
{
  return dynamic_cast<CsoundFile *>(this);
}

bool CppSound::getIsCompiled() const
{
  return isCompiled;
}

void CppSound::setIsPerforming(bool isPerforming)
{
  this->isPerforming = isPerforming;
}

bool CppSound::getIsPerforming() const
{
  return isPerforming;
}

bool CppSound::getIsGo()
{
  if(csound) {
    if(GetSpin() && GetSpout()) {
      return go;
    }
  }
  return false;
}

<commit_msg>Removed from the stop method a message which was messy if stop is called from a different thread, which it usually is.<commit_after>/**
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "CppSound.hpp"

#include <cstdio>
#include <cstring>

CppSound::CppSound() : Csound(),
                       go(false),
                       isCompiled(false),
                       isPerforming(false),
                       spoutSize(0)
{
  SetHostData((CSOUND *)0);
}

CppSound::~CppSound()
{
}

int CppSound::compile(int argc, char **argv_)
{
  Message("BEGAN CppSound::compile(%d, %p)...\n", argc, argv_);
  go = false;
  int returnValue = Compile(argc, argv_);
  spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT);
  if(returnValue)
    {
      isCompiled = false;
    }
  else
    {
      const char *outfilename = GetOutputFileName();
      if (outfilename) {
        renderedSoundfile = outfilename;
      }
      isCompiled = true;
      go = true;
    }
  Message("ENDED CppSound::compile.\n");
  return returnValue;
}

int CppSound::compile()
{
  Message("BEGAN CppSound::compile()...\n");
  if(getCommand().length() <= 0)
    {
      Message("No Csound command.\n");
      return 0;
    }
  scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));
  int returnValue = compile(args.size(), &argv.front());
  Message("ENDED CppSound::compile.\n");
  return returnValue;
}

int CppSound::perform(int argc, char **argv_)
{
  double beganAt = double(clock()) / double(CLOCKS_PER_SEC);
  isCompiled = false;
  go = false;
  Message("BEGAN CppSound::perform(%d, %p)...\n", argc, argv_);
  if(argc <= 0)
    {
      Message("ENDED CppSound::perform without compiling or performing.\n");
      return 0;
    }
  int result = compile(argc, argv_);
  if(result == -1)
    {
      return result;
    }
  for(result = 0; (result == 0) && go; )
    {
      result = PerformKsmps();
    }
  cleanup();
  double endedAt = double(clock()) / double(CLOCKS_PER_SEC);
  double elapsed = endedAt - beganAt;
  Message("Elapsed time = %f seconds.\n", elapsed);
  Message("ENDED CppSound::perform.\n");
  isCompiled = false;
  isPerforming = false;
  return 1;
}

int CppSound::perform()
{
  int returnValue = 0;
  std::string command = getCommand();
  if(command.find("-") == 0)
    {
      const char *argv_[] = {"csound", getFilename().c_str(), 0};
      returnValue = perform(2, (char **)argv_);
    }
  else
    {
      scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));
      returnValue = perform(args.size(), &argv.front());
    }
  return returnValue;
}

void CppSound::stop()
{
  isCompiled = false;
  isPerforming = false;
  go = false;
  Stop();
}

CSOUND *CppSound::getCsound()
{
  return csound;
}

int CppSound::performKsmps(bool absolute)
{
  if(absolute){
    return PerformKsmpsAbsolute();
  }
  else {
    return PerformKsmps();
  }
}

void CppSound::cleanup()
{
  Cleanup();
  Reset();
}

size_t CppSound::getSpoutSize() const
{
  return spoutSize;
}

std::string CppSound::getOutputSoundfileName() const
{
  return renderedSoundfile;
}

void CppSound::inputMessage(const char *istatement)
{
  InputMessage(istatement);
}

void CppSound::write(const char *text)
{
  Message("%s", text);
}

long CppSound::getThis()
{
  return (long) this;
}

CsoundFile *CppSound::getCsoundFile()
{
  return dynamic_cast<CsoundFile *>(this);
}

bool CppSound::getIsCompiled() const
{
  return isCompiled;
}

void CppSound::setIsPerforming(bool isPerforming)
{
  this->isPerforming = isPerforming;
}

bool CppSound::getIsPerforming() const
{
  return isPerforming;
}

bool CppSound::getIsGo()
{
  if(csound) {
    if(GetSpin() && GetSpout()) {
      return go;
    }
  }
  return false;
}

<|endoftext|>


<commit_before>#include "interface.h"

Interface::Interface() {
  ftyp = new Box_ftyp();
  moov = new Box_moov();
  mvhd = new Box_mvhd();
  trak_vide = new Box_trak();
  tkhd_vide = new Box_tkhd();
  mdia_vide = new Box_mdia();
  mdhd_vide = new Box_mdhd();
  hdlr_vide = new Box_hdlr();
  minf_vide = new Box_minf();
  vmhd_vide = new Box_vmhd();
  dinf_vide = new Box_dinf();
  dref_vide = new Box_dref();
  url_vide = new Box_url();
  stbl_vide = new Box_stbl();
  stts_vide = new Box_stts();
  stsc_vide = new Box_stsc();
  stco_vide = new Box_stco();
  stsd_vide = new Box_stsd();
  avcC_vide = new Box_avcC();
  trak_soun = new Box_trak();
  tkhd_soun = new Box_tkhd();
  mdia_soun = new Box_mdia();
  mdhd_soun = new Box_mdhd();
  hdlr_soun = new Box_hdlr();
  minf_soun = new Box_minf();
  smhd_soun = new Box_smhd();
  dinf_soun = new Box_dinf();
  dref_soun = new Box_dref();
  url_soun = new Box_url();
  stbl_soun = new Box_stbl();
  stts_soun = new Box_stts();
  stsc_soun = new Box_stsc();
  stco_soun = new Box_stco();
  stsd_soun = new Box_stsd();
  esds_soun = new Box_esds();
}

Interface::~Interface() {
  if( esds_soun ) { delete esds_soun; esds_soun = NULL; }
  if( stsd_soun ) { delete stsd_soun; stsd_soun = NULL; }
  if( stco_soun ) { delete stco_soun; stco_soun = NULL; }
  if( stsc_soun ) { delete stsc_soun; stsc_soun = NULL; }
  if( stts_soun ) { delete stts_soun; stts_soun = NULL; }
  if( stbl_soun ) { delete stbl_soun; stbl_soun = NULL; }
  if( url_soun ) { delete url_soun; url_soun = NULL; }
  if( dref_soun ) { delete dref_soun; dref_soun = NULL; }
  if( dinf_soun ) { delete dinf_soun; dinf_soun = NULL; }
  if( minf_soun ) { delete minf_soun; minf_soun = NULL; }
  if( hdlr_soun ) { delete hdlr_soun; hdlr_soun = NULL; }
  if( mdhd_soun ) { delete mdhd_soun; mdhd_soun = NULL; }
  if( mdia_soun ) { delete mdia_soun; mdia_soun = NULL; }
  if( tkhd_soun ) { delete tkhd_soun; tkhd_soun = NULL; }
  if( trak_soun ) { delete trak_soun; trak_soun = NULL; }
  if( avcC_vide ) { delete avcC_vide; avcC_vide = NULL; }
  if( stsd_vide ) { delete stsd_vide; stsd_vide = NULL; }
  if( stco_vide ) { delete stco_vide; stco_vide = NULL; }
  if( stsc_vide ) { delete stsc_vide; stsc_vide = NULL; }
  if( stts_vide ) { delete stts_vide; stts_vide = NULL; }
  if( stbl_vide ) { delete stbl_vide; stbl_vide = NULL; }
  if( url_vide ) { delete url_vide; url_vide = NULL; }
  if( dref_vide ) { delete dref_vide; dref_vide = NULL; }
  if( dinf_vide ) { delete dinf_vide; dinf_vide = NULL; }
  if( minf_vide ) { delete minf_vide; minf_vide = NULL; }
  if( hdlr_vide ) { delete hdlr_vide; hdlr_vide = NULL; }
  if( mdhd_vide ) { delete mdhd_vide; mdhd_vide = NULL; }
  if( mdia_vide ) { delete mdia_vide; mdia_vide = NULL; }
  if( tkhd_vide ) { delete tkhd_vide; tkhd_vide = NULL; }
  if( trak_vide ) { delete trak_vide; trak_vide = NULL; }
  if( mvhd ) { delete mvhd; mvhd = NULL; }
  if( moov ) { delete moov; moov = NULL; }
  if( ftyp ) { delete ftyp; ftyp = NULL; }
}

void Interface::link( ) {
  //Linking Video Track
  stsd_vide->AddContent(avcC_vide->GetBox());
  stbl_vide->AddContent(stsd_vide->GetBox(),3);
  stbl_vide->AddContent(stco_vide->GetBox(),2);
  stbl_vide->AddContent(stsc_vide->GetBox(),1);
  stbl_vide->AddContent(stts_vide->GetBox());
  dref_vide->AddContent(url_vide->GetBox());
  dinf_vide->AddContent(dref_vide->GetBox());
  minf_vide->AddContent(stbl_vide->GetBox(),2);
  minf_vide->AddContent(dinf_vide->GetBox(),1);
  minf_vide->AddContent(vmhd_vide->GetBox());
  mdia_vide->AddContent(minf_vide->GetBox(),2);
  mdia_vide->AddContent(hdlr_vide->GetBox(),1);
  mdia_vide->AddContent(mdhd_vide->GetBox());
  trak_vide->AddContent(mdia_vide->GetBox(),1);
  trak_vide->AddContent(tkhd_vide->GetBox());

  //Linking Sound Track
  stsd_soun->AddContent(esds_soun->GetBox());
  stbl_soun->AddContent(stsd_soun->GetBox(),3);
  stbl_soun->AddContent(stco_soun->GetBox(),2);
  stbl_soun->AddContent(stsc_soun->GetBox(),1);
  stbl_soun->AddContent(stts_soun->GetBox());
  dref_soun->AddContent(url_soun->GetBox());
  dinf_soun->AddContent(dref_soun->GetBox());
  minf_soun->AddContent(stbl_soun->GetBox(),2);
  minf_soun->AddContent(dinf_soun->GetBox(),1);
  minf_soun->AddContent(smhd_soun->GetBox());
  mdia_soun->AddContent(minf_soun->GetBox(),2);
  mdia_soun->AddContent(hdlr_soun->GetBox(),1);
  mdia_soun->AddContent(mdhd_soun->GetBox());
  trak_soun->AddContent(mdia_soun->GetBox(),1);
  trak_soun->AddContent(tkhd_soun->GetBox());

  //Linking total file
  moov->AddContent(trak_soun->GetBox(),2);
  moov->AddContent(trak_vide->GetBox(),1);
  moov->AddContent(mvhd->GetBox());
}

uint32_t Interface::GetContentSize( ) {
  return ftyp->GetBoxedDataSize( ) + moov->GetBoxedDataSize( );
}

uint8_t * Interface::GetContents( ) {
  uint8_t * Result = new uint8_t[GetContentSize( )];
  memcpy(Result,ftyp->GetBoxedData( ),ftyp->GetBoxedDataSize( ));
  memcpy(&Result[ftyp->GetBoxedDataSize( )],moov->GetBoxedData( ),moov->GetBoxedDataSize( ));
  return Result;
}
<commit_msg>[Stable] Filedata functionlity in interface working<commit_after>#include "interface.h"

Interface::Interface() {
  ftyp = new Box_ftyp();
  moov = new Box_moov();
  mvhd = new Box_mvhd();
  trak_vide = new Box_trak();
  tkhd_vide = new Box_tkhd();
  mdia_vide = new Box_mdia();
  mdhd_vide = new Box_mdhd();
  hdlr_vide = new Box_hdlr();
  minf_vide = new Box_minf();
  vmhd_vide = new Box_vmhd();
  dinf_vide = new Box_dinf();
  dref_vide = new Box_dref();
  url_vide = new Box_url();
  stbl_vide = new Box_stbl();
  stts_vide = new Box_stts();
  stsc_vide = new Box_stsc();
  stco_vide = new Box_stco();
  stsd_vide = new Box_stsd();
  avcC_vide = new Box_avcC();
  trak_soun = new Box_trak();
  tkhd_soun = new Box_tkhd();
  mdia_soun = new Box_mdia();
  mdhd_soun = new Box_mdhd();
  hdlr_soun = new Box_hdlr();
  minf_soun = new Box_minf();
  smhd_soun = new Box_smhd();
  dinf_soun = new Box_dinf();
  dref_soun = new Box_dref();
  url_soun = new Box_url();
  stbl_soun = new Box_stbl();
  stts_soun = new Box_stts();
  stsc_soun = new Box_stsc();
  stco_soun = new Box_stco();
  stsd_soun = new Box_stsd();
  esds_soun = new Box_esds();
}

Interface::~Interface() {
  if( esds_soun ) { delete esds_soun; esds_soun = NULL; }
  if( stsd_soun ) { delete stsd_soun; stsd_soun = NULL; }
  if( stco_soun ) { delete stco_soun; stco_soun = NULL; }
  if( stsc_soun ) { delete stsc_soun; stsc_soun = NULL; }
  if( stts_soun ) { delete stts_soun; stts_soun = NULL; }
  if( stbl_soun ) { delete stbl_soun; stbl_soun = NULL; }
  if( url_soun ) { delete url_soun; url_soun = NULL; }
  if( dref_soun ) { delete dref_soun; dref_soun = NULL; }
  if( dinf_soun ) { delete dinf_soun; dinf_soun = NULL; }
  if( minf_soun ) { delete minf_soun; minf_soun = NULL; }
  if( hdlr_soun ) { delete hdlr_soun; hdlr_soun = NULL; }
  if( mdhd_soun ) { delete mdhd_soun; mdhd_soun = NULL; }
  if( mdia_soun ) { delete mdia_soun; mdia_soun = NULL; }
  if( tkhd_soun ) { delete tkhd_soun; tkhd_soun = NULL; }
  if( trak_soun ) { delete trak_soun; trak_soun = NULL; }
  if( avcC_vide ) { delete avcC_vide; avcC_vide = NULL; }
  if( stsd_vide ) { delete stsd_vide; stsd_vide = NULL; }
  if( stco_vide ) { delete stco_vide; stco_vide = NULL; }
  if( stsc_vide ) { delete stsc_vide; stsc_vide = NULL; }
  if( stts_vide ) { delete stts_vide; stts_vide = NULL; }
  if( stbl_vide ) { delete stbl_vide; stbl_vide = NULL; }
  if( url_vide ) { delete url_vide; url_vide = NULL; }
  if( dref_vide ) { delete dref_vide; dref_vide = NULL; }
  if( dinf_vide ) { delete dinf_vide; dinf_vide = NULL; }
  if( minf_vide ) { delete minf_vide; minf_vide = NULL; }
  if( hdlr_vide ) { delete hdlr_vide; hdlr_vide = NULL; }
  if( mdhd_vide ) { delete mdhd_vide; mdhd_vide = NULL; }
  if( mdia_vide ) { delete mdia_vide; mdia_vide = NULL; }
  if( tkhd_vide ) { delete tkhd_vide; tkhd_vide = NULL; }
  if( trak_vide ) { delete trak_vide; trak_vide = NULL; }
  if( mvhd ) { delete mvhd; mvhd = NULL; }
  if( moov ) { delete moov; moov = NULL; }
  if( ftyp ) { delete ftyp; ftyp = NULL; }
}

void Interface::link( ) {
  //Linking Video Track
  stsd_vide->AddContent(avcC_vide->GetBox());
  stbl_vide->AddContent(stsd_vide->GetBox(),3);
  stbl_vide->AddContent(stco_vide->GetBox(),2);
  stbl_vide->AddContent(stsc_vide->GetBox(),1);
  stbl_vide->AddContent(stts_vide->GetBox());
  dref_vide->AddContent(url_vide->GetBox());
  dinf_vide->AddContent(dref_vide->GetBox());
  minf_vide->AddContent(stbl_vide->GetBox(),2);
  minf_vide->AddContent(dinf_vide->GetBox(),1);
  minf_vide->AddContent(vmhd_vide->GetBox());
  mdia_vide->AddContent(minf_vide->GetBox(),2);
  mdia_vide->AddContent(hdlr_vide->GetBox(),1);
  mdia_vide->AddContent(mdhd_vide->GetBox());
  trak_vide->AddContent(mdia_vide->GetBox(),1);
  trak_vide->AddContent(tkhd_vide->GetBox());

  //Linking Sound Track
  stsd_soun->AddContent(esds_soun->GetBox());
  stbl_soun->AddContent(stsd_soun->GetBox(),3);
  stbl_soun->AddContent(stco_soun->GetBox(),2);
  stbl_soun->AddContent(stsc_soun->GetBox(),1);
  stbl_soun->AddContent(stts_soun->GetBox());
  dref_soun->AddContent(url_soun->GetBox());
  dinf_soun->AddContent(dref_soun->GetBox());
  minf_soun->AddContent(stbl_soun->GetBox(),2);
  minf_soun->AddContent(dinf_soun->GetBox(),1);
  minf_soun->AddContent(smhd_soun->GetBox());
  mdia_soun->AddContent(minf_soun->GetBox(),2);
  mdia_soun->AddContent(hdlr_soun->GetBox(),1);
  mdia_soun->AddContent(mdhd_soun->GetBox());
  trak_soun->AddContent(mdia_soun->GetBox(),1);
  trak_soun->AddContent(tkhd_soun->GetBox());

  //Linking total file
  moov->AddContent(trak_soun->GetBox(),2);
  moov->AddContent(trak_vide->GetBox(),1);
  moov->AddContent(mvhd->GetBox());
}

uint32_t Interface::GetContentSize( ) {
  return ftyp->GetBox( )->GetBoxedDataSize( ) + moov->GetBox( )->GetBoxedDataSize( );
}

uint8_t * Interface::GetContents( ) {
  uint8_t * Result = new uint8_t[GetContentSize( )];
  memcpy(Result,ftyp->GetBox( )->GetBoxedData( ),ftyp->GetBox( )->GetBoxedDataSize( ));
  memcpy(&Result[ftyp->GetBox( )->GetBoxedDataSize( )],moov->GetBox( )->GetBoxedData( ),moov->GetBox( )->GetBoxedDataSize( ));
  return Result;
}
<|endoftext|>


<commit_before>/** Implementation of canonpy.
 */

#include <canonpy.h>

#include <Python.h>

#include <libcanon/perm.h>

using libcanon::Simple_perm;

//
// Perm class
// ==========
//
// Internal functions
// ------------------
//
// These functions are not directly set to Python types but are used
// internally.  They are also used by other parts of this extension.
//

/** Builds a tuple object for a permutation.
 *
 * This function creates a pair, where the first field is a list of integers
 * for the preimage array, and the second field is the accompanied action,
 * which is also encoded as an integer.
 */

static PyObject* build_perm_to_tuple(const Simple_perm& perm);

/** Builds a permutation from its construction arguments.
 *
 * An iterable of positive integers for the pre-image array needs to be given
 * as the first argument.  The accompanied action can be optionally given as
 * another integral argument, or by the keyword ``acc``.
 *
 * If the arguments are not valid, a Perm of size zero is going to be returned.
 *
 * This function is designed to be compatible with the result from the function
 * `build_perm_to_tuple`.  However, more general input format is accepted.
 */

static Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs);

//
// Interface functions
// -------------------
//

//
// Class definition
// ----------------
//

/** Methods for Perm objects.
 */

static PyMethodDef perm_methods[] = {
    { "__getnewargs__", (PyCFunction)perm_getnewargs, METH_NOARGS,
        perm_getnewargs_doc },
    { NULL, NULL } /* sentinel */
};

/** Sequence operations for Perm objects.
 *
 * Here we only support size and pre-image query.
 */

// clang-format off
static PySequenceMethods perm_as_sequence = {
    (lenfunc)perm_length,                       /* sq_length */
    0,                                          /* sq_concat */
    0,                                          /* sq_repeat */
    (ssizeargfunc)perm_item,                    /* sq_item */
    0,                                          /* sq_slice */
    0,                                          /* sq_ass_item */
    0,                                          /* sq_ass_slice */
    0                                           /* sq_contains */
};
// clang-format on

/** Accessors for Perms.
 *
 * The accompanied action query is made here.
 */

// clang-format off
static PyGetSetDef perm_getsets[] = {
    { "acc", (getter)perm_get_acc, NULL, "The accompanied action.", NULL },
    { NULL }
};
// clang-format on

/** Type definition for Perm class.
 */

// clang-format off
static PyTypeObject perm_type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "drudge.canonpy.Perm",
    sizeof(Perm_object),
    0,
    (destructor) perm_dealloc,                  /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    (reprfunc) perm_repr,                       /* tp_repr */
    0,                                          /* tp_as_number */
    &perm_as_sequence,                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    (hashfunc) perm_hash,                       /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    0, /* In main. */                           /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    perm_doc,                                   /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    perm_methods,                               /* tp_methods */
    0,                                          /* tp_members */
    perm_getsets,                               /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    perm_new,                                   /* tp_new */
    0,                                          /* tp_free */
};
// clang-format on

//
// Python module definition
// ========================
//

/** Docstring for the canonpy module.
 */

static const char* canonpy_docstring = R"CANONPYDOC(
Canonpy, simple wrapper over libcanon for Python.

)CANONPYDOC";

/** Methods in the canonpy module.
 */

static PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };

/** Executes the initialization of the canonpy module.
 */

static int canopy_exec(PyObject* m)
{
    //
    // Add the class for Perm.
    //

    perm_type.tp_getattro = PyObject_GenericGetAttr;
    if (PyType_Ready(&perm_type) < 0)
        return NULL;
    Py_INCREF(&perm_type);
    PyModule_AddObject(m, "Perm", (PyObject*)&perm_type);

    return 0;
}

/** Slots for for canonpy module definition.
 */

static struct PyModuleDef_Slot canonpy_slots[] = {
    { Py_mod_exec, canonpy_exec }, { 0, NULL },
};

/** Canonpy module definition.
 */

// clang-format off

static struct PyModuleDef canonpy_module = {
    PyModuleDef_HEAD_INIT,
    "drudge.canonpy",
    canonpy_docstring,
    0, // m-size
    canonpy_methods,
    canonpy_slots,
    NULL, // Transverse
    NULL, // Clear
    NULL  // Free
};

// clang-format on

/** The published canonpy function.
 */

PyMODINIT_FUNC PyInit_canonpy(void)
{
    return PyModuleDef_Init(&canonpy_module);
}
<commit_msg>Update docstring for canonpy module<commit_after>/** Implementation of canonpy.
 */

#include <canonpy.h>

#include <Python.h>

#include <libcanon/perm.h>

using libcanon::Simple_perm;

//
// Perm class
// ==========
//
// Internal functions
// ------------------
//
// These functions are not directly set to Python types but are used
// internally.  They are also used by other parts of this extension.
//

/** Builds a tuple object for a permutation.
 *
 * This function creates a pair, where the first field is a list of integers
 * for the preimage array, and the second field is the accompanied action,
 * which is also encoded as an integer.
 */

static PyObject* build_perm_to_tuple(const Simple_perm& perm);

/** Builds a permutation from its construction arguments.
 *
 * An iterable of positive integers for the pre-image array needs to be given
 * as the first argument.  The accompanied action can be optionally given as
 * another integral argument, or by the keyword ``acc``.
 *
 * If the arguments are not valid, a Perm of size zero is going to be returned.
 *
 * This function is designed to be compatible with the result from the function
 * `build_perm_to_tuple`.  However, more general input format is accepted.
 */

static Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs);

//
// Interface functions
// -------------------
//

//
// Class definition
// ----------------
//

/** Methods for Perm objects.
 */

static PyMethodDef perm_methods[] = {
    { "__getnewargs__", (PyCFunction)perm_getnewargs, METH_NOARGS,
        perm_getnewargs_doc },
    { NULL, NULL } /* sentinel */
};

/** Sequence operations for Perm objects.
 *
 * Here we only support size and pre-image query.
 */

// clang-format off
static PySequenceMethods perm_as_sequence = {
    (lenfunc)perm_length,                       /* sq_length */
    0,                                          /* sq_concat */
    0,                                          /* sq_repeat */
    (ssizeargfunc)perm_item,                    /* sq_item */
    0,                                          /* sq_slice */
    0,                                          /* sq_ass_item */
    0,                                          /* sq_ass_slice */
    0                                           /* sq_contains */
};
// clang-format on

/** Accessors for Perms.
 *
 * The accompanied action query is made here.
 */

// clang-format off
static PyGetSetDef perm_getsets[] = {
    { "acc", (getter)perm_get_acc, NULL, "The accompanied action.", NULL },
    { NULL }
};
// clang-format on

/** Type definition for Perm class.
 */

// clang-format off
static PyTypeObject perm_type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "drudge.canonpy.Perm",
    sizeof(Perm_object),
    0,
    (destructor) perm_dealloc,                  /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    (reprfunc) perm_repr,                       /* tp_repr */
    0,                                          /* tp_as_number */
    &perm_as_sequence,                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    (hashfunc) perm_hash,                       /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    0, /* In main. */                           /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    perm_doc,                                   /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    perm_methods,                               /* tp_methods */
    0,                                          /* tp_members */
    perm_getsets,                               /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    perm_new,                                   /* tp_new */
    0,                                          /* tp_free */
};
// clang-format on

//
// Python module definition
// ========================
//

/** Docstring for the canonpy module.
 */

static const char* canonpy_docstring
    = R"__doc__(Canonpy, simple wrapper over libcanon for Python.

This wrapper of libcanon is directly targeted towards usage using drudge.
Here, we have a class `Perm`, which wraps over the `Simple_perm` class in
libcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class
for `Simple_perm`.  And we also have the function `canon_eldag` to canonicalize
an Eldag.

)__doc__";

/** Methods in the canonpy module.
 */

static PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };

/** Executes the initialization of the canonpy module.
 */

static int canopy_exec(PyObject* m)
{
    //
    // Add the class for Perm.
    //

    perm_type.tp_getattro = PyObject_GenericGetAttr;
    if (PyType_Ready(&perm_type) < 0)
        return NULL;
    Py_INCREF(&perm_type);
    PyModule_AddObject(m, "Perm", (PyObject*)&perm_type);

    return 0;
}

/** Slots for for canonpy module definition.
 */

static struct PyModuleDef_Slot canonpy_slots[] = {
    { Py_mod_exec, canonpy_exec }, { 0, NULL },
};

/** Canonpy module definition.
 */

// clang-format off

static struct PyModuleDef canonpy_module = {
    PyModuleDef_HEAD_INIT,
    "drudge.canonpy",
    canonpy_docstring,
    0, // m-size
    canonpy_methods,
    canonpy_slots,
    NULL, // Transverse
    NULL, // Clear
    NULL  // Free
};

// clang-format on

/** The published canonpy function.
 */

PyMODINIT_FUNC PyInit_canonpy(void)
{
    return PyModuleDef_Init(&canonpy_module);
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: slowdown_timer.cc,v 1.8 2001/10/11 13:01:27 yakovlev Exp $
/////////////////////////////////////////////////////////////////////////
//
#include "bochs.h"
#include <errno.h>

#if BX_USE_SLOWDOWN_TIMER

//These need to stay printfs because they are useless in the log file.
#define BX_SLOWDOWN_PRINTF_FEEDBACK 0

#define SECINUSEC 1000000
#define usectosec(a) ((a)/SECINUSEC)
#define sectousec(a) ((a)*SECINUSEC)
#define nsectousec(a) ((a)/1000)

#if BX_HAVE_USLEEP
#  define Qval 1000
#else
#  define Qval SECINUSEC
#endif

#define MAXMULT 1.5
#define REALTIME_Q SECINUSEC

bx_slowdown_timer_c bx_slowdown_timer;

bx_slowdown_timer_c::bx_slowdown_timer_c() {
  s.start_time=0;
  s.start_emulated_time=0;
  s.timer_handle=BX_NULL_TIMER_HANDLE;
}

int
bx_slowdown_timer_c::init() {
  s.MAXmultiplier=MAXMULT;
  s.Q=Qval;

  if(s.MAXmultiplier<1)
    s.MAXmultiplier=1;

  s.start_time=sectousec(time(NULL));
  s.start_emulated_time = bx_pc_system.time_usec();
  s.lasttime=0;
  s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1);
  bx_pc_system.deactivate_timer(s.timer_handle);
  bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);
  return 0;
}

void
bx_slowdown_timer_c::timer_handler(void * this_ptr) {
  bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;

  class_ptr->handle_timer();
}

void
bx_slowdown_timer_c::handle_timer() {
  Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;
  Bit64u wanttime = s.lasttime+s.Q;
  Bit64u totaltime = sectousec(time(NULL)) - s.start_time;
  Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;

#if BX_SLOWDOWN_PRINTF_FEEDBACK
  printf("Entering slowdown timer handler.\n");
#endif

  /* Decide if we're behind.
   * Set interrupt interval accordingly. */
  if(totaltime > total_emu_time) {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,
				(Bit32u)((Bit64u)
					 (s.MAXmultiplier * (float)s.Q)),
				0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at MAX speed\n");
#endif
  } else {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,s.Q,0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at NORMAL speed\n");
#endif
  }

  /* Make sure we took at least one time quantum. */
  /* This is a little strange.  I'll try to explain.
   * We're running bochs one second ahead of real time.
   *  this gives us a very precise division on whether
   *  we're ahead or behind the second line.
   * Basically, here's how it works:
   * *****|******************|***********...
   *      Time               Time+1sec
   *                        <^Bochs doesn't delay.
   *                          ^>Bochs delays.
   *    <^Bochs runs at MAX speed.
   *      ^>Bochs runs at normal
   */
  if(wanttime > (totaltime+REALTIME_Q)) {
#if BX_HAVE_USLEEP
    usleep(s.Q);
#else
    sleep(usectosec(s.Q));
#endif
    //delay(wanttime-totaltime);
    /*alternatively: delay(Q);
     * This works okay because we share the delay between
     * two time quantums.
     */
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("DELAYING for a quantum\n");
#endif
  }
  s.lasttime=thistime;

  //Diagnostic info:
  if(wanttime > (totaltime+REALTIME_Q)) {
    if(totaltime > total_emu_time) {
      if(0) printf("Solving OpenBSD problem.\n");
    } else {
      if(0) printf("too fast.\n");
    }
  } else {
    if(totaltime > total_emu_time) {
      if(0) printf("too slow.\n");
    } else {
      if(0) printf("sometimes invalid state, normally okay.\n");
    }
  }
}

#endif

<commit_msg>commented out the diagnostic code, no use using 10 jumps for nothing, and it will take less time to re-enable it in the future than using those if(0)<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: slowdown_timer.cc,v 1.9 2002/03/06 01:19:50 instinc Exp $
/////////////////////////////////////////////////////////////////////////
//
#include "bochs.h"
#include <errno.h>

#if BX_USE_SLOWDOWN_TIMER

//These need to stay printfs because they are useless in the log file.
#define BX_SLOWDOWN_PRINTF_FEEDBACK 0

#define SECINUSEC 1000000
#define usectosec(a) ((a)/SECINUSEC)
#define sectousec(a) ((a)*SECINUSEC)
#define nsectousec(a) ((a)/1000)

#if BX_HAVE_USLEEP
#  define Qval 1000
#else
#  define Qval SECINUSEC
#endif

#define MAXMULT 1.5
#define REALTIME_Q SECINUSEC

bx_slowdown_timer_c bx_slowdown_timer;

bx_slowdown_timer_c::bx_slowdown_timer_c() {
  s.start_time=0;
  s.start_emulated_time=0;
  s.timer_handle=BX_NULL_TIMER_HANDLE;
}

int
bx_slowdown_timer_c::init() {
  s.MAXmultiplier=MAXMULT;
  s.Q=Qval;

  if(s.MAXmultiplier<1)
    s.MAXmultiplier=1;

  s.start_time=sectousec(time(NULL));
  s.start_emulated_time = bx_pc_system.time_usec();
  s.lasttime=0;
  s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1);
  bx_pc_system.deactivate_timer(s.timer_handle);
  bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);
  return 0;
}

void
bx_slowdown_timer_c::timer_handler(void * this_ptr) {
  bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;

  class_ptr->handle_timer();
}

void
bx_slowdown_timer_c::handle_timer() {
  Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;
  Bit64u wanttime = s.lasttime+s.Q;
  Bit64u totaltime = sectousec(time(NULL)) - s.start_time;
  Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;

#if BX_SLOWDOWN_PRINTF_FEEDBACK
  printf("Entering slowdown timer handler.\n");
#endif

  /* Decide if we're behind.
   * Set interrupt interval accordingly. */
  if(totaltime > total_emu_time) {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,
				(Bit32u)((Bit64u)
					 (s.MAXmultiplier * (float)s.Q)),
				0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at MAX speed\n");
#endif
  } else {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,s.Q,0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at NORMAL speed\n");
#endif
  }

  /* Make sure we took at least one time quantum. */
  /* This is a little strange.  I'll try to explain.
   * We're running bochs one second ahead of real time.
   *  this gives us a very precise division on whether
   *  we're ahead or behind the second line.
   * Basically, here's how it works:
   * *****|******************|***********...
   *      Time               Time+1sec
   *                        <^Bochs doesn't delay.
   *                          ^>Bochs delays.
   *    <^Bochs runs at MAX speed.
   *      ^>Bochs runs at normal
   */
  if(wanttime > (totaltime+REALTIME_Q)) {
#if BX_HAVE_USLEEP
    usleep(s.Q);
#else
    sleep(usectosec(s.Q));
#endif
    //delay(wanttime-totaltime);
    /*alternatively: delay(Q);
     * This works okay because we share the delay between
     * two time quantums.
     */
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("DELAYING for a quantum\n");
#endif
  }
  s.lasttime=thistime;

  //Diagnostic info:
#if 0
  if(wanttime > (totaltime+REALTIME_Q)) {
    if(totaltime > total_emu_time) {
      printf("Solving OpenBSD problem.\n");
    } else {
      printf("too fast.\n");
    }
  } else {
    if(totaltime > total_emu_time) {
      printf("too slow.\n");
    } else {
      printf("sometimes invalid state, normally okay.\n");
    }
  }
#endif // Diagnostic info
}

#endif

<|endoftext|>


<commit_before><commit_msg>Fix 64-bit warnings (for 64-bit Windows build)<commit_after><|endoftext|>