<commit_before>// libjingle
// Copyright 2011 Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. The name of the author may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Implementation of class WebRtcVideoCapturer.

#include "talk/media/webrtc/webrtcvideocapturer.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_WEBRTC_VIDEO
#include "talk/base/criticalsection.h"
#include "talk/base/logging.h"
#include "talk/base/thread.h"
#include "talk/base/timeutils.h"
#include "talk/media/webrtc/webrtcvideoframe.h"

#include "talk/base/win32.h"  // Need this to #include the impl files.
#include "webrtc/modules/video_capture/include/video_capture_factory.h"

namespace cricket {

struct kVideoFourCCEntry {
  uint32 fourcc;
  webrtc::RawVideoType webrtc_type;
};

// This indicates our format preferences and defines a mapping between
// webrtc::RawVideoType (from video_capture_defines.h) to our FOURCCs.
static kVideoFourCCEntry kSupportedFourCCs[] = {
  { FOURCC_I420, webrtc::kVideoI420 },   // 12 bpp, no conversion.
  { FOURCC_YV12, webrtc::kVideoYV12 },   // 12 bpp, no conversion.
  { FOURCC_NV12, webrtc::kVideoNV12 },   // 12 bpp, fast conversion.
  { FOURCC_NV21, webrtc::kVideoNV21 },   // 12 bpp, fast conversion.
  { FOURCC_YUY2, webrtc::kVideoYUY2 },   // 16 bpp, fast conversion.
  { FOURCC_UYVY, webrtc::kVideoUYVY },   // 16 bpp, fast conversion.
  { FOURCC_MJPG, webrtc::kVideoMJPEG },  // compressed, slow conversion.
  { FOURCC_ARGB, webrtc::kVideoARGB },   // 32 bpp, slow conversion.
  { FOURCC_24BG, webrtc::kVideoRGB24 },  // 24 bpp, slow conversion.
};

class WebRtcVcmFactory : public WebRtcVcmFactoryInterface {
 public:
  virtual webrtc::VideoCaptureModule* Create(int id, const char* device) {
    return webrtc::VideoCaptureFactory::Create(id, device);
  }
  virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo(int id) {
    return webrtc::VideoCaptureFactory::CreateDeviceInfo(id);
  }
  virtual void DestroyDeviceInfo(webrtc::VideoCaptureModule::DeviceInfo* info) {
    delete info;
  }
};

static bool CapabilityToFormat(const webrtc::VideoCaptureCapability& cap,
                               VideoFormat* format) {
  uint32 fourcc = 0;
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    if (kSupportedFourCCs[i].webrtc_type == cap.rawType) {
      fourcc = kSupportedFourCCs[i].fourcc;
      break;
    }
  }
  if (fourcc == 0) {
    return false;
  }

  format->fourcc = fourcc;
  format->width = cap.width;
  format->height = cap.height;
  format->interval = VideoFormat::FpsToInterval(cap.maxFPS);
  return true;
}

static bool FormatToCapability(const VideoFormat& format,
                               webrtc::VideoCaptureCapability* cap) {
  webrtc::RawVideoType webrtc_type = webrtc::kVideoUnknown;
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    if (kSupportedFourCCs[i].fourcc == format.fourcc) {
      webrtc_type = kSupportedFourCCs[i].webrtc_type;
      break;
    }
  }
  if (webrtc_type == webrtc::kVideoUnknown) {
    return false;
  }

  cap->width = format.width;
  cap->height = format.height;
  cap->maxFPS = VideoFormat::IntervalToFps(format.interval);
  cap->expectedCaptureDelay = 0;
  cap->rawType = webrtc_type;
  cap->codecType = webrtc::kVideoCodecUnknown;
  cap->interlaced = false;
  return true;
}

///////////////////////////////////////////////////////////////////////////
// Implementation of class WebRtcVideoCapturer
///////////////////////////////////////////////////////////////////////////

WebRtcVideoCapturer::WebRtcVideoCapturer()
    : factory_(new WebRtcVcmFactory),
      module_(NULL),
      captured_frames_(0) {
}

WebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)
    : factory_(factory),
      module_(NULL),
      captured_frames_(0) {
}

WebRtcVideoCapturer::~WebRtcVideoCapturer() {
  if (module_) {
    module_->Release();
  }
}

bool WebRtcVideoCapturer::Init(const Device& device) {
  if (module_) {
    LOG(LS_ERROR) << "The capturer is already initialized";
    return false;
  }

  webrtc::VideoCaptureModule::DeviceInfo* info = factory_->CreateDeviceInfo(0);
  if (!info) {
    return false;
  }

  // Find the desired camera, by name.
  // In the future, comparing IDs will be more robust.
  // TODO(juberti): Figure what's needed to allow this.
  int num_cams = info->NumberOfDevices();
  char vcm_id[256] = "";
  bool found = false;
  for (int index = 0; index < num_cams; ++index) {
    char vcm_name[256];
    if (info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name),
                            vcm_id, ARRAY_SIZE(vcm_id)) != -1) {
      if (device.name == reinterpret_cast<char*>(vcm_name)) {
        found = true;
        break;
      }
    }
  }
  if (!found) {
    LOG(LS_WARNING) << "Failed to find capturer for id: " << device.id;
    factory_->DestroyDeviceInfo(info);
    return false;
  }

  // Enumerate the supported formats.
  // TODO(juberti): Find out why this starts/stops the camera...
  std::vector<VideoFormat> supported;
  int32_t num_caps = info->NumberOfCapabilities(vcm_id);
  for (int32_t i = 0; i < num_caps; ++i) {
    webrtc::VideoCaptureCapability cap;
    if (info->GetCapability(vcm_id, i, cap) != -1) {
      VideoFormat format;
      if (CapabilityToFormat(cap, &format)) {
        supported.push_back(format);
      } else {
        LOG(LS_WARNING) << "Ignoring unsupported WebRTC capture format "
                        << cap.rawType;
      }
    }
  }
  factory_->DestroyDeviceInfo(info);
// TODO(fischman): Remove the following check
// when capabilities for iOS are implemented
// https://code.google.com/p/webrtc/issues/detail?id=2968
#if !defined(IOS)
  if (supported.empty()) {
    LOG(LS_ERROR) << "Failed to find usable formats for id: " << device.id;
    return false;
  }
#endif
  module_ = factory_->Create(0, vcm_id);
  if (!module_) {
    LOG(LS_ERROR) << "Failed to create capturer for id: " << device.id;
    return false;
  }

  // It is safe to change member attributes now.
  module_->AddRef();
  SetId(device.id);
  SetSupportedFormats(supported);
  return true;
}

bool WebRtcVideoCapturer::Init(webrtc::VideoCaptureModule* module) {
  if (module_) {
    LOG(LS_ERROR) << "The capturer is already initialized";
    return false;
  }
  if (!module) {
    LOG(LS_ERROR) << "Invalid VCM supplied";
    return false;
  }
  // TODO(juberti): Set id and formats.
  (module_ = module)->AddRef();
  return true;
}

bool WebRtcVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,
                                               VideoFormat* best_format) {
  if (!best_format) {
    return false;
  }

  if (!VideoCapturer::GetBestCaptureFormat(desired, best_format)) {
    // We maybe using a manually injected VCM which doesn't support enum.
    // Use the desired format as the best format.
    best_format->width = desired.width;
    best_format->height = desired.height;
    best_format->fourcc = FOURCC_I420;
    best_format->interval = desired.interval;
    LOG(LS_INFO) << "Failed to find best capture format,"
                 << " fall back to the requested format "
                 << best_format->ToString();
  }
  return true;
}

CaptureState WebRtcVideoCapturer::Start(const VideoFormat& capture_format) {
  if (!module_) {
    LOG(LS_ERROR) << "The capturer has not been initialized";
    return CS_NO_DEVICE;
  }

  talk_base::CritScope cs(&critical_section_stopping_);
  // TODO(hellner): weird to return failure when it is in fact actually running.
  if (IsRunning()) {
    LOG(LS_ERROR) << "The capturer is already running";
    return CS_FAILED;
  }

  SetCaptureFormat(&capture_format);

  webrtc::VideoCaptureCapability cap;
  if (!FormatToCapability(capture_format, &cap)) {
    LOG(LS_ERROR) << "Invalid capture format specified";
    return CS_FAILED;
  }

  std::string camera_id(GetId());
  uint32 start = talk_base::Time();
  module_->RegisterCaptureDataCallback(*this);
  if (module_->StartCapture(cap) != 0) {
    LOG(LS_ERROR) << "Camera '" << camera_id << "' failed to start";
    return CS_FAILED;
  }

  LOG(LS_INFO) << "Camera '" << camera_id << "' started with format "
               << capture_format.ToString() << ", elapsed time "
               << talk_base::TimeSince(start) << " ms";

  captured_frames_ = 0;
  SetCaptureState(CS_RUNNING);
  return CS_STARTING;
}

// Critical section blocks Stop from shutting down during callbacks from capture
// thread to OnIncomingCapturedFrame. Note that the crit is try-locked in
// OnFrameCaptured, as the lock ordering between this and the system component
// controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;
// Stop -> system stop camera).
void WebRtcVideoCapturer::Stop() {
  talk_base::CritScope cs(&critical_section_stopping_);
  if (IsRunning()) {
    talk_base::Thread::Current()->Clear(this);
    module_->StopCapture();
    module_->DeRegisterCaptureDataCallback();

    // TODO(juberti): Determine if the VCM exposes any drop stats we can use.
    double drop_ratio = 0.0;
    std::string camera_id(GetId());
    LOG(LS_INFO) << "Camera '" << camera_id << "' stopped after capturing "
                 << captured_frames_ << " frames and dropping "
                 << drop_ratio << "%";
  }
  SetCaptureFormat(NULL);
}

bool WebRtcVideoCapturer::IsRunning() {
  return (module_ != NULL && module_->CaptureStarted());
}

bool WebRtcVideoCapturer::GetPreferredFourccs(
    std::vector<uint32>* fourccs) {
  if (!fourccs) {
    return false;
  }

  fourccs->clear();
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    fourccs->push_back(kSupportedFourCCs[i].fourcc);
  }
  return true;
}

void WebRtcVideoCapturer::OnIncomingCapturedFrame(const int32_t id,
    webrtc::I420VideoFrame& sample) {
  // This would be a normal CritScope, except that it's possible that:
  // (1) whatever system component producing this frame has taken a lock, and
  // (2) Stop() probably calls back into that system component, which may take
  // the same lock. Due to the reversed order, we have to try-lock in order to
  // avoid a potential deadlock. Besides, if we can't enter because we're
  // stopping, we may as well drop the frame.
  talk_base::TryCritScope cs(&critical_section_stopping_);
  if (!cs.locked() || !IsRunning()) {
    // Capturer has been stopped or is in the process of stopping.
    return;
  }

  ++captured_frames_;
  // Log the size and pixel aspect ratio of the first captured frame.
  if (1 == captured_frames_) {
    LOG(LS_INFO) << "Captured frame size "
                 << sample.width() << "x" << sample.height()
                 << ". Expected format " << GetCaptureFormat()->ToString();
  }

  // Signal down stream components on captured frame.
  // The CapturedFrame class doesn't support planes. We have to ExtractBuffer
  // to one block for it.
  int length = webrtc::CalcBufferSize(webrtc::kI420,
                                      sample.width(), sample.height());
  capture_buffer_.resize(length);
  // TODO(ronghuawu): Refactor the WebRtcCapturedFrame to avoid memory copy.
  webrtc::ExtractBuffer(sample, length, &capture_buffer_[0]);
  WebRtcCapturedFrame frame(sample, &capture_buffer_[0], length);
  SignalFrameCaptured(this, &frame);
}

void WebRtcVideoCapturer::OnCaptureDelayChanged(const int32_t id,
                                                const int32_t delay) {
  LOG(LS_INFO) << "Capture delay changed to " << delay << " ms";
}

// WebRtcCapturedFrame
WebRtcCapturedFrame::WebRtcCapturedFrame(const webrtc::I420VideoFrame& sample,
                                         void* buffer,
                                         int length) {
  width = sample.width();
  height = sample.height();
  fourcc = FOURCC_I420;
  // TODO(hellner): Support pixel aspect ratio (for OSX).
  pixel_width = 1;
  pixel_height = 1;
  // Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).
  elapsed_time = sample.render_time_ms() * talk_base::kNumNanosecsPerMillisec;
  time_stamp = elapsed_time;
  data_size = length;
  data = buffer;
}

}  // namespace cricket

#endif  // HAVE_WEBRTC_VIDEO
<commit_msg>(Auto)update libjingle 71599033-> 71605904<commit_after>// libjingle
// Copyright 2011 Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. The name of the author may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Implementation of class WebRtcVideoCapturer.

#include "talk/media/webrtc/webrtcvideocapturer.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_WEBRTC_VIDEO
#include "talk/base/criticalsection.h"
#include "talk/base/logging.h"
#include "talk/base/thread.h"
#include "talk/base/timeutils.h"
#include "talk/media/webrtc/webrtcvideoframe.h"

#include "talk/base/win32.h"  // Need this to #include the impl files.
#include "webrtc/modules/video_capture/include/video_capture_factory.h"

namespace cricket {

struct kVideoFourCCEntry {
  uint32 fourcc;
  webrtc::RawVideoType webrtc_type;
};

// This indicates our format preferences and defines a mapping between
// webrtc::RawVideoType (from video_capture_defines.h) to our FOURCCs.
static kVideoFourCCEntry kSupportedFourCCs[] = {
  { FOURCC_I420, webrtc::kVideoI420 },   // 12 bpp, no conversion.
  { FOURCC_YV12, webrtc::kVideoYV12 },   // 12 bpp, no conversion.
  { FOURCC_YUY2, webrtc::kVideoYUY2 },   // 16 bpp, fast conversion.
  { FOURCC_UYVY, webrtc::kVideoUYVY },   // 16 bpp, fast conversion.
  { FOURCC_NV12, webrtc::kVideoNV12 },   // 12 bpp, fast conversion.
  { FOURCC_NV21, webrtc::kVideoNV21 },   // 12 bpp, fast conversion.
  { FOURCC_MJPG, webrtc::kVideoMJPEG },  // compressed, slow conversion.
  { FOURCC_ARGB, webrtc::kVideoARGB },   // 32 bpp, slow conversion.
  { FOURCC_24BG, webrtc::kVideoRGB24 },  // 24 bpp, slow conversion.
};

class WebRtcVcmFactory : public WebRtcVcmFactoryInterface {
 public:
  virtual webrtc::VideoCaptureModule* Create(int id, const char* device) {
    return webrtc::VideoCaptureFactory::Create(id, device);
  }
  virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo(int id) {
    return webrtc::VideoCaptureFactory::CreateDeviceInfo(id);
  }
  virtual void DestroyDeviceInfo(webrtc::VideoCaptureModule::DeviceInfo* info) {
    delete info;
  }
};

static bool CapabilityToFormat(const webrtc::VideoCaptureCapability& cap,
                               VideoFormat* format) {
  uint32 fourcc = 0;
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    if (kSupportedFourCCs[i].webrtc_type == cap.rawType) {
      fourcc = kSupportedFourCCs[i].fourcc;
      break;
    }
  }
  if (fourcc == 0) {
    return false;
  }

  format->fourcc = fourcc;
  format->width = cap.width;
  format->height = cap.height;
  format->interval = VideoFormat::FpsToInterval(cap.maxFPS);
  return true;
}

static bool FormatToCapability(const VideoFormat& format,
                               webrtc::VideoCaptureCapability* cap) {
  webrtc::RawVideoType webrtc_type = webrtc::kVideoUnknown;
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    if (kSupportedFourCCs[i].fourcc == format.fourcc) {
      webrtc_type = kSupportedFourCCs[i].webrtc_type;
      break;
    }
  }
  if (webrtc_type == webrtc::kVideoUnknown) {
    return false;
  }

  cap->width = format.width;
  cap->height = format.height;
  cap->maxFPS = VideoFormat::IntervalToFps(format.interval);
  cap->expectedCaptureDelay = 0;
  cap->rawType = webrtc_type;
  cap->codecType = webrtc::kVideoCodecUnknown;
  cap->interlaced = false;
  return true;
}

///////////////////////////////////////////////////////////////////////////
// Implementation of class WebRtcVideoCapturer
///////////////////////////////////////////////////////////////////////////

WebRtcVideoCapturer::WebRtcVideoCapturer()
    : factory_(new WebRtcVcmFactory),
      module_(NULL),
      captured_frames_(0) {
}

WebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)
    : factory_(factory),
      module_(NULL),
      captured_frames_(0) {
}

WebRtcVideoCapturer::~WebRtcVideoCapturer() {
  if (module_) {
    module_->Release();
  }
}

bool WebRtcVideoCapturer::Init(const Device& device) {
  if (module_) {
    LOG(LS_ERROR) << "The capturer is already initialized";
    return false;
  }

  webrtc::VideoCaptureModule::DeviceInfo* info = factory_->CreateDeviceInfo(0);
  if (!info) {
    return false;
  }

  // Find the desired camera, by name.
  // In the future, comparing IDs will be more robust.
  // TODO(juberti): Figure what's needed to allow this.
  int num_cams = info->NumberOfDevices();
  char vcm_id[256] = "";
  bool found = false;
  for (int index = 0; index < num_cams; ++index) {
    char vcm_name[256];
    if (info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name),
                            vcm_id, ARRAY_SIZE(vcm_id)) != -1) {
      if (device.name == reinterpret_cast<char*>(vcm_name)) {
        found = true;
        break;
      }
    }
  }
  if (!found) {
    LOG(LS_WARNING) << "Failed to find capturer for id: " << device.id;
    factory_->DestroyDeviceInfo(info);
    return false;
  }

  // Enumerate the supported formats.
  // TODO(juberti): Find out why this starts/stops the camera...
  std::vector<VideoFormat> supported;
  int32_t num_caps = info->NumberOfCapabilities(vcm_id);
  for (int32_t i = 0; i < num_caps; ++i) {
    webrtc::VideoCaptureCapability cap;
    if (info->GetCapability(vcm_id, i, cap) != -1) {
      VideoFormat format;
      if (CapabilityToFormat(cap, &format)) {
        supported.push_back(format);
      } else {
        LOG(LS_WARNING) << "Ignoring unsupported WebRTC capture format "
                        << cap.rawType;
      }
    }
  }
  factory_->DestroyDeviceInfo(info);
// TODO(fischman): Remove the following check
// when capabilities for iOS are implemented
// https://code.google.com/p/webrtc/issues/detail?id=2968
#if !defined(IOS)
  if (supported.empty()) {
    LOG(LS_ERROR) << "Failed to find usable formats for id: " << device.id;
    return false;
  }
#endif
  module_ = factory_->Create(0, vcm_id);
  if (!module_) {
    LOG(LS_ERROR) << "Failed to create capturer for id: " << device.id;
    return false;
  }

  // It is safe to change member attributes now.
  module_->AddRef();
  SetId(device.id);
  SetSupportedFormats(supported);
  return true;
}

bool WebRtcVideoCapturer::Init(webrtc::VideoCaptureModule* module) {
  if (module_) {
    LOG(LS_ERROR) << "The capturer is already initialized";
    return false;
  }
  if (!module) {
    LOG(LS_ERROR) << "Invalid VCM supplied";
    return false;
  }
  // TODO(juberti): Set id and formats.
  (module_ = module)->AddRef();
  return true;
}

bool WebRtcVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,
                                               VideoFormat* best_format) {
  if (!best_format) {
    return false;
  }

  if (!VideoCapturer::GetBestCaptureFormat(desired, best_format)) {
    // We maybe using a manually injected VCM which doesn't support enum.
    // Use the desired format as the best format.
    best_format->width = desired.width;
    best_format->height = desired.height;
    best_format->fourcc = FOURCC_I420;
    best_format->interval = desired.interval;
    LOG(LS_INFO) << "Failed to find best capture format,"
                 << " fall back to the requested format "
                 << best_format->ToString();
  }
  return true;
}

CaptureState WebRtcVideoCapturer::Start(const VideoFormat& capture_format) {
  if (!module_) {
    LOG(LS_ERROR) << "The capturer has not been initialized";
    return CS_NO_DEVICE;
  }

  talk_base::CritScope cs(&critical_section_stopping_);
  // TODO(hellner): weird to return failure when it is in fact actually running.
  if (IsRunning()) {
    LOG(LS_ERROR) << "The capturer is already running";
    return CS_FAILED;
  }

  SetCaptureFormat(&capture_format);

  webrtc::VideoCaptureCapability cap;
  if (!FormatToCapability(capture_format, &cap)) {
    LOG(LS_ERROR) << "Invalid capture format specified";
    return CS_FAILED;
  }

  std::string camera_id(GetId());
  uint32 start = talk_base::Time();
  module_->RegisterCaptureDataCallback(*this);
  if (module_->StartCapture(cap) != 0) {
    LOG(LS_ERROR) << "Camera '" << camera_id << "' failed to start";
    return CS_FAILED;
  }

  LOG(LS_INFO) << "Camera '" << camera_id << "' started with format "
               << capture_format.ToString() << ", elapsed time "
               << talk_base::TimeSince(start) << " ms";

  captured_frames_ = 0;
  SetCaptureState(CS_RUNNING);
  return CS_STARTING;
}

// Critical section blocks Stop from shutting down during callbacks from capture
// thread to OnIncomingCapturedFrame. Note that the crit is try-locked in
// OnFrameCaptured, as the lock ordering between this and the system component
// controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;
// Stop -> system stop camera).
void WebRtcVideoCapturer::Stop() {
  talk_base::CritScope cs(&critical_section_stopping_);
  if (IsRunning()) {
    talk_base::Thread::Current()->Clear(this);
    module_->StopCapture();
    module_->DeRegisterCaptureDataCallback();

    // TODO(juberti): Determine if the VCM exposes any drop stats we can use.
    double drop_ratio = 0.0;
    std::string camera_id(GetId());
    LOG(LS_INFO) << "Camera '" << camera_id << "' stopped after capturing "
                 << captured_frames_ << " frames and dropping "
                 << drop_ratio << "%";
  }
  SetCaptureFormat(NULL);
}

bool WebRtcVideoCapturer::IsRunning() {
  return (module_ != NULL && module_->CaptureStarted());
}

bool WebRtcVideoCapturer::GetPreferredFourccs(
    std::vector<uint32>* fourccs) {
  if (!fourccs) {
    return false;
  }

  fourccs->clear();
  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {
    fourccs->push_back(kSupportedFourCCs[i].fourcc);
  }
  return true;
}

void WebRtcVideoCapturer::OnIncomingCapturedFrame(const int32_t id,
    webrtc::I420VideoFrame& sample) {
  // This would be a normal CritScope, except that it's possible that:
  // (1) whatever system component producing this frame has taken a lock, and
  // (2) Stop() probably calls back into that system component, which may take
  // the same lock. Due to the reversed order, we have to try-lock in order to
  // avoid a potential deadlock. Besides, if we can't enter because we're
  // stopping, we may as well drop the frame.
  talk_base::TryCritScope cs(&critical_section_stopping_);
  if (!cs.locked() || !IsRunning()) {
    // Capturer has been stopped or is in the process of stopping.
    return;
  }

  ++captured_frames_;
  // Log the size and pixel aspect ratio of the first captured frame.
  if (1 == captured_frames_) {
    LOG(LS_INFO) << "Captured frame size "
                 << sample.width() << "x" << sample.height()
                 << ". Expected format " << GetCaptureFormat()->ToString();
  }

  // Signal down stream components on captured frame.
  // The CapturedFrame class doesn't support planes. We have to ExtractBuffer
  // to one block for it.
  int length = webrtc::CalcBufferSize(webrtc::kI420,
                                      sample.width(), sample.height());
  capture_buffer_.resize(length);
  // TODO(ronghuawu): Refactor the WebRtcCapturedFrame to avoid memory copy.
  webrtc::ExtractBuffer(sample, length, &capture_buffer_[0]);
  WebRtcCapturedFrame frame(sample, &capture_buffer_[0], length);
  SignalFrameCaptured(this, &frame);
}

void WebRtcVideoCapturer::OnCaptureDelayChanged(const int32_t id,
                                                const int32_t delay) {
  LOG(LS_INFO) << "Capture delay changed to " << delay << " ms";
}

// WebRtcCapturedFrame
WebRtcCapturedFrame::WebRtcCapturedFrame(const webrtc::I420VideoFrame& sample,
                                         void* buffer,
                                         int length) {
  width = sample.width();
  height = sample.height();
  fourcc = FOURCC_I420;
  // TODO(hellner): Support pixel aspect ratio (for OSX).
  pixel_width = 1;
  pixel_height = 1;
  // Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).
  elapsed_time = sample.render_time_ms() * talk_base::kNumNanosecsPerMillisec;
  time_stamp = elapsed_time;
  data_size = length;
  data = buffer;
}

}  // namespace cricket

#endif  // HAVE_WEBRTC_VIDEO
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlpropertymap.h"

#include "qmlopenmetaobject_p.h"

#include <QDebug>

QT_BEGIN_NAMESPACE

//QmlPropertyMapMetaObject lets us listen for changes coming from QML
//so we can emit the changed signal.
class QmlPropertyMapMetaObject : public QmlOpenMetaObject
{
public:
    QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv);

protected:
    virtual void propertyWrite(int index);

private:
    QmlPropertyMap *map;
    QmlPropertyMapPrivate *priv;
};

class QmlPropertyMapPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QmlPropertyMap)
public:
    QmlPropertyMapMetaObject *mo;
    QStringList keys;
    void emitChanged(const QString &key);
};

void QmlPropertyMapPrivate::emitChanged(const QString &key)
{
    Q_Q(QmlPropertyMap);
    emit q->valueChanged(key);
}

QmlPropertyMapMetaObject::QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv) : QmlOpenMetaObject(obj)
{
    map = obj;
    priv = objPriv;
}

void QmlPropertyMapMetaObject::propertyWrite(int index)
{
    priv->emitChanged(QString::fromUtf8(name(index)));
}

/*!
    \class QmlPropertyMap
    \brief The QmlPropertyMap class allows you to set key-value pairs that can be used in bindings.

    QmlPropertyMap provides a convenient way to expose domain data to the UI layer.
    The following example shows how you might declare data in C++ and then
    access it in QML.

    Setup in C++:
    \code
    //create our data
    QmlPropertyMap ownerData;
    ownerData.insert("name", QVariant(QString("John Smith")));
    ownerData.insert("phone", QVariant(QString("555-5555")));

    //expose it to the UI layer
    QmlContext *ctxt = view->bindContext();
    ctxt->setProperty("owner", &data);
    \endcode

    Then, in QML:
    \code
    Text { text: owner.name }
    Text { text: owner.phone }
    \endcode

    The binding is dynamic - whenever a key's value is updated, anything bound to that
    key will be updated as well.

    To detect value changes made in the UI layer you can connect to the valueChanged() signal.
    However, note that valueChanged() is \b NOT emitted when changes are made by calling insert()
    or clear() - it is only emitted when a value is updated from QML.

    \note It is not possible to remove keys from the map; once a key has been added, you can only
    modify or clear its associated value.
*/

/*!
    Constructs a bindable map with parent object \a parent.
*/
QmlPropertyMap::QmlPropertyMap(QObject *parent)
: QObject(*(new QmlPropertyMapPrivate), parent)
{
    Q_D(QmlPropertyMap);
    d->mo = new QmlPropertyMapMetaObject(this, d);
}

/*!
    Destroys the bindable map.
*/
QmlPropertyMap::~QmlPropertyMap()
{
}

/*!
    Clears the value (if any) associated with \a key.
*/
void QmlPropertyMap::clear(const QString &key)
{
    Q_D(QmlPropertyMap);
    d->mo->setValue(key.toUtf8(), QVariant());
}

/*!
    Returns the value associated with \a key.

    If no value has been set for this key (or if the value has been cleared),
    an invalid QVariant is returned.
*/
QVariant QmlPropertyMap::value(const QString &key) const
{
    Q_D(const QmlPropertyMap);
    return d->mo->value(key.toUtf8());
}

/*!
    Sets the value associated with \a key to \a value.

    If the key doesn't exist, it is automatically created.
*/
void QmlPropertyMap::insert(const QString &key, const QVariant &value)
{
    Q_D(QmlPropertyMap);
    if (!d->keys.contains(key))
        d->keys.append(key);
    d->mo->setValue(key.toUtf8(), value);
}

/*!
    Returns the list of keys.

    Keys that have been cleared will still appear in this list, even though their
    associated values are invalid QVariants.
*/
QStringList QmlPropertyMap::keys() const
{
    Q_D(const QmlPropertyMap);
    return d->keys;
}

/*!
    \overload

    Same as size().
*/
int QmlPropertyMap::count() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.count();
}

/*!
    Returns the number of keys in the map.

    \sa isEmpty(), count()
*/
int QmlPropertyMap::size() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.size();
}

/*!
    Returns true if the map contains no keys; otherwise returns
    false.

    \sa size()
*/
bool QmlPropertyMap::isEmpty() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.isEmpty();
}

/*!
    Returns true if the map contains \a key.

    \sa size()
*/
bool QmlPropertyMap::contains(const QString &key) const
{
    Q_D(const QmlPropertyMap);
    return d->keys.contains(key);
}

/*!
    Returns the value associated with the key \a key as a modifiable
    reference.

    If the map contains no item with key \a key, the function inserts
    an invalid QVariant into the map with key \a key, and
    returns a reference to it.

    \sa insert(), value()
*/
QVariant &QmlPropertyMap::operator[](const QString &key)
{
    //### optimize
    Q_D(QmlPropertyMap);
    QByteArray utf8key = key.toUtf8();
    if (!d->keys.contains(key)) {
        d->keys.append(key);
        d->mo->setValue(utf8key, QVariant());   //force creation -- needed below
    }

    return (*(d->mo))[utf8key];
}

/*!
    \overload

    Same as value().
*/
const QVariant QmlPropertyMap::operator[](const QString &key) const
{
    return value(key);
}

/*!
    \fn void QmlPropertyMap::valueChanged(const QString &key)
    This signal is emitted whenever one of the values in the map is changed. \a key
    is the key corresponding to the value that was changed.
*/

QT_END_NAMESPACE
<commit_msg>Clarify QmlPropertyMap::valueChanged docs.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlpropertymap.h"

#include "qmlopenmetaobject_p.h"

#include <QDebug>

QT_BEGIN_NAMESPACE

//QmlPropertyMapMetaObject lets us listen for changes coming from QML
//so we can emit the changed signal.
class QmlPropertyMapMetaObject : public QmlOpenMetaObject
{
public:
    QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv);

protected:
    virtual void propertyWrite(int index);

private:
    QmlPropertyMap *map;
    QmlPropertyMapPrivate *priv;
};

class QmlPropertyMapPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QmlPropertyMap)
public:
    QmlPropertyMapMetaObject *mo;
    QStringList keys;
    void emitChanged(const QString &key);
};

void QmlPropertyMapPrivate::emitChanged(const QString &key)
{
    Q_Q(QmlPropertyMap);
    emit q->valueChanged(key);
}

QmlPropertyMapMetaObject::QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv) : QmlOpenMetaObject(obj)
{
    map = obj;
    priv = objPriv;
}

void QmlPropertyMapMetaObject::propertyWrite(int index)
{
    priv->emitChanged(QString::fromUtf8(name(index)));
}

/*!
    \class QmlPropertyMap
    \brief The QmlPropertyMap class allows you to set key-value pairs that can be used in bindings.

    QmlPropertyMap provides a convenient way to expose domain data to the UI layer.
    The following example shows how you might declare data in C++ and then
    access it in QML.

    Setup in C++:
    \code
    //create our data
    QmlPropertyMap ownerData;
    ownerData.insert("name", QVariant(QString("John Smith")));
    ownerData.insert("phone", QVariant(QString("555-5555")));

    //expose it to the UI layer
    QmlContext *ctxt = view->bindContext();
    ctxt->setProperty("owner", &data);
    \endcode

    Then, in QML:
    \code
    Text { text: owner.name }
    Text { text: owner.phone }
    \endcode

    The binding is dynamic - whenever a key's value is updated, anything bound to that
    key will be updated as well.

    To detect value changes made in the UI layer you can connect to the valueChanged() signal.
    However, note that valueChanged() is \bold NOT emitted when changes are made by calling insert()
    or clear() - it is only emitted when a value is updated from QML.

    \note It is not possible to remove keys from the map; once a key has been added, you can only
    modify or clear its associated value.
*/

/*!
    Constructs a bindable map with parent object \a parent.
*/
QmlPropertyMap::QmlPropertyMap(QObject *parent)
: QObject(*(new QmlPropertyMapPrivate), parent)
{
    Q_D(QmlPropertyMap);
    d->mo = new QmlPropertyMapMetaObject(this, d);
}

/*!
    Destroys the bindable map.
*/
QmlPropertyMap::~QmlPropertyMap()
{
}

/*!
    Clears the value (if any) associated with \a key.
*/
void QmlPropertyMap::clear(const QString &key)
{
    Q_D(QmlPropertyMap);
    d->mo->setValue(key.toUtf8(), QVariant());
}

/*!
    Returns the value associated with \a key.

    If no value has been set for this key (or if the value has been cleared),
    an invalid QVariant is returned.
*/
QVariant QmlPropertyMap::value(const QString &key) const
{
    Q_D(const QmlPropertyMap);
    return d->mo->value(key.toUtf8());
}

/*!
    Sets the value associated with \a key to \a value.

    If the key doesn't exist, it is automatically created.
*/
void QmlPropertyMap::insert(const QString &key, const QVariant &value)
{
    Q_D(QmlPropertyMap);
    if (!d->keys.contains(key))
        d->keys.append(key);
    d->mo->setValue(key.toUtf8(), value);
}

/*!
    Returns the list of keys.

    Keys that have been cleared will still appear in this list, even though their
    associated values are invalid QVariants.
*/
QStringList QmlPropertyMap::keys() const
{
    Q_D(const QmlPropertyMap);
    return d->keys;
}

/*!
    \overload

    Same as size().
*/
int QmlPropertyMap::count() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.count();
}

/*!
    Returns the number of keys in the map.

    \sa isEmpty(), count()
*/
int QmlPropertyMap::size() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.size();
}

/*!
    Returns true if the map contains no keys; otherwise returns
    false.

    \sa size()
*/
bool QmlPropertyMap::isEmpty() const
{
    Q_D(const QmlPropertyMap);
    return d->keys.isEmpty();
}

/*!
    Returns true if the map contains \a key.

    \sa size()
*/
bool QmlPropertyMap::contains(const QString &key) const
{
    Q_D(const QmlPropertyMap);
    return d->keys.contains(key);
}

/*!
    Returns the value associated with the key \a key as a modifiable
    reference.

    If the map contains no item with key \a key, the function inserts
    an invalid QVariant into the map with key \a key, and
    returns a reference to it.

    \sa insert(), value()
*/
QVariant &QmlPropertyMap::operator[](const QString &key)
{
    //### optimize
    Q_D(QmlPropertyMap);
    QByteArray utf8key = key.toUtf8();
    if (!d->keys.contains(key)) {
        d->keys.append(key);
        d->mo->setValue(utf8key, QVariant());   //force creation -- needed below
    }

    return (*(d->mo))[utf8key];
}

/*!
    \overload

    Same as value().
*/
const QVariant QmlPropertyMap::operator[](const QString &key) const
{
    return value(key);
}

/*!
    \fn void QmlPropertyMap::valueChanged(const QString &key)
    This signal is emitted whenever one of the values in the map is changed. \a key
    is the key corresponding to the value that was changed.

    \note valueChanged() is \bold NOT emitted when changes are made by calling insert()
    or clear() - it is only emitted when a value is updated from QML.
*/

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include <Winbase.h>
<commit_msg>yaaaY!!! it works!!<commit_after>
#define _WIN32_WINNT NTDDI_WINXP
#include <Windows.h>

int main()
{
     SYSTEM_POWER_STATUS syspwr;
     if (GetSystemPowerStatus(&syspwr))
	  std::cout << "AC line active: " << syspwr.ACLineStatus == 1 ? "yes" : "no" << std::endl;
     return 0;
}
<|endoftext|>


<commit_before>/*
*  Copyright (c) 2014-present, Facebook, Inc.
*  All rights reserved.
*
*  This source code is licensed under the BSD-style license found in the
*  LICENSE file in the root directory of this source tree. An additional grant
*  of patent rights can be found in the PATENTS file in the same directory.
*
*/

#define WIN32_LEAN_AND_MEAN

#include <memory>
#include <string>
#include <windows.h>
#include <winsock2.h>

#include <wS2tcpip.h>
#include <ws2ipdef.h>

#include <iphlpapi.h>
#include <mstcpip.h>

#include <boost/algorithm/string/join.hpp>
#include <osquery/logger.h>
#include <osquery/tables.h>

#include "osquery/core/conversions.h"
#include "osquery/core/windows/wmi.h"

namespace osquery {
namespace tables {

std::map<DWORD, IP_ADAPTER_INFO> getAdapterAddressMapping() {
  std::map<DWORD, IP_ADAPTER_INFO> returnMapping;
  auto dwBufLen = 0UL;
  auto dwStatus = GetAdaptersInfo(NULL, &dwBufLen);

  if (dwStatus != ERROR_BUFFER_OVERFLOW) {
    return returnMapping;
  }

  std::vector<BYTE> buffer(dwBufLen);
  auto pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());
  dwStatus = GetAdaptersInfo(pAdapterInfo, &dwBufLen);

  if (dwStatus != NO_ERROR) {
    return returnMapping;
  }

  while (pAdapterInfo != nullptr) {
    const auto& adapter = *pAdapterInfo;
    const auto& index = pAdapterInfo->Index;
    returnMapping.insert(std::make_pair(index, adapter));
    pAdapterInfo = pAdapterInfo->Next;
  }

  buffer.clear();

  return returnMapping;
}

std::map<unsigned long, MIB_IPINTERFACE_ROW> getInterfaceRowMapping(
    int type = AF_UNSPEC) {
  std::map<unsigned long, MIB_IPINTERFACE_ROW> returnMapping;
  PMIB_IPINTERFACE_TABLE interfaces;
  auto dwRetVal = GetIpInterfaceTable(type, &interfaces);

  if (dwRetVal != NO_ERROR) {
    return returnMapping;
  }

  for (unsigned long i = 0; i < interfaces->NumEntries; ++i) {
    MIB_IPINTERFACE_ROW currentRow = interfaces->Table[i];
    returnMapping.insert(std::make_pair(currentRow.InterfaceIndex, currentRow));
  }

  FreeMibTable(interfaces);

  return returnMapping;
}

QueryData genRoutes(QueryContext& context) {
  QueryData results;
  PMIB_IPFORWARD_TABLE2 ipTable = nullptr;
  auto result = GetIpForwardTable2(AF_UNSPEC, &ipTable);

  if (result != NO_ERROR) {
    FreeMibTable(ipTable);

    return results;
  }

  auto numEntries = ipTable[0].NumEntries;
  auto interfaces = getInterfaceRowMapping();
  auto adapters = getAdapterAddressMapping();

  for (unsigned long i = 0; i < numEntries; ++i) {
    Row r;
    std::string interfaceIpAddress;
    const auto& currentRow = ipTable[0].Table[i];
    auto addrFamily = currentRow.DestinationPrefix.Prefix.si_family;
    auto actualInterface = interfaces.at(currentRow.InterfaceIndex);
    if (addrFamily == AF_INET6) {
      std::vector<char> buffer(INET6_ADDRSTRLEN);

      r["mtu"] = INTEGER(actualInterface.NlMtu);
      // These are all technically "on-link" addresses according to
      // `route print -6`.
      r["type"] = "local";
      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv6.sin6_addr;
      auto gateway = currentRow.NextHop.Ipv6.sin6_addr;

      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());
      r["destination"] = SQL_TEXT(buffer.data());
      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());
      r["gateway"] = SQL_TEXT(buffer.data());
    } else if (addrFamily == AF_INET) {
      std::vector<char> buffer(INET_ADDRSTRLEN);
      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv4.sin_addr;
      auto gateway = currentRow.NextHop.Ipv4.sin_addr;

      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());
      r["destination"] = SQL_TEXT(buffer.data());
      buffer.clear();
      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());
      r["gateway"] = SQL_TEXT(buffer.data());

      // The software loopback is not returned by GetAdaptersInfo, so any
      // lookups into that index must be skipped and default values set.
      IP_ADAPTER_INFO actualAdapter;
      if (currentRow.InterfaceIndex != 1) {
        try {
          actualAdapter = adapters.at(currentRow.InterfaceIndex);
          interfaceIpAddress = actualAdapter.IpAddressList.IpAddress.String;
          r["mtu"] = INTEGER(actualInterface.NlMtu);
        } catch (const std::out_of_range& oor) {
          LOG(ERROR) << "Error looking up interface "
                     << currentRow.InterfaceIndex;
          LOG(ERROR) << oor.what();
        }
      } else {
        interfaceIpAddress = "127.0.0.1";
        r["mtu"] = UNSIGNED_BIGINT(0xFFFFFFFF);
      }
      r["type"] = currentRow.Loopback ? "local" : "remote";
    }
    r["interface"] = SQL_TEXT(interfaceIpAddress);
    r["metric"] = INTEGER(currentRow.Metric + actualInterface.Metric);
    r["netmask"] =
        SQL_TEXT(std::to_string(currentRow.DestinationPrefix.PrefixLength));
    // TODO: implement routes flags
    r["flags"] = SQL_TEXT("-1");

    results.push_back(r);
  }

  // Cleanup
  FreeMibTable(ipTable);

  return results;
}
}
}<commit_msg>[fix #3257] report proper routes for 0.0.0.0 (#3259)<commit_after>/*
*  Copyright (c) 2014-present, Facebook, Inc.
*  All rights reserved.
*
*  This source code is licensed under the BSD-style license found in the
*  LICENSE file in the root directory of this source tree. An additional grant
*  of patent rights can be found in the PATENTS file in the same directory.
*
*/

#define WIN32_LEAN_AND_MEAN

#include <memory>
#include <string>
#include <windows.h>
#include <winsock2.h>

#include <wS2tcpip.h>
#include <ws2ipdef.h>

#include <iphlpapi.h>
#include <mstcpip.h>

#include <boost/algorithm/string/join.hpp>
#include <osquery/logger.h>
#include <osquery/tables.h>

#include "osquery/core/conversions.h"
#include "osquery/core/windows/wmi.h"

namespace osquery {
namespace tables {

std::map<DWORD, IP_ADAPTER_INFO> getAdapterAddressMapping() {
  std::map<DWORD, IP_ADAPTER_INFO> returnMapping;
  auto dwBufLen = 0UL;
  auto dwStatus = GetAdaptersInfo(NULL, &dwBufLen);

  if (dwStatus != ERROR_BUFFER_OVERFLOW) {
    return returnMapping;
  }

  std::vector<BYTE> buffer(dwBufLen);
  auto pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());
  dwStatus = GetAdaptersInfo(pAdapterInfo, &dwBufLen);

  if (dwStatus != NO_ERROR) {
    return returnMapping;
  }

  while (pAdapterInfo != nullptr) {
    const auto& adapter = *pAdapterInfo;
    const auto& index = pAdapterInfo->Index;
    returnMapping.insert(std::make_pair(index, adapter));
    pAdapterInfo = pAdapterInfo->Next;
  }

  buffer.clear();

  return returnMapping;
}

std::map<unsigned long, MIB_IPINTERFACE_ROW> getInterfaceRowMapping(
    int type = AF_UNSPEC) {
  std::map<unsigned long, MIB_IPINTERFACE_ROW> returnMapping;
  PMIB_IPINTERFACE_TABLE interfaces;
  auto dwRetVal = GetIpInterfaceTable(type, &interfaces);

  if (dwRetVal != NO_ERROR) {
    return returnMapping;
  }

  for (unsigned long i = 0; i < interfaces->NumEntries; ++i) {
    MIB_IPINTERFACE_ROW currentRow = interfaces->Table[i];
    returnMapping.insert(std::make_pair(currentRow.InterfaceIndex, currentRow));
  }

  FreeMibTable(interfaces);

  return returnMapping;
}

QueryData genRoutes(QueryContext& context) {
  QueryData results;
  PMIB_IPFORWARD_TABLE2 ipTable = nullptr;
  auto result = GetIpForwardTable2(AF_UNSPEC, &ipTable);

  if (result != NO_ERROR) {
    FreeMibTable(ipTable);

    return results;
  }

  auto numEntries = ipTable[0].NumEntries;
  auto interfaces = getInterfaceRowMapping();
  auto adapters = getAdapterAddressMapping();

  for (unsigned long i = 0; i < numEntries; ++i) {
    Row r;
    std::string interfaceIpAddress;
    const auto& currentRow = ipTable[0].Table[i];
    auto addrFamily = currentRow.DestinationPrefix.Prefix.si_family;
    auto actualInterface = interfaces.at(currentRow.InterfaceIndex);
    if (addrFamily == AF_INET6) {
      std::vector<char> buffer(INET6_ADDRSTRLEN);

      r["mtu"] = INTEGER(actualInterface.NlMtu);
      // These are all technically "on-link" addresses according to
      // `route print -6`.
      r["type"] = "local";
      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv6.sin6_addr;
      auto gateway = currentRow.NextHop.Ipv6.sin6_addr;

      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());
      r["destination"] = SQL_TEXT(buffer.data());
      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());
      r["gateway"] = SQL_TEXT(buffer.data());
    } else if (addrFamily == AF_INET) {
      std::vector<char> buffer(INET_ADDRSTRLEN);
      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv4.sin_addr;
      auto gateway = currentRow.NextHop.Ipv4.sin_addr;

      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());
      r["destination"] = SQL_TEXT(buffer.data());
      buffer.clear();

      // The software loopback is not returned by GetAdaptersInfo, so any
      // lookups into that index must be skipped and default values set.
      IP_ADAPTER_INFO actualAdapter;
      if (currentRow.InterfaceIndex != 1) {
        try {
          actualAdapter = adapters.at(currentRow.InterfaceIndex);
          interfaceIpAddress = actualAdapter.IpAddressList.IpAddress.String;
          r["gateway"] = SQL_TEXT(actualAdapter.GatewayList.IpAddress.String);
          r["mtu"] = INTEGER(actualInterface.NlMtu);
        } catch (const std::out_of_range& oor) {
          LOG(ERROR) << "Error looking up interface "
                     << currentRow.InterfaceIndex;
          LOG(ERROR) << oor.what();
        }
      } else {
        interfaceIpAddress = "127.0.0.1";
        InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());
        r["gateway"] = SQL_TEXT(buffer.data());
        r["mtu"] = UNSIGNED_BIGINT(0xFFFFFFFF);
        buffer.clear();
      }
      r["type"] = currentRow.Loopback ? "local" : "remote";
    }
    r["interface"] = SQL_TEXT(interfaceIpAddress);
    r["metric"] = INTEGER(currentRow.Metric + actualInterface.Metric);
    r["netmask"] =
        SQL_TEXT(std::to_string(currentRow.DestinationPrefix.PrefixLength));
    // TODO: implement routes flags
    r["flags"] = SQL_TEXT("-1");

    results.push_back(r);
  }

  // Cleanup
  FreeMibTable(ipTable);

  return results;
}
}
}<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <queue>

namespace AGE
{
	class ObjectPoolBase
	{
	public:
		ObjectPoolBase(std::size_t chunkSize);
		ObjectPoolBase() = delete;
		virtual ~ObjectPoolBase();
		virtual void destroy(void *ptr) = 0;
	protected:
		std::size_t _chunkSize;
		std::size_t _objectSize;
	};

	template <typename Type>
	class ObjectPool : public ObjectPoolBase
	{
	private:
		template <typename T>
		struct Chunk
		{
			Chunk(std::size_t size)
			{
				data = new char[sizeof(T) * size];
				for (auto i = 0; i < size; ++i)
				{
					trash.push(i);
				}
				sizeOfT = sizeof(T);
				from = (std::size_t)(data);
				to = from + sizeOfT * size;
			}

			~Chunk()
			{
				delete []data;
			}

			char *data;
			std::queue < std::size_t > trash;
			std::size_t sizeOfT;
			std::size_t from;
			std::size_t to;
			inline bool hasEmptyPlace() { return trash.size() > 0; }
			inline bool isIn(std::size_t addr) { return from <= addr && to >= addr; }

		};
	public:
		ObjectPool(std::size_t chunkSize = 1024)
			: ObjectPoolBase(chunkSize)
		{}

		virtual ~ObjectPool()
		{
			// very very dirty
			// for the moment it's leaking
		}

		virtual void destroy(void *ptr) final
		{
			destroy((Type*)(ptr));
		}

		void destroy(Type *ptr)
		{
			if (!ptr)
				return;
			size_t addr = (size_t)(ptr);
			for (auto &e : _chunks)
			{
				if (e.isIn(addr))
				{
					ptr->~Type();
					e.trash.push((addr - e.from) / e.sizeOfT);
					return;
				}
			}
			assert(false);
		}

		Type *create()
		{
			Chunk<Type> *chunk = nullptr;

			for (auto &e : _chunks)
			{
				if (e.hasEmptyPlace())
				{
					chunk = &e;
					break;
				}
			}

			if (chunk == nullptr)
			{
				_chunks.emplace_back<Chunk<Type>>(_chunkSize);
				chunk = &_chunks.back();
			}

			auto index = chunk->trash.front();
			chunk->trash.pop();
			Type *res = new (chunk->data + chunk->sizeOfT * index) Type();
			return res;
		}

		std::vector <Chunk<Type>> _chunks;
	};
}<commit_msg>object pool fixed<commit_after>#pragma once

#include <vector>
#include <queue>

namespace AGE
{
	class ObjectPoolBase
	{
	public:
		ObjectPoolBase(std::size_t chunkSize);
		ObjectPoolBase() = delete;
		virtual ~ObjectPoolBase();
		virtual void destroy(void *ptr) = 0;
	protected:
		std::size_t _chunkSize;
		std::size_t _objectSize;
	};

	template <typename Type>
	class ObjectPool : public ObjectPoolBase
	{
	private:
		template <typename T>
		struct Chunk
		{
			Chunk()
				: data(nullptr)
				, from(0)
				, to(0)
				, sizeOfT(0)
			{
			}

			void init(std::size_t size)
			{
				assert(data == nullptr);
				data = new char[sizeof(T) * size];
				for (auto i = 0; i < size; ++i)
				{
					trash.push(i);
				}
				sizeOfT = sizeof(T);
				from = (std::size_t)(data);
				to = from + sizeOfT * size;
			}

			Chunk(Chunk &&o)
				: data(nullptr)
				, from(0)
				, to(0)
				, sizeOfT(0)
			{
				std::swap(o.data, data);
				sizeOfT = std::move(o.sizeOfT);
				from = std::move(o.from);
				to = std::move(o.to);
			}

			Chunk(const Chunk &o) = delete;
			Chunk &operator=(const Chunk &o) = delete;
			Chunk &operator=(Chunk &&o) = delete;

			~Chunk()
			{
				if (data)
				{
					delete[]data;
				}
			}

			char *data;
			std::queue < std::size_t > trash;
			std::size_t sizeOfT;
			std::size_t from;
			std::size_t to;
			inline bool hasEmptyPlace() { return trash.size() > 0; }
			inline bool isIn(std::size_t addr) { return from <= addr && to >= addr; }

		};
	public:
		ObjectPool(std::size_t chunkSize = 1024)
			: ObjectPoolBase(chunkSize)
		{}

		virtual ~ObjectPool()
		{
			// very very dirty
			// for the moment it's leaking
		}

		virtual void destroy(void *ptr) final
		{
			destroy((Type*)(ptr));
		}

		void destroy(Type *ptr)
		{
			if (!ptr)
				return;
			size_t addr = (size_t)(ptr);
			for (auto &e : _chunks)
			{
				if (e.isIn(addr))
				{
					ptr->~Type();
					e.trash.push((addr - e.from) / e.sizeOfT);
					return;
				}
			}
			assert(false);
		}

		Type *create()
		{
			Chunk<Type> *chunk = nullptr;

			for (auto &e : _chunks)
			{
				if (e.hasEmptyPlace())
				{
					chunk = &e;
					break;
				}
			}

			if (chunk == nullptr)
			{
				_chunks.push_back(Chunk<Type>());
				chunk = &_chunks.back();
				chunk->init(_chunkSize);
			}

			auto index = chunk->trash.front();
			chunk->trash.pop();
			Type *res = new (chunk->data + chunk->sizeOfT * index) Type();
			return res;
		}

		std::vector <Chunk<Type>> _chunks;
	};
}<|endoftext|>


<commit_before>#include "scanningsonar_form.h"
#include "ui_scanningsonar_form.h"
#include "sonarreturndata.h"
#include <Framework/dataloghelper.h>

ScanningSonarForm::ScanningSonarForm(Module_ScanningSonar* sonar,QWidget *parent) :
        QWidget(parent),
        ui(new Ui::ScanningSonarForm),
        scene()
{
    ui->setupUi(this);
    this->sonar = sonar;

    oldHeading = NAN;
    oldStepSize = 0;

    logger = Log4Qt::Logger::logger("ScanningSonarForm");

    this->ui->graphicsView->setScene(&scene);
    scanLine = scene.addLine(0,0,0,50, QPen(QColor("red")));
    scanLine->setZValue(20);

    scene.addLine(-50,0,50,0,QPen(QColor("white")))->setZValue(10);
    scene.addLine(0,-50,0,50,QPen(QColor("white")))->setZValue(10);
    scene.addEllipse(-50,-50,100,100,QPen(QColor("white")))->setZValue(10);
    scene.addEllipse(-40,-40,80,80,QPen(QColor("white")))->setZValue(10);
    scene.addEllipse(-30,-30,60,60,QPen(QColor("white")))->setZValue(10);
    scene.addEllipse(-20,-20,40,40,QPen(QColor("white")))->setZValue(10);
    scene.addEllipse(-10,-10,20,20,QPen(QColor("white")))->setZValue(10);

    connect(sonar, SIGNAL(newSonarData(SonarReturnData)), this, SLOT(updateSonarView(SonarReturnData)));

    ui->serialPort->setText(sonar->getSettingsValue("serialPort").toString());
    ui->frequency->setCurrentIndex(sonar->getSettingsValue("frequency").toInt());
    ui->gain->setValue(sonar->getSettingsValue("gain").toInt());
    ui->pulseLength->setValue(sonar->getSettingsValue("pulseLength").toInt());
    ui->range->setValue(sonar->getSettingsValue("range").toInt());
    ui->sectorWidth->setValue(sonar->getSettingsValue("sectorWidth").toInt());
    ui->stepSize->setCurrentIndex(sonar->getSettingsValue("stepSize").toInt()-1);
    ui->switchDelay->setText(sonar->getSettingsValue("switchDelay").toString());
    ui->trainAngle->setText(sonar->getSettingsValue("trainAngle").toString());
    ui->dataPoints->setText(sonar->getSettingsValue("dataPoints").toString());

    ui->sourceFile->setChecked(sonar->getSettingsValue("readFromFile").toBool());
    ui->sourceSerial->setChecked(!sonar->getSettingsValue("readFromFile").toBool());
    ui->fileName->setText(sonar->getSettingsValue("filename").toString());
    ui->enableRecording->setChecked(sonar->getSettingsValue("enableRecording").toBool());
    ui->fileReaderDelay->setValue(sonar->getSettingsValue("fileReaderDelay").toInt());
    ui->formatCSV->setChecked(sonar->getSettingsValue("formatCSV").toBool());
    ui->format852->setChecked(!sonar->getSettingsValue("formatCSV").toBool());
    ui->startTime->setDateTime(sonar->getSettingsValue("startTime").toDateTime());

    ui->recorderFilename->setText(DataLogHelper::getLogDir()+"sonarlog.XXX");
}

ScanningSonarForm::~ScanningSonarForm()
{
    delete ui;
}

void ScanningSonarForm::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ScanningSonarForm::updateSonarView(const SonarReturnData data)
{
    float n = data.getEchoData().length();
    float range = data.getRange();

    if (oldStepSize != data.switchCommand.stepSize) {
        oldStepSize = data.switchCommand.stepSize;
        foreach (QGraphicsPolygonItem* o, queue) {
            delete o;
        }
        queue.clear();
    }

    ui->time->setDateTime(data.switchCommand.time);
    ui->heading->setText(QString::number(data.getHeadPosition()));
    ui->gain_2->setText(QString::number(data.switchCommand.startGain));
    ui->range_2->setText(QString::number(data.getRange()));

    // TODO: if any of the parameters have changed; reset the scene

    float newHeading = data.getHeadPosition();
    int bla = oldHeading;
    bool isnumber = (bla != 0);

    if(ui->checkBox->isChecked() && isnumber && (fabs(newHeading - oldHeading)<20 || fabs(newHeading - oldHeading)>340))
    {

        QPolygonF polygon;

        QPointF endPoint1 = QTransform().rotate(oldHeading).map(QPointF(range,0));
        QPointF endPoint2 = QTransform().rotate(newHeading).map(QPointF(range,0));

        polygon << QPointF(0,0) << endPoint1 << endPoint2;
        QGraphicsPolygonItem *it = scene.addPolygon(polygon,QPen(Qt::NoPen));
        queue.append(it);

        scanLine->setRotation(newHeading-90);

        QLinearGradient g(QPointF(0, 0), endPoint2);
        for (int i = 0; i < n; i++) {
            char b = data.getEchoData()[i];
            g.setColorAt(1.0*i/n,QColor(0,2*b,0));
        }
        it->setBrush(QBrush(g));

        // this should ensure that a full circle is conserved even at highest resolution
        // it may result in overlay, but this doesn't matter since newer items will always
        // be drawn on top of older ones.
        // 480: don't ask, it just works :)
        while (queue.size()>480/(oldStepSize*3+3)) {
            delete queue.takeFirst();
        }

    }

    oldHeading = newHeading;
}

void ScanningSonarForm::on_save_clicked()
{
    sonar->setSettingsValue("serialPort", ui->serialPort->text());
    sonar->setSettingsValue("frequency", ui->frequency->currentIndex());
    sonar->setSettingsValue("gain", ui->gain->value());
    sonar->setSettingsValue("pulseLength", ui->pulseLength->value());
    sonar->setSettingsValue("range", ui->range->value());
    sonar->setSettingsValue("sectorWidth", ui->sectorWidth->value());
    sonar->setSettingsValue("stepSize", ui->stepSize->currentIndex()+1);
    sonar->setSettingsValue("switchDelay", ui->switchDelay->text().toInt());
    sonar->setSettingsValue("trainAngle", ui->trainAngle->text().toInt());
    sonar->setSettingsValue("dataPoints", ui->dataPoints->text().toInt());

    QTimer::singleShot(0,sonar,SLOT(reset()));

    // the scan resolution may have changed, clear the graphics scene
    foreach(QGraphicsItem* g, queue) {
        delete queue.takeFirst();
    }
}

void ScanningSonarForm::on_fileCfgApply_clicked()
{
    sonar->setSettingsValue("readFromFile", ui->sourceFile->isChecked());
    sonar->setSettingsValue("filename", ui->fileName->text());
    sonar->setSettingsValue("fileReaderDelay", ui->fileReaderDelay->value());
    sonar->setSettingsValue("enableRecording", ui->enableRecording->isChecked());
    sonar->setSettingsValue("formatCSV", ui->formatCSV->isChecked());
    sonar->setSettingsValue("startTime", ui->startTime->dateTime());

    // richtiges reset?
    QTimer::singleShot(0,sonar,SLOT(reset()));

}

void ScanningSonarForm::on_fileReaderDelay_valueChanged(int )
{
    sonar->setSettingsValue("fileReaderDelay", ui->fileReaderDelay->value());
}

void ScanningSonarForm::on_selFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
         "Open Sonar Recording", ui->fileName->text(), "Recording (*.852)");

    if (fileName.length()>0)
        ui->fileName->setText(fileName);
}
<commit_msg>changed sonar view to black/white with red lines<commit_after>#include "scanningsonar_form.h"
#include "ui_scanningsonar_form.h"
#include "sonarreturndata.h"
#include <Framework/dataloghelper.h>

ScanningSonarForm::ScanningSonarForm(Module_ScanningSonar* sonar,QWidget *parent) :
        QWidget(parent),
        ui(new Ui::ScanningSonarForm),
        scene()
{
    ui->setupUi(this);
    this->sonar = sonar;

    oldHeading = NAN;
    oldStepSize = 0;

    logger = Log4Qt::Logger::logger("ScanningSonarForm");

    this->ui->graphicsView->setScene(&scene);
    scanLine = scene.addLine(0,0,0,50, QPen(QColor("red")));
    scanLine->setZValue(20);

    scene.addLine(-50,0,50,0,QPen(QColor("red")))->setZValue(10);
    scene.addLine(0,-50,0,50,QPen(QColor("red")))->setZValue(10);
    scene.addEllipse(-50,-50,100,100,QPen(QColor("red")))->setZValue(10);
    scene.addEllipse(-40,-40,80,80,QPen(QColor("red")))->setZValue(10);
    scene.addEllipse(-30,-30,60,60,QPen(QColor("red")))->setZValue(10);
    scene.addEllipse(-20,-20,40,40,QPen(QColor("red")))->setZValue(10);
    scene.addEllipse(-10,-10,20,20,QPen(QColor("red")))->setZValue(10);

    connect(sonar, SIGNAL(newSonarData(SonarReturnData)), this, SLOT(updateSonarView(SonarReturnData)));

    ui->serialPort->setText(sonar->getSettingsValue("serialPort").toString());
    ui->frequency->setCurrentIndex(sonar->getSettingsValue("frequency").toInt());
    ui->gain->setValue(sonar->getSettingsValue("gain").toInt());
    ui->pulseLength->setValue(sonar->getSettingsValue("pulseLength").toInt());
    ui->range->setValue(sonar->getSettingsValue("range").toInt());
    ui->sectorWidth->setValue(sonar->getSettingsValue("sectorWidth").toInt());
    ui->stepSize->setCurrentIndex(sonar->getSettingsValue("stepSize").toInt()-1);
    ui->switchDelay->setText(sonar->getSettingsValue("switchDelay").toString());
    ui->trainAngle->setText(sonar->getSettingsValue("trainAngle").toString());
    ui->dataPoints->setText(sonar->getSettingsValue("dataPoints").toString());

    ui->sourceFile->setChecked(sonar->getSettingsValue("readFromFile").toBool());
    ui->sourceSerial->setChecked(!sonar->getSettingsValue("readFromFile").toBool());
    ui->fileName->setText(sonar->getSettingsValue("filename").toString());
    ui->enableRecording->setChecked(sonar->getSettingsValue("enableRecording").toBool());
    ui->fileReaderDelay->setValue(sonar->getSettingsValue("fileReaderDelay").toInt());
    ui->formatCSV->setChecked(sonar->getSettingsValue("formatCSV").toBool());
    ui->format852->setChecked(!sonar->getSettingsValue("formatCSV").toBool());
    ui->startTime->setDateTime(sonar->getSettingsValue("startTime").toDateTime());

    ui->recorderFilename->setText(DataLogHelper::getLogDir()+"sonarlog.XXX");
}

ScanningSonarForm::~ScanningSonarForm()
{
    delete ui;
}

void ScanningSonarForm::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ScanningSonarForm::updateSonarView(const SonarReturnData data)
{
    float n = data.getEchoData().length();
    float range = data.getRange();

    if (oldStepSize != data.switchCommand.stepSize) {
        oldStepSize = data.switchCommand.stepSize;
        foreach (QGraphicsPolygonItem* o, queue) {
            delete o;
        }
        queue.clear();
    }

    ui->time->setDateTime(data.switchCommand.time);
    ui->heading->setText(QString::number(data.getHeadPosition()));
    ui->gain_2->setText(QString::number(data.switchCommand.startGain));
    ui->range_2->setText(QString::number(data.getRange()));

    // TODO: if any of the parameters have changed; reset the scene

    float newHeading = data.getHeadPosition();
    int bla = oldHeading;
    bool isnumber = (bla != 0);

    if(ui->checkBox->isChecked() && isnumber && (fabs(newHeading - oldHeading)<20 || fabs(newHeading - oldHeading)>340))
    {

        QPolygonF polygon;

        QPointF endPoint1 = QTransform().rotate(oldHeading).map(QPointF(range,0));
        QPointF endPoint2 = QTransform().rotate(newHeading).map(QPointF(range,0));

        polygon << QPointF(0,0) << endPoint1 << endPoint2;
        QGraphicsPolygonItem *it = scene.addPolygon(polygon,QPen(Qt::NoPen));
        queue.append(it);

        scanLine->setRotation(newHeading-90);

        QLinearGradient g(QPointF(0, 0), endPoint2);
        for (int i = 0; i < n; i++) {
            char b = data.getEchoData()[i];
            g.setColorAt(1.0*i/n,QColor(2*b,2*b,2*b));
        }
        it->setBrush(QBrush(g));

        // this should ensure that a full circle is conserved even at highest resolution
        // it may result in overlay, but this doesn't matter since newer items will always
        // be drawn on top of older ones.
        // 480: don't ask, it just works :)
        while (queue.size()>480/(oldStepSize*3+3)) {
            delete queue.takeFirst();
        }

    }

    oldHeading = newHeading;
}

void ScanningSonarForm::on_save_clicked()
{
    sonar->setSettingsValue("serialPort", ui->serialPort->text());
    sonar->setSettingsValue("frequency", ui->frequency->currentIndex());
    sonar->setSettingsValue("gain", ui->gain->value());
    sonar->setSettingsValue("pulseLength", ui->pulseLength->value());
    sonar->setSettingsValue("range", ui->range->value());
    sonar->setSettingsValue("sectorWidth", ui->sectorWidth->value());
    sonar->setSettingsValue("stepSize", ui->stepSize->currentIndex()+1);
    sonar->setSettingsValue("switchDelay", ui->switchDelay->text().toInt());
    sonar->setSettingsValue("trainAngle", ui->trainAngle->text().toInt());
    sonar->setSettingsValue("dataPoints", ui->dataPoints->text().toInt());

    QTimer::singleShot(0,sonar,SLOT(reset()));

    // the scan resolution may have changed, clear the graphics scene
    foreach(QGraphicsItem* g, queue) {
        delete queue.takeFirst();
    }
}

void ScanningSonarForm::on_fileCfgApply_clicked()
{
    sonar->setSettingsValue("readFromFile", ui->sourceFile->isChecked());
    sonar->setSettingsValue("filename", ui->fileName->text());
    sonar->setSettingsValue("fileReaderDelay", ui->fileReaderDelay->value());
    sonar->setSettingsValue("enableRecording", ui->enableRecording->isChecked());
    sonar->setSettingsValue("formatCSV", ui->formatCSV->isChecked());
    sonar->setSettingsValue("startTime", ui->startTime->dateTime());

    // richtiges reset?
    QTimer::singleShot(0,sonar,SLOT(reset()));

}

void ScanningSonarForm::on_fileReaderDelay_valueChanged(int )
{
    sonar->setSettingsValue("fileReaderDelay", ui->fileReaderDelay->value());
}

void ScanningSonarForm::on_selFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
         "Open Sonar Recording", ui->fileName->text(), "Recording (*.852)");

    if (fileName.length()>0)
        ui->fileName->setText(fileName);
}
<|endoftext|>


<commit_before>#include "AliZMQManager.h"
#include "AliStorageTypes.h"
#include <iostream>
#include <sstream>
#include <ostream>
#include <AliTrackPointArray.h>
#include <TXMLEngine.h>

using namespace std;

TXMLEngine* xml = new TXMLEngine;

stringstream& getXml(AliESDEvent *event)
{
	// Create main node of document tree
	XMLNodePointer_t mainnode = xml->NewChild(0, 0, "main");

	cout<<"tracks:"<<event->GetNumberOfTracks()<<endl;
	XMLNodePointer_t tracks[event->GetNumberOfTracks()];

	for(int i=0;i<event->GetNumberOfTracks();i++)
	{
		AliESDtrack *track = event->GetTrack(i);
		tracks[i] = xml->NewChild(mainnode, 0, Form("track%d",i));
		const AliTrackPointArray *array = track->GetTrackPointArray();
		if(array)
		{
			const float *x = array->GetX();
			const float *y = array->GetY();
			const float *z = array->GetZ();
			int n = array->GetNPoints();

			for(int j=0;j<n;j++)
			{
				cout<<"3"<<endl;
				xml->NewChild(tracks[i], 0,Form("point%d",j),Form("%f\t%f\t%f\n",x[j],y[j],z[j]));
			}
		}
		else cout<<"no array"<<endl;
	}

	stringstream streamXml;
	xml->SavePrimitive(streamXml);
	delete xml;
	return streamXml;
}

int main()
{
	AliZMQManager *manager = AliZMQManager::GetInstance();
	AliESDEvent *event;

	while(1)
	{
        manager->Get(event,EVENTS_SERVER_SUB);
		cout<<"sending xml"<<endl;
		manager->Send(getXml(event),XML_PUB);
		cout<<"xml sent"<<endl;
	}
	return 0;
}

<commit_msg>Fixed compilation (Markus Fasel)<commit_after>#include "AliZMQManager.h"
#include "AliStorageTypes.h"
#include <iostream>
#include <sstream>
#include <ostream>
#include <AliTrackPointArray.h>
#include <TXMLEngine.h>

using namespace std;

TXMLEngine* xml = new TXMLEngine;

stringstream& getXml(AliESDEvent *event)
{
	// Create main node of document tree
	XMLNodePointer_t mainnode = xml->NewChild(0, 0, "main");

	cout<<"tracks:"<<event->GetNumberOfTracks()<<endl;
	XMLNodePointer_t tracks[event->GetNumberOfTracks()];

	for(int i=0;i<event->GetNumberOfTracks();i++)
	{
		AliESDtrack *track = event->GetTrack(i);
		tracks[i] = xml->NewChild(mainnode, 0, Form("track%d",i));
		const AliTrackPointArray *array = track->GetTrackPointArray();
		if(array)
		{
			const float *x = array->GetX();
			const float *y = array->GetY();
			const float *z = array->GetZ();
			int n = array->GetNPoints();

			for(int j=0;j<n;j++)
			{
				cout<<"3"<<endl;
				xml->NewChild(tracks[i], 0,Form("point%d",j),Form("%f\t%f\t%f\n",x[j],y[j],z[j]));
			}
		}
		else cout<<"no array"<<endl;
	}

	stringstream streamXml;
	xml->SavePrimitive(streamXml);
	delete xml;
	return streamXml;
}

int main()
{
	AliZMQManager *manager = AliZMQManager::GetInstance();
	AliESDEvent *event;

	while(1)
	{
        manager->Get(event,EVENTS_SERVER_SUB);
		cout<<"sending xml"<<endl;
		manager->SendAsXml(event,XML_PUB);
		cout<<"xml sent"<<endl;
	}
	return 0;
}

<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkUSImageVideoSource.h"
#include "mitkTestingMacros.h"

class mitkUSImageVideoSourceTestClass
{
public:

  static void TestInstantiation()
  {
    // let's create an object of our class
    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();
    MITK_TEST_CONDITION_REQUIRED(usSource.IsNotNull(), "USImageVideoSource should not be null after instantiation");
  }

  static void TestOpenVideoFile(std::string videoFilePath)
  {
    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();

    usSource->SetVideoFileInput(videoFilePath);
    MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Video File");
    mitk::Image::Pointer frame;
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "First frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Second frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Third frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fourth frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fifth frame should not be null.");
  }
  /** This Test will fail if no device is attached. Since it basically covers the same non-OpenCV Functionality as TestOpenVideoFile, it is ommited
  static void TestOpenDevice()
  {
  mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();
  usSource->SetCameraInput(-1);
  MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Camera device");
  }
  */
};

/**
* This function is testing methods of the class USImageVideoSource.
*/
int mitkUSImageVideoSourceTest(int, char* argv[])
{
  MITK_TEST_BEGIN("mitkUSImageVideoSourceTest");

  mitkUSImageVideoSourceTestClass::TestInstantiation();

#ifdef WIN32 // Video file compression is currently only supported under windows.
  mitkUSImageVideoSourceTestClass::TestOpenVideoFile(argv[1]);
#else
  argv;
#endif

  // This test is commented out since no videodevcie ist steadily connected to the dart clients.
  // Functionality should sufficiently be tested through TestOpenVideoFile anyway
  //mitkUSImageVideoSourceTestClass::TestOpenDevice();

  MITK_TEST_END();
}
<commit_msg>removed no effect warning<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkUSImageVideoSource.h"
#include "mitkTestingMacros.h"

class mitkUSImageVideoSourceTestClass
{
public:

  static void TestInstantiation()
  {
    // let's create an object of our class
    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();
    MITK_TEST_CONDITION_REQUIRED(usSource.IsNotNull(), "USImageVideoSource should not be null after instantiation");
  }

  static void TestOpenVideoFile(std::string videoFilePath)
  {
    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();

    usSource->SetVideoFileInput(videoFilePath);
    MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Video File");
    mitk::Image::Pointer frame;
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "First frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Second frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Third frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fourth frame should not be null.");
    frame = usSource->GetNextImage();
    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), "Fifth frame should not be null.");
  }
  /** This Test will fail if no device is attached. Since it basically covers the same non-OpenCV Functionality as TestOpenVideoFile, it is ommited
  static void TestOpenDevice()
  {
  mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();
  usSource->SetCameraInput(-1);
  MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), "USImageVideoSource should have isVideoReady flag set after opening a Camera device");
  }
  */
};

/**
* This function is testing methods of the class USImageVideoSource.
*/
int mitkUSImageVideoSourceTest(int, char* argv[])
{
  MITK_TEST_BEGIN("mitkUSImageVideoSourceTest");

  mitkUSImageVideoSourceTestClass::TestInstantiation();

#ifdef WIN32 // Video file compression is currently only supported under windows.
  mitkUSImageVideoSourceTestClass::TestOpenVideoFile(argv[1]);
#endif

  // This test is commented out since no videodevcie ist steadily connected to the dart clients.
  // Functionality should sufficiently be tested through TestOpenVideoFile anyway
  //mitkUSImageVideoSourceTestClass::TestOpenDevice();

  MITK_TEST_END();
}
<|endoftext|>