<commit_before>#include <cstdio>
#include <cstdlib>
#include <string.h>
#include "xcint.hpp"

#ifndef FORTRAN_INT
typedef int fortran_int_t;
#else
typedef FORTRAN_INT fortran_int_t;
#endif

functional_data xcint_funs[XC_NR_FUNCTIONALS];
parameter_data xcint_params[XC_NR_PARAMETERS_AND_FUNCTIONALS];

int xcint_lookup_functional(const char *name)
{
  for (int i=0;i<XC_NR_FUNCTIONALS;i++)
    if (strcasecmp(name,xcint_funs[i].name) == 0)
      return i;
  return -1;
}

int xcint_lookup_parameter(const char *name)
{
  for (int i=XC_NR_FUNCTIONALS;i<XC_NR_PARAMETERS_AND_FUNCTIONALS;i++)
    if (strcasecmp(name,xcint_params[i].name) == 0)
      return i;
  return -1;
}

int xcint_lookup_alias(const char *name)
{
  for (int i=0;i<XC_MAX_ALIASES and xcint_aliases[i].name;i++)
    if (strcasecmp(name,xcint_aliases[i].name) == 0)
      return i;
  return -1;
}

template<int FUN>
void xcint_functional_setup_helper()
{
  if (!(fundat_db<FUN>::symbol[0] == 'X' and fundat_db<FUN>::symbol[1] == 'C' and fundat_db<FUN>::symbol[2] == '_'))
    xcint_die("Functional symbol does not start with XC_",FUN);
  fundat_db<FUN>::d.name = fundat_db<FUN>::symbol + 3;
  fundat_db<FUN>::d.id = (enum xc_functional_id)FUN;
  xcint_funs[FUN] = fundat_db<FUN>::d;
  xcint_functional_setup_helper<FUN+1>();
}

template<> void xcint_functional_setup_helper<XC_NR_FUNCTIONALS>() {  }

template<int P>
void xcint_parameter_setup_helper()
{
  if (!(pardat_db<P>::symbol[0] == 'X' and pardat_db<P>::symbol[1] == 'C' and pardat_db<P>::symbol[2] == '_'))
    xcint_die("Symbol does not start with XC_",P);
  pardat_db<P>::d.name = pardat_db<P>::symbol + 3;
  xcint_params[P] = pardat_db<P>::d;
  xcint_parameter_setup_helper<P+1>();
}

template<>
void xcint_parameter_setup_helper<XC_NR_PARAMETERS_AND_FUNCTIONALS>() {}

vars_data xcint_vars[XC_NR_VARS] =
  {
    {"XC_A", 1, XC_DENSITY},
    {"XC_N", 1, XC_DENSITY},
    {"XC_A_B", 2, XC_DENSITY},
    {"XC_N_S", 2, XC_DENSITY},
    {"XC_A_GAA", 2, XC_DENSITY | XC_GRADIENT},
    {"XC_N_GNN", 2, XC_DENSITY | XC_GRADIENT},
    {"XC_A_B_GAA_GAB_GBB", 5, XC_DENSITY | XC_GRADIENT},
    {"XC_N_S_GNN_GNS_GSS", 5, XC_DENSITY | XC_GRADIENT},
    {"XC_A_GAA_LAPA", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_GAA_TAUA", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_GNN_LAPN", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_GNN_TAUN", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_B_GAA_GAB_GBB_LAPA_LAPB",7, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_B_GAA_GAB_GBB_TAUA_TAUB",7, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_N_S_GNN_GNS_GSS_LAPN_LAPS",7, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_S_GNN_GNS_GSS_TAUN_TAUS",7, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_A_AX_AY_AZ",4, XC_DENSITY | XC_GRADIENT},
    {"XC_A_B_AX_AY_AZ_BX_BY_BZ", 8, XC_DENSITY | XC_GRADIENT},
    {"XC_N_NX_NY_NZ",4, XC_DENSITY | XC_GRADIENT},
    {"XC_N_S_NX_NY_NZ_SX_SY_SZ",8, XC_DENSITY | XC_GRADIENT},
    {"XC_A_2ND_TAYLOR", 10, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_B_2ND_TAYLOR", 20, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_2ND_TAYLOR", 10, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_S_2ND_TAYLOR", 20, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
  };

void xcint_assure_setup()
{
  static bool is_setup = false;
  if (!is_setup)
    {
      xcint_functional_setup_helper<0>();
      xcint_parameter_setup_helper<XC_NR_FUNCTIONALS>();
      is_setup = true;
    }
}

void xcint_die(const char *message, int code)
{
  fprintf(stderr,"XCFun fatal error %i: ",code);
  fprintf(stderr,"%s",message);
  fprintf(stderr,"\n");
  exit(-1);
}
<commit_msg>Fix some variable sets that contain tau and not laplacian.<commit_after>#include <cstdio>
#include <cstdlib>
#include <string.h>
#include "xcint.hpp"

#ifndef FORTRAN_INT
typedef int fortran_int_t;
#else
typedef FORTRAN_INT fortran_int_t;
#endif

functional_data xcint_funs[XC_NR_FUNCTIONALS];
parameter_data xcint_params[XC_NR_PARAMETERS_AND_FUNCTIONALS];

int xcint_lookup_functional(const char *name)
{
  for (int i=0;i<XC_NR_FUNCTIONALS;i++)
    if (strcasecmp(name,xcint_funs[i].name) == 0)
      return i;
  return -1;
}

int xcint_lookup_parameter(const char *name)
{
  for (int i=XC_NR_FUNCTIONALS;i<XC_NR_PARAMETERS_AND_FUNCTIONALS;i++)
    if (strcasecmp(name,xcint_params[i].name) == 0)
      return i;
  return -1;
}

int xcint_lookup_alias(const char *name)
{
  for (int i=0;i<XC_MAX_ALIASES and xcint_aliases[i].name;i++)
    if (strcasecmp(name,xcint_aliases[i].name) == 0)
      return i;
  return -1;
}

template<int FUN>
void xcint_functional_setup_helper()
{
  if (!(fundat_db<FUN>::symbol[0] == 'X' and fundat_db<FUN>::symbol[1] == 'C' and fundat_db<FUN>::symbol[2] == '_'))
    xcint_die("Functional symbol does not start with XC_",FUN);
  fundat_db<FUN>::d.name = fundat_db<FUN>::symbol + 3;
  fundat_db<FUN>::d.id = (enum xc_functional_id)FUN;
  xcint_funs[FUN] = fundat_db<FUN>::d;
  xcint_functional_setup_helper<FUN+1>();
}

template<> void xcint_functional_setup_helper<XC_NR_FUNCTIONALS>() {  }

template<int P>
void xcint_parameter_setup_helper()
{
  if (!(pardat_db<P>::symbol[0] == 'X' and pardat_db<P>::symbol[1] == 'C' and pardat_db<P>::symbol[2] == '_'))
    xcint_die("Symbol does not start with XC_",P);
  pardat_db<P>::d.name = pardat_db<P>::symbol + 3;
  xcint_params[P] = pardat_db<P>::d;
  xcint_parameter_setup_helper<P+1>();
}

template<>
void xcint_parameter_setup_helper<XC_NR_PARAMETERS_AND_FUNCTIONALS>() {}

vars_data xcint_vars[XC_NR_VARS] =
  {
    {"XC_A", 1, XC_DENSITY},
    {"XC_N", 1, XC_DENSITY},
    {"XC_A_B", 2, XC_DENSITY},
    {"XC_N_S", 2, XC_DENSITY},
    {"XC_A_GAA", 2, XC_DENSITY | XC_GRADIENT},
    {"XC_N_GNN", 2, XC_DENSITY | XC_GRADIENT},
    {"XC_A_B_GAA_GAB_GBB", 5, XC_DENSITY | XC_GRADIENT},
    {"XC_N_S_GNN_GNS_GSS", 5, XC_DENSITY | XC_GRADIENT},
    {"XC_A_GAA_LAPA", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_GAA_TAUA", 3, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_N_GNN_LAPN", 3, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_GNN_TAUN", 3, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_A_B_GAA_GAB_GBB_LAPA_LAPB",7, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_B_GAA_GAB_GBB_TAUA_TAUB",7, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_N_S_GNN_GNS_GSS_LAPN_LAPS",7, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_S_GNN_GNS_GSS_TAUN_TAUS",7, XC_DENSITY | XC_GRADIENT | XC_KINETIC},
    {"XC_A_AX_AY_AZ",4, XC_DENSITY | XC_GRADIENT},
    {"XC_A_B_AX_AY_AZ_BX_BY_BZ", 8, XC_DENSITY | XC_GRADIENT},
    {"XC_N_NX_NY_NZ",4, XC_DENSITY | XC_GRADIENT},
    {"XC_N_S_NX_NY_NZ_SX_SY_SZ",8, XC_DENSITY | XC_GRADIENT},
    {"XC_A_2ND_TAYLOR", 10, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_A_B_2ND_TAYLOR", 20, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_2ND_TAYLOR", 10, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
    {"XC_N_S_2ND_TAYLOR", 20, XC_DENSITY | XC_GRADIENT | XC_LAPLACIAN},
  };

void xcint_assure_setup()
{
  static bool is_setup = false;
  if (!is_setup)
    {
      xcint_functional_setup_helper<0>();
      xcint_parameter_setup_helper<XC_NR_FUNCTIONALS>();
      is_setup = true;
    }
}

void xcint_die(const char *message, int code)
{
  fprintf(stderr,"XCFun fatal error %i: ",code);
  fprintf(stderr,"%s",message);
  fprintf(stderr,"\n");
  exit(-1);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/video_source.h"
#include "test/util.h"

// Enable(1) or Disable(0) writing of the compressed bitstream.
#define WRITE_COMPRESSED_STREAM 0

namespace {

#if WRITE_COMPRESSED_STREAM
static void mem_put_le16(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
}

static void mem_put_le32(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
  mem[2] = val >> 16;
  mem[3] = val >> 24;
}

static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg,
                                  int frame_cnt, FILE *const outfile) {
  char header[32];

  header[0] = 'D';
  header[1] = 'K';
  header[2] = 'I';
  header[3] = 'F';
  mem_put_le16(header + 4,  0);                   /* version */
  mem_put_le16(header + 6,  32);                  /* headersize */
  mem_put_le32(header + 8,  0x30395056);          /* fourcc (vp9) */
  mem_put_le16(header + 12, cfg->g_w);            /* width */
  mem_put_le16(header + 14, cfg->g_h);            /* height */
  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
  mem_put_le32(header + 24, frame_cnt);           /* length */
  mem_put_le32(header + 28, 0);                   /* unused */

  (void)fwrite(header, 1, 32, outfile);
}

static void write_ivf_frame_size(FILE *const outfile, const size_t size) {
  char header[4];
  mem_put_le32(header, static_cast<unsigned int>(size));
  (void)fwrite(header, 1, 4, outfile);
}

static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt,
                                   FILE *const outfile) {
  char header[12];
  vpx_codec_pts_t pts;

  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
    return;

  pts = pkt->data.frame.pts;
  mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz));
  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
  mem_put_le32(header + 8, pts >> 32);

  (void)fwrite(header, 1, 12, outfile);
}
#endif  // WRITE_COMPRESSED_STREAM

const unsigned int kInitialWidth = 320;
const unsigned int kInitialHeight = 240;

unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) {
  if (frame < 10)
    return val;
  if (frame < 20)
    return val / 2;
  if (frame < 30)
    return val * 2 / 3;
  if (frame < 40)
    return val / 4;
  if (frame < 50)
    return val * 7 / 8;
  return val;
}

class ResizingVideoSource : public ::libvpx_test::DummyVideoSource {
 public:
  ResizingVideoSource() {
    SetSize(kInitialWidth, kInitialHeight);
    limit_ = 60;
  }

  virtual ~ResizingVideoSource() {}

 protected:
  virtual void Next() {
    ++frame_;
    SetSize(ScaleForFrameNumber(frame_, kInitialWidth),
            ScaleForFrameNumber(frame_, kInitialHeight));
    FillFrame();
  }
};

class ResizeTest : public ::libvpx_test::EncoderTest,
  public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
 protected:
  ResizeTest() : EncoderTest(GET_PARAM(0)) {}

  virtual ~ResizeTest() {}

  struct FrameInfo {
    FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h)
        : pts(_pts), w(_w), h(_h) {}

    vpx_codec_pts_t pts;
    unsigned int w;
    unsigned int h;
  };

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
  }

  virtual void DecompressedFrameHook(const vpx_image_t &img,
                                     vpx_codec_pts_t pts) {
    frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h));
  }

  std::vector< FrameInfo > frame_info_list_;
};

TEST_P(ResizeTest, TestExternalResizeWorks) {
  ResizingVideoSource video;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::const_iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const unsigned int frame = static_cast<unsigned>(info->pts);
    const unsigned int expected_w = ScaleForFrameNumber(frame, kInitialWidth);
    const unsigned int expected_h = ScaleForFrameNumber(frame, kInitialHeight);

    EXPECT_EQ(expected_w, info->w)
        << "Frame " << frame << "had unexpected width";
    EXPECT_EQ(expected_h, info->h)
        << "Frame " << frame << "had unexpected height";
  }
}

const unsigned int kStepDownFrame = 3;
const unsigned int kStepUpFrame = 6;

class ResizeInternalTest : public ResizeTest {
 protected:
#if WRITE_COMPRESSED_STREAM
  ResizeInternalTest()
      : ResizeTest(),
        frame0_psnr_(0.0),
        outfile_(NULL),
        out_frames_(0) {}
#else
  ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {}
#endif

  virtual ~ResizeInternalTest() {}

  virtual void BeginPassHook(unsigned int /*pass*/) {
#if WRITE_COMPRESSED_STREAM
    outfile_ = fopen("vp90-2-05-resize.ivf", "wb");
#endif
  }

  virtual void EndPassHook() {
#if WRITE_COMPRESSED_STREAM
    if (outfile_) {
      if (!fseek(outfile_, 0, SEEK_SET))
        write_ivf_file_header(&cfg_, out_frames_, outfile_);
      fclose(outfile_);
      outfile_ = NULL;
    }
#endif
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == kStepDownFrame) {
      struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
    if (video->frame() == kStepUpFrame) {
      struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
  }

  virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
    if (!frame0_psnr_)
      frame0_psnr_ = pkt->data.psnr.psnr[0];
    EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 2.0);
  }

  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
#if WRITE_COMPRESSED_STREAM
    ++out_frames_;

    // Write initial file header if first frame.
    if (pkt->data.frame.pts == 0)
      write_ivf_file_header(&cfg_, 0, outfile_);

    // Write frame header and data.
    write_ivf_frame_header(pkt, outfile_);
    (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_);
#endif
  }

  double frame0_psnr_;
#if WRITE_COMPRESSED_STREAM
  FILE *outfile_;
  unsigned int out_frames_;
#endif
};

TEST_P(ResizeInternalTest, TestInternalResizeWorks) {
  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                       30, 1, 0, 10);
  init_flags_ = VPX_CODEC_USE_PSNR;

  // q picked such that initial keyframe on this clip is ~30dB PSNR
  cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48;

  // If the number of frames being encoded is smaller than g_lag_in_frames
  // the encoded frame is unavailable using the current API. Comparing
  // frames to detect mismatch would then not be possible. Set
  // g_lag_in_frames = 0 to get around this.
  cfg_.g_lag_in_frames = 0;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::const_iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    if (pts >= kStepDownFrame && pts < kStepUpFrame) {
      ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width";
      ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height";
    } else {
      EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width";
      EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height";
    }
  }
}

VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest,
                          ::testing::Values(::libvpx_test::kOnePassBest));
}  // namespace
<commit_msg>resize_test.cc: remove unused param warnings<commit_after>/*
 *  Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/video_source.h"
#include "test/util.h"

// Enable(1) or Disable(0) writing of the compressed bitstream.
#define WRITE_COMPRESSED_STREAM 0

namespace {

#if WRITE_COMPRESSED_STREAM
static void mem_put_le16(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
}

static void mem_put_le32(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
  mem[2] = val >> 16;
  mem[3] = val >> 24;
}

static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg,
                                  int frame_cnt, FILE *const outfile) {
  char header[32];

  header[0] = 'D';
  header[1] = 'K';
  header[2] = 'I';
  header[3] = 'F';
  mem_put_le16(header + 4,  0);                   /* version */
  mem_put_le16(header + 6,  32);                  /* headersize */
  mem_put_le32(header + 8,  0x30395056);          /* fourcc (vp9) */
  mem_put_le16(header + 12, cfg->g_w);            /* width */
  mem_put_le16(header + 14, cfg->g_h);            /* height */
  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
  mem_put_le32(header + 24, frame_cnt);           /* length */
  mem_put_le32(header + 28, 0);                   /* unused */

  (void)fwrite(header, 1, 32, outfile);
}

static void write_ivf_frame_size(FILE *const outfile, const size_t size) {
  char header[4];
  mem_put_le32(header, static_cast<unsigned int>(size));
  (void)fwrite(header, 1, 4, outfile);
}

static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt,
                                   FILE *const outfile) {
  char header[12];
  vpx_codec_pts_t pts;

  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
    return;

  pts = pkt->data.frame.pts;
  mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz));
  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
  mem_put_le32(header + 8, pts >> 32);

  (void)fwrite(header, 1, 12, outfile);
}
#endif  // WRITE_COMPRESSED_STREAM

const unsigned int kInitialWidth = 320;
const unsigned int kInitialHeight = 240;

unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) {
  if (frame < 10)
    return val;
  if (frame < 20)
    return val / 2;
  if (frame < 30)
    return val * 2 / 3;
  if (frame < 40)
    return val / 4;
  if (frame < 50)
    return val * 7 / 8;
  return val;
}

class ResizingVideoSource : public ::libvpx_test::DummyVideoSource {
 public:
  ResizingVideoSource() {
    SetSize(kInitialWidth, kInitialHeight);
    limit_ = 60;
  }

  virtual ~ResizingVideoSource() {}

 protected:
  virtual void Next() {
    ++frame_;
    SetSize(ScaleForFrameNumber(frame_, kInitialWidth),
            ScaleForFrameNumber(frame_, kInitialHeight));
    FillFrame();
  }
};

class ResizeTest : public ::libvpx_test::EncoderTest,
  public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
 protected:
  ResizeTest() : EncoderTest(GET_PARAM(0)) {}

  virtual ~ResizeTest() {}

  struct FrameInfo {
    FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h)
        : pts(_pts), w(_w), h(_h) {}

    vpx_codec_pts_t pts;
    unsigned int w;
    unsigned int h;
  };

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
  }

  virtual void DecompressedFrameHook(const vpx_image_t &img,
                                     vpx_codec_pts_t pts) {
    frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h));
  }

  std::vector< FrameInfo > frame_info_list_;
};

TEST_P(ResizeTest, TestExternalResizeWorks) {
  ResizingVideoSource video;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::const_iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const unsigned int frame = static_cast<unsigned>(info->pts);
    const unsigned int expected_w = ScaleForFrameNumber(frame, kInitialWidth);
    const unsigned int expected_h = ScaleForFrameNumber(frame, kInitialHeight);

    EXPECT_EQ(expected_w, info->w)
        << "Frame " << frame << "had unexpected width";
    EXPECT_EQ(expected_h, info->h)
        << "Frame " << frame << "had unexpected height";
  }
}

const unsigned int kStepDownFrame = 3;
const unsigned int kStepUpFrame = 6;

class ResizeInternalTest : public ResizeTest {
 protected:
#if WRITE_COMPRESSED_STREAM
  ResizeInternalTest()
      : ResizeTest(),
        frame0_psnr_(0.0),
        outfile_(NULL),
        out_frames_(0) {}
#else
  ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {}
#endif

  virtual ~ResizeInternalTest() {}

  virtual void BeginPassHook(unsigned int /*pass*/) {
#if WRITE_COMPRESSED_STREAM
    outfile_ = fopen("vp90-2-05-resize.ivf", "wb");
#endif
  }

  virtual void EndPassHook() {
#if WRITE_COMPRESSED_STREAM
    if (outfile_) {
      if (!fseek(outfile_, 0, SEEK_SET))
        write_ivf_file_header(&cfg_, out_frames_, outfile_);
      fclose(outfile_);
      outfile_ = NULL;
    }
#endif
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == kStepDownFrame) {
      struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
    if (video->frame() == kStepUpFrame) {
      struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
  }

  virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
    if (!frame0_psnr_)
      frame0_psnr_ = pkt->data.psnr.psnr[0];
    EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 2.0);
  }

#if WRITE_COMPRESSED_STREAM
  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
    ++out_frames_;

    // Write initial file header if first frame.
    if (pkt->data.frame.pts == 0)
      write_ivf_file_header(&cfg_, 0, outfile_);

    // Write frame header and data.
    write_ivf_frame_header(pkt, outfile_);
    (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_);
  }
#endif

  double frame0_psnr_;
#if WRITE_COMPRESSED_STREAM
  FILE *outfile_;
  unsigned int out_frames_;
#endif
};

TEST_P(ResizeInternalTest, TestInternalResizeWorks) {
  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                       30, 1, 0, 10);
  init_flags_ = VPX_CODEC_USE_PSNR;

  // q picked such that initial keyframe on this clip is ~30dB PSNR
  cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48;

  // If the number of frames being encoded is smaller than g_lag_in_frames
  // the encoded frame is unavailable using the current API. Comparing
  // frames to detect mismatch would then not be possible. Set
  // g_lag_in_frames = 0 to get around this.
  cfg_.g_lag_in_frames = 0;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::const_iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    if (pts >= kStepDownFrame && pts < kStepUpFrame) {
      ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width";
      ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height";
    } else {
      EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width";
      EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height";
    }
  }
}

VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest,
                          ::testing::Values(::libvpx_test::kOnePassBest));
}  // namespace
<|endoftext|>


<commit_before><commit_msg>clean up<commit_after><|endoftext|>


<commit_before>#include "unit-test.h"

<commit_msg>removed include since this is not needed (and doesn't compile without application.h)<commit_after>
/*
 * Nothing needed here. The unit test library is all in the header.
 */

<|endoftext|>


<commit_before><commit_msg>ShadowMap: Fix potentially wrong EntityManager.<commit_after><|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "QmitkNavigationToolCreationWidget.h"

//mitk headers
#include "mitkTrackingTypes.h"
#include <mitkSTLFileReader.h>
#include <mitkSurface.h>

//qt headers
#include <qfiledialog.h>
#include <qmessagebox.h>

//poco headers
#include <Poco/Path.h>

// vtk
#include <vtkSphereSource.h>

const std::string QmitkNavigationToolCreationWidget::VIEW_ID = "org.mitk.views.navigationtoolcreationwizardwidget";

QmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)
  : QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
  CreateConnections();
}

QmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()
{
}

void QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)
  {
    if (!m_Controls)
    {
    // create GUI widgets
    m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;
    m_Controls->setupUi(parent);
    }
  }

void QmitkNavigationToolCreationWidget::CreateConnections()
  {
    if ( m_Controls )
    {
      connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );
      connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );
      connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );
      connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );
    }
  }

void QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier)
  {
  m_DataStorage = dataStorage;
  m_Controls->m_IdentifierEdit->setText(QString(supposedIdentifier.c_str()));

  //initialize UI components
  m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);
  m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);
  m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New("Surface"));

  //set default data
  m_Controls->m_ToolNameEdit->setText("NewTool");
  m_Controls->m_CalibrationFileName->setText("<not given>");
  m_Controls->m_SerialNumberEdit->setText("<not given>");
  m_Controls->m_Surface_Use_Sphere->setChecked(true);
  m_Controls->m_ToolTypeChooser->setCurrentIndex(0);

  }

void QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)
  {
  switch(type)
      {
      case mitk::NDIAurora:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;
      case mitk::NDIPolaris:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;
      case mitk::ClaronMicron:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;
      default:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);
      }
  m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);
  }

mitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()
{
  return m_CreatedTool;
}

//##################################################################################
//############################## slots                  ############################
//##################################################################################

void QmitkNavigationToolCreationWidget::OnFinished()
  {
    //here we create a new tool
    m_CreatedTool = mitk::NavigationTool::New();

    //create DataNode...
    mitk::DataNode::Pointer newNode = mitk::DataNode::New();
    newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());
    if(m_Controls->m_Surface_Use_Sphere->isChecked())
      {
      //create small sphere and use it as surface
      mitk::Surface::Pointer mySphere = mitk::Surface::New();
      vtkSphereSource *vtkData = vtkSphereSource::New();
      vtkData->SetRadius(3.0f);
      vtkData->SetCenter(0.0, 0.0, 0.0);
      vtkData->Update();
      mySphere->SetVtkPolyData(vtkData->GetOutput());
      vtkData->Delete();
      newNode->SetData(mySphere);
      }
    else {newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());}

    m_CreatedTool->SetDataNode(newNode);

    //fill NavigationTool object
    m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());
    m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());
    m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());

    //Tracking Device
    if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Aurora") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);
    else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Polaris") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);
    else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="Claron Technology Micron Tracker") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);
    else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);

    //ToolType
    if (m_Controls->m_ToolTypeChooser->currentText()=="Instrument") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);
    else if (m_Controls->m_ToolTypeChooser->currentText()=="Fiducial") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);
    else if (m_Controls->m_ToolTypeChooser->currentText()=="Skinmarker") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);
    else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);

    emit NavigationToolFinished();
  }

void QmitkNavigationToolCreationWidget::OnCancel()
  {
    m_CreatedTool = NULL;
    emit Canceled();
  }

void QmitkNavigationToolCreationWidget::OnLoadSurface()
  {
    std::string filename = QFileDialog::getOpenFileName(NULL,tr("Open Surface"), "/", "*.stl").toLatin1().data();
    mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();
    try
      {
      stlReader->SetFileName( filename.c_str() );
      stlReader->Update();
      }
    catch (...)
      {
      }

    if ( stlReader->GetOutput() == NULL );
    else
      {
      mitk::DataNode::Pointer newNode = mitk::DataNode::New();
      newNode->SetName(filename);
      newNode->SetData(stlReader->GetOutput());
      m_DataStorage->Add(newNode);
      }
  }

void QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()
  {
    m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr("Open Calibration File"), "/", "*.*"));
  }

void QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)
  {
    m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));
    m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));
    m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));
    switch(DefaultTool->GetTrackingDeviceType())
      {
      case mitk::NDIAurora:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;
      case mitk::NDIPolaris:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;
      case mitk::ClaronMicron:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;
      default:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);
      }
    m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));
    m_Controls->m_Surface_Use_Other->setChecked(true);
    switch(DefaultTool->GetType())
      {
      case mitk::NavigationTool::Instrument:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;
      case mitk::NavigationTool::Fiducial:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;
      case mitk::NavigationTool::Skinmarker:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;
      case mitk::NavigationTool::Unknown:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;
      }

    m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());

  }

//##################################################################################
//############################## internal help methods #############################
//##################################################################################
void QmitkNavigationToolCreationWidget::MessageBox(std::string s)
  {
  QMessageBox msgBox;
  msgBox.setText(s.c_str());
  msgBox.exec();
}<commit_msg>changed radius of default spheres<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "QmitkNavigationToolCreationWidget.h"

//mitk headers
#include "mitkTrackingTypes.h"
#include <mitkSTLFileReader.h>
#include <mitkSurface.h>

//qt headers
#include <qfiledialog.h>
#include <qmessagebox.h>

//poco headers
#include <Poco/Path.h>

// vtk
#include <vtkSphereSource.h>

const std::string QmitkNavigationToolCreationWidget::VIEW_ID = "org.mitk.views.navigationtoolcreationwizardwidget";

QmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)
  : QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
  CreateConnections();
}

QmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()
{
}

void QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)
  {
    if (!m_Controls)
    {
    // create GUI widgets
    m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;
    m_Controls->setupUi(parent);
    }
  }

void QmitkNavigationToolCreationWidget::CreateConnections()
  {
    if ( m_Controls )
    {
      connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );
      connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );
      connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );
      connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );
    }
  }

void QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier)
  {
  m_DataStorage = dataStorage;
  m_Controls->m_IdentifierEdit->setText(QString(supposedIdentifier.c_str()));

  //initialize UI components
  m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);
  m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);
  m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New("Surface"));

  //set default data
  m_Controls->m_ToolNameEdit->setText("NewTool");
  m_Controls->m_CalibrationFileName->setText("<not given>");
  m_Controls->m_SerialNumberEdit->setText("<not given>");
  m_Controls->m_Surface_Use_Sphere->setChecked(true);
  m_Controls->m_ToolTypeChooser->setCurrentIndex(0);

  }

void QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)
  {
  switch(type)
      {
      case mitk::NDIAurora:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;
      case mitk::NDIPolaris:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;
      case mitk::ClaronMicron:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;
      default:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);
      }
  m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);
  }

mitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()
{
  return m_CreatedTool;
}

//##################################################################################
//############################## slots                  ############################
//##################################################################################

void QmitkNavigationToolCreationWidget::OnFinished()
  {
    //here we create a new tool
    m_CreatedTool = mitk::NavigationTool::New();

    //create DataNode...
    mitk::DataNode::Pointer newNode = mitk::DataNode::New();
    newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());
    if(m_Controls->m_Surface_Use_Sphere->isChecked())
      {
      //create small sphere and use it as surface
      mitk::Surface::Pointer mySphere = mitk::Surface::New();
      vtkSphereSource *vtkData = vtkSphereSource::New();
      vtkData->SetRadius(6.0f);
      vtkData->SetCenter(0.0, 0.0, 0.0);
      vtkData->Update();
      mySphere->SetVtkPolyData(vtkData->GetOutput());
      vtkData->Delete();
      newNode->SetData(mySphere);
      }
    else {newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());}

    m_CreatedTool->SetDataNode(newNode);

    //fill NavigationTool object
    m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());
    m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());
    m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());

    //Tracking Device
    if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Aurora") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);
    else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="NDI Polaris") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);
    else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()=="Claron Technology Micron Tracker") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);
    else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);

    //ToolType
    if (m_Controls->m_ToolTypeChooser->currentText()=="Instrument") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);
    else if (m_Controls->m_ToolTypeChooser->currentText()=="Fiducial") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);
    else if (m_Controls->m_ToolTypeChooser->currentText()=="Skinmarker") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);
    else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);

    emit NavigationToolFinished();
  }

void QmitkNavigationToolCreationWidget::OnCancel()
  {
    m_CreatedTool = NULL;
    emit Canceled();
  }

void QmitkNavigationToolCreationWidget::OnLoadSurface()
  {
    std::string filename = QFileDialog::getOpenFileName(NULL,tr("Open Surface"), "/", "*.stl").toLatin1().data();
    mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();
    try
      {
      stlReader->SetFileName( filename.c_str() );
      stlReader->Update();
      }
    catch (...)
      {
      }

    if ( stlReader->GetOutput() == NULL );
    else
      {
      mitk::DataNode::Pointer newNode = mitk::DataNode::New();
      newNode->SetName(filename);
      newNode->SetData(stlReader->GetOutput());
      m_DataStorage->Add(newNode);
      }
  }

void QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()
  {
    m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr("Open Calibration File"), "/", "*.*"));
  }

void QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)
  {
    m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));
    m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));
    m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));
    switch(DefaultTool->GetTrackingDeviceType())
      {
      case mitk::NDIAurora:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;
      case mitk::NDIPolaris:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;
      case mitk::ClaronMicron:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;
      default:
              m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);
      }
    m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));
    m_Controls->m_Surface_Use_Other->setChecked(true);
    switch(DefaultTool->GetType())
      {
      case mitk::NavigationTool::Instrument:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;
      case mitk::NavigationTool::Fiducial:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;
      case mitk::NavigationTool::Skinmarker:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;
      case mitk::NavigationTool::Unknown:
        m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;
      }

    m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());

  }

//##################################################################################
//############################## internal help methods #############################
//##################################################################################
void QmitkNavigationToolCreationWidget::MessageBox(std::string s)
  {
  QMessageBox msgBox;
  msgBox.setText(s.c_str());
  msgBox.exec();
}<|endoftext|>


<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
//  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

//      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new User(login_request.req_username, address)});

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
        std::cout << std::endl;
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, &client_addr);
    }
  }
}
<commit_msg>client_add pointer attempt to fix login/logout<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
//  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

//      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new User(login_request.req_username, address)});

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
        std::cout << std::endl;
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in *client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, client_addr);
    }
  }
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Nathan Osman
 *
 * 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 <QJsonDocument>
#include <QJsonObject>
#include <QTest>

#include <nitroshare/application.h>
#include <nitroshare/bundle.h>
#include <nitroshare/handlerregistry.h>
#include <nitroshare/transfer.h>
#include <nitroshare/transportserverregistry.h>

#include "mock/mockapplication.h"
#include "mock/mockdevice.h"
#include "mock/mockhandler.h"
#include "mock/mockitem.h"
#include "mock/mocktransport.h"
#include "mock/mocktransportserver.h"

class TestTransfer : public QObject
{
    Q_OBJECT

private slots:

    void initTestCase();

    void testSending();
    void testReceiving();

private:

    MockApplication mApplication;
    MockHandler mHandler;
    MockTransportServer mTransportServer;
};

void TestTransfer::initTestCase()
{
    mApplication.application()->handlerRegistry()->add(&mHandler);
    mApplication.application()->transportServerRegistry()->add(&mTransportServer);
}

void TestTransfer::testSending()
{
    MockDevice device;
    Bundle bundle;
    bundle.add(new MockItem);
    Transfer *transfer = new Transfer(mApplication.application(), &device, &bundle);

    // The device saves a copy of the transport so that it can be retrieved
    MockTransport *transport = device.transport();

    QCOMPARE(transfer->direction(), Transfer::Send);
    QCOMPARE(transfer->state(), Transfer::Connecting);

    // Have the transport complete the connection
    transport->emitConnected();

    QCOMPARE(transfer->state(), Transfer::InProgress);

    // The first two packets should be JSON data (the transfer & item headers)
    // and the third will be the payload
    QTRY_COMPARE(transport->packets().count(), 3);

    const MockTransport::PacketList &packets = transport->packets();

    // Ensure the transfer header was sent correctly
    QCOMPARE(packets.at(0).first, Packet::Json);
    QJsonObject transferHeader{
        { "name", MockApplication::DeviceName },
        { "size", QString::number(MockItem::Data.size()) },
        { "count", QString::number(1) }
    };
    QCOMPARE(QJsonDocument::fromJson(packets.at(0).second).object(), transferHeader);

    // Ensure the item header was sent correctly
    QCOMPARE(packets.at(1).first, Packet::Json);
    QJsonObject itemHeader{
        { "name", MockItem::Name },
        { "type", MockItem::Type },
        { "size", QString::number(MockItem::Data.size()) }
    };
    QCOMPARE(QJsonDocument::fromJson(packets.at(1).second).object(), itemHeader);

    // Ensure the item was sent correctly
    QCOMPARE(packets.at(2).first, Packet::Binary);
    QCOMPARE(packets.at(2).second, MockItem::Data);

    QCOMPARE(transfer->state(), Transfer::InProgress);

    // Send the success packet
    transport->sendData(Packet::Success);

    QCOMPARE(transfer->state(), Transfer::Succeeded);
    QVERIFY(transport->isClosed());
}

void TestTransfer::testReceiving()
{
    MockTransport transport;
    Transfer *transfer = new Transfer(mApplication.application(), &transport);

    QCOMPARE(transfer->direction(), Transfer::Receive);
    QCOMPARE(transfer->state(), Transfer::InProgress);

    // Send the transfer header to the transport
    QJsonObject transferHeader{
        { "name", MockDevice::Name },
        { "size", QString::number(MockItem::Data.size()) },
        { "count", QString::number(1) }
    };
    transport.sendData(Packet::Json, QJsonDocument(transferHeader).toJson());

    QCOMPARE(transfer->deviceName(), MockDevice::Name);

    // Send the item header to the transport followed by the data for the item
    QJsonObject itemHeader{
        { "name", MockItem::Name },
        { "type", MockItem::Type },
        { "size", QString::number(MockItem::Data.size()) }
    };
    transport.sendData(Packet::Json, QJsonDocument(itemHeader).toJson());
    transport.sendData(Packet::Binary, MockItem::Data);

    QTRY_COMPARE(transfer->state(), Transfer::Succeeded);

    // Ensure a success packet was sent and the transport closed
    QCOMPARE(transport.packets().count(), 1);
    QCOMPARE(transport.packets().at(0).first, Packet::Success);
    QVERIFY(transport.isClosed());
}

QTEST_MAIN(TestTransfer)
#include "TestTransfer.moc"
<commit_msg>Add test for aborting a transfer (#148).<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Nathan Osman
 *
 * 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 <QJsonDocument>
#include <QJsonObject>
#include <QTest>

#include <nitroshare/application.h>
#include <nitroshare/bundle.h>
#include <nitroshare/handlerregistry.h>
#include <nitroshare/transfer.h>
#include <nitroshare/transportserverregistry.h>

#include "mock/mockapplication.h"
#include "mock/mockdevice.h"
#include "mock/mockhandler.h"
#include "mock/mockitem.h"
#include "mock/mocktransport.h"
#include "mock/mocktransportserver.h"

const QString ErrorMessage = "test";

class TestTransfer : public QObject
{
    Q_OBJECT

private slots:

    void initTestCase();

    void testSending();
    void testReceiving();
    void testAbort();

private:

    MockApplication mApplication;
    MockHandler mHandler;
    MockTransportServer mTransportServer;
};

void TestTransfer::initTestCase()
{
    mApplication.application()->handlerRegistry()->add(&mHandler);
    mApplication.application()->transportServerRegistry()->add(&mTransportServer);
}

void TestTransfer::testSending()
{
    MockDevice device;
    Bundle bundle;
    bundle.add(new MockItem);
    Transfer *transfer = new Transfer(mApplication.application(), &device, &bundle);

    // The device saves a copy of the transport so that it can be retrieved
    MockTransport *transport = device.transport();

    QCOMPARE(transfer->direction(), Transfer::Send);
    QCOMPARE(transfer->state(), Transfer::Connecting);

    // Have the transport complete the connection
    transport->emitConnected();

    QCOMPARE(transfer->state(), Transfer::InProgress);

    // The first two packets should be JSON data (the transfer & item headers)
    // and the third will be the payload
    QTRY_COMPARE(transport->packets().count(), 3);

    const MockTransport::PacketList &packets = transport->packets();

    // Ensure the transfer header was sent correctly
    QCOMPARE(packets.at(0).first, Packet::Json);
    QJsonObject transferHeader{
        { "name", MockApplication::DeviceName },
        { "size", QString::number(MockItem::Data.size()) },
        { "count", QString::number(1) }
    };
    QCOMPARE(QJsonDocument::fromJson(packets.at(0).second).object(), transferHeader);

    // Ensure the item header was sent correctly
    QCOMPARE(packets.at(1).first, Packet::Json);
    QJsonObject itemHeader{
        { "name", MockItem::Name },
        { "type", MockItem::Type },
        { "size", QString::number(MockItem::Data.size()) }
    };
    QCOMPARE(QJsonDocument::fromJson(packets.at(1).second).object(), itemHeader);

    // Ensure the item was sent correctly
    QCOMPARE(packets.at(2).first, Packet::Binary);
    QCOMPARE(packets.at(2).second, MockItem::Data);

    QCOMPARE(transfer->state(), Transfer::InProgress);

    // Send the success packet
    transport->sendData(Packet::Success);

    QCOMPARE(transfer->state(), Transfer::Succeeded);
    QVERIFY(transport->isClosed());
}

void TestTransfer::testReceiving()
{
    MockTransport transport;
    Transfer *transfer = new Transfer(mApplication.application(), &transport);

    QCOMPARE(transfer->direction(), Transfer::Receive);
    QCOMPARE(transfer->state(), Transfer::InProgress);

    // Send the transfer header to the transport
    QJsonObject transferHeader{
        { "name", MockDevice::Name },
        { "size", QString::number(MockItem::Data.size()) },
        { "count", QString::number(1) }
    };
    transport.sendData(Packet::Json, QJsonDocument(transferHeader).toJson());

    QCOMPARE(transfer->deviceName(), MockDevice::Name);

    // Send the item header to the transport followed by the data for the item
    QJsonObject itemHeader{
        { "name", MockItem::Name },
        { "type", MockItem::Type },
        { "size", QString::number(MockItem::Data.size()) }
    };
    transport.sendData(Packet::Json, QJsonDocument(itemHeader).toJson());
    transport.sendData(Packet::Binary, MockItem::Data);

    QTRY_COMPARE(transfer->state(), Transfer::Succeeded);

    // Ensure a success packet was sent and the transport closed
    QCOMPARE(transport.packets().count(), 1);
    QCOMPARE(transport.packets().at(0).first, Packet::Success);
    QVERIFY(transport.isClosed());
}

void TestTransfer::testAbort()
{
    MockTransport transport;
    Transfer *transfer = new Transfer(mApplication.application(), &transport);

    // Send a header, though it will be ignored
    QJsonObject transferHeader{
        { "name", MockDevice::Name },
        { "size", QString::number(1) },
        { "count", QString::number(1) }
    };
    transport.sendData(Packet::Json, QJsonDocument(transferHeader).toJson());

    // Abort the transfer by having the transport emit an error
    emit transport.error(ErrorMessage);

    // Confirm the transfer status is set to Failed
    QCOMPARE(transfer->state(), Transfer::Failed);
    QCOMPARE(transfer->error(), ErrorMessage);
}

QTEST_MAIN(TestTransfer)
#include "TestTransfer.moc"
<|endoftext|>


<commit_before>#include "lexer.hpp"

dice::lexer::lexer(std::istream* input, logger* log) :
    input_(input),
    log_(log) {}

dice::symbol dice::lexer::read_token()
{
    for (;;)
    {
        skip_space();

        auto current = static_cast<char>(get_char());
        if (input_->fail())
            return { symbol_type::end };

        auto next = static_cast<char>(input_->peek());
        if (current == '+')
            return symbol{ symbol_type::plus };
        if (current == '-')
            return symbol{ symbol_type::minus };
        if (current == '*')
            return symbol{ symbol_type::times };
        if (current == '/')
            return symbol{ symbol_type::divide };
        if (std::tolower(current) == 'd' && !std::isalpha(next))
            return symbol{ symbol_type::roll_op };
        if (current == '(')
            return symbol{ symbol_type::left_paren };
        if (current == ')')
            return symbol{ symbol_type::right_paren };
        if (current == '[')
            return symbol{ symbol_type::left_square_bracket };
        if (current == ']')
            return symbol{ symbol_type::right_square_bracket };
        if (current == ',')
            return symbol{ symbol_type::param_delim };

        if (current == '<' || current == '>' || current == '!' || current == '=')
        {
            if (next == '=')
            {
                get_char();
                return symbol{ symbol_type::rel_op, std::string(1, current) + "=" };
            }
            else if (current == '<' || current == '>')
            {
                return symbol{ symbol_type::rel_op, std::string(1, current) };
            }
        }

        // parse numbers
        if (std::isdigit(current))
        {
            std::string value(1, current);
            for (;;)
            {
                if (std::isdigit(input_->peek()))
                {
                    value += static_cast<char>(get_char());
                }
                else if (input_->peek() == '.')
                {
                    value += static_cast<char>(get_char());
                }
                else
                {
                    break;
                }
            }

            if (value.back() == '.')
            {
                error("Invalid floating point number. "
                    "Decimal part must not be empty: " + value);
                value += "0";
            }

            return symbol{
                symbol_type::number,
                value
            };
        }

        // parse identifiers
        if (std::isalpha(current))
        {
            // read a string value
            std::string value(1, current);
            for (;;)
            {
                if (input_->peek() == EOF)
                    break;
                if (!std::isalnum(input_->peek()) && input_->peek() != '_')
                    break;
                value += static_cast<char>(get_char());
            }

            // check if it's a reserved keyword
            if (value == "in")
                return symbol{ symbol_type::in };

            // otherwise, it's an identifier
            return symbol{ symbol_type::id, value };
        }

        // format an error message
        const char digits[] = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F'
        };
        error("Unexpected character: '" + std::string(1, current) + "' (0x" +
            std::string(1, digits[(current >> 4) & 0xF]) +
            std::string(1, digits[current & 0xF])  + ").");
    }
}

void dice::lexer::skip_space()
{
    for (;;)
    {
        if (input_->peek() == EOF)
            break;
        if (!std::isspace(input_->peek()))
            break;
        get_char();
    }
}

int dice::lexer::get_char()
{
    auto c = input_->get();
    if (c == '\n')
    {
        ++location_.line;
        location_.col = 0;
    }
    else
    {
        ++location_.col;
    }
    return c;
}

void dice::lexer::error(const std::string& message)
{
    log_->error(location_.line, location_.col, message);
}
<commit_msg>Refactor lexer: make line width smaller<commit_after>#include "lexer.hpp"

dice::lexer::lexer(std::istream* input, logger* log) :
    input_(input),
    log_(log) {}

dice::symbol dice::lexer::read_token()
{
    for (;;)
    {
        skip_space();

        auto current = static_cast<char>(get_char());
        if (input_->fail())
            return { symbol_type::end };

        auto next = static_cast<char>(input_->peek());
        if (current == '+')
            return symbol{ symbol_type::plus };
        if (current == '-')
            return symbol{ symbol_type::minus };
        if (current == '*')
            return symbol{ symbol_type::times };
        if (current == '/')
            return symbol{ symbol_type::divide };
        if (std::tolower(current) == 'd' && !std::isalpha(next))
            return symbol{ symbol_type::roll_op };
        if (current == '(')
            return symbol{ symbol_type::left_paren };
        if (current == ')')
            return symbol{ symbol_type::right_paren };
        if (current == '[')
            return symbol{ symbol_type::left_square_bracket };
        if (current == ']')
            return symbol{ symbol_type::right_square_bracket };
        if (current == ',')
            return symbol{ symbol_type::param_delim };

        if (current == '<' || current == '>' || current == '!' ||
            current == '=')
        {
            if (next == '=')
            {
                get_char();
                return symbol{ symbol_type::rel_op,
                    std::string(1, current) + "=" };
            }
            else if (current == '<' || current == '>')
            {
                return symbol{ symbol_type::rel_op,
                    std::string(1, current) };
            }
        }

        // parse numbers
        if (std::isdigit(current))
        {
            std::string value(1, current);
            for (;;)
            {
                if (std::isdigit(input_->peek()))
                {
                    value += static_cast<char>(get_char());
                }
                else if (input_->peek() == '.')
                {
                    value += static_cast<char>(get_char());
                }
                else
                {
                    break;
                }
            }

            if (value.back() == '.')
            {
                error("Invalid floating point number. "
                    "Decimal part must not be empty: " + value);
                value += "0";
            }

            return symbol{
                symbol_type::number,
                value
            };
        }

        // parse identifiers
        if (std::isalpha(current))
        {
            // read a string value
            std::string value(1, current);
            for (;;)
            {
                if (input_->peek() == EOF)
                    break;
                if (!std::isalnum(input_->peek()) && input_->peek() != '_')
                    break;
                value += static_cast<char>(get_char());
            }

            // check if it's a reserved keyword
            if (value == "in")
                return symbol{ symbol_type::in };

            // otherwise, it's an identifier
            return symbol{ symbol_type::id, value };
        }

        // format an error message
        const char digits[] = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F'
        };
        error("Unexpected character: '" + std::string(1, current) + "' (0x" +
            std::string(1, digits[(current >> 4) & 0xF]) +
            std::string(1, digits[current & 0xF])  + ").");
    }
}

void dice::lexer::skip_space()
{
    for (;;)
    {
        if (input_->peek() == EOF)
            break;
        if (!std::isspace(input_->peek()))
            break;
        get_char();
    }
}

int dice::lexer::get_char()
{
    auto c = input_->get();
    if (c == '\n')
    {
        ++location_.line;
        location_.col = 0;
    }
    else
    {
        ++location_.col;
    }
    return c;
}

void dice::lexer::error(const std::string& message)
{
    log_->error(location_.line, location_.col, message);
}
<|endoftext|>


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

#include "CordioBLE.h"
#include "CordioHCIDriver.h"
#include "hci_defs.h"
#include "hci_api.h"
#include "hci_cmd.h"
#include "hci_core.h"
#include "bstream.h"
#include "wsf_buf.h"
#include <stdbool.h>
#include "hci_mbed_os_adaptation.h"
#include "H4TransportDriver.h"
#include "OdinCordioInterface.h"

namespace ble {
namespace vendor {
namespace odin_w2 {

class HCIDriver : public cordio::CordioHCIDriver {
public:
    HCIDriver(cordio::CordioHCITransportDriver &transport_driver, PinName shutdown_name, PinName hci_rts_name) :
        cordio::CordioHCIDriver(transport_driver),
        shutdown(shutdown_name, 0),
        hci_rts(hci_rts_name, 0),
        service_pack_index(0),
        service_pack_transfered(false) {
    };

    virtual void do_initialize();

    virtual void do_terminate();

    virtual void start_reset_sequence();

    virtual void handle_reset_sequence(uint8_t *pMsg);

private:
    void start_service_pack_transfert(void)
    {
        service_pack_index = 0;
        service_pack_transfered = false;
        send_service_pack_command();
    }

    void send_service_pack_command(void)
    {
        uint16_t cmd_len = odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN];
        cmd_opcode_ack_expected = (odin_service_pack[service_pack_index + 2] << 8) | odin_service_pack[service_pack_index + 1];
        uint8_t *pBuf = hciCmdAlloc(cmd_opcode_ack_expected, cmd_len);
        if (pBuf) {
            memcpy(pBuf, odin_service_pack + service_pack_index + 1, cmd_len + HCI_CMD_HDR_LEN);
            hciCmdSend(pBuf);
        } else {
            printf("Error cannot allocate memory for the buffer");
        }
    }

    void ack_service_pack_command(uint16_t opcode, uint8_t *msg)
    {
        /* check if response opcode is same as expected command opcode */
        MBED_ASSERT (cmd_opcode_ack_expected == opcode);

        // update service pack index
        service_pack_index += (1 + HCI_CMD_HDR_LEN + odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN]);

        if (service_pack_index < service_pack_size)
            send_service_pack_command();
        else if (opcode == HCID_VS_WRITE_BD_ADDR) {
           /* send an HCI Reset command to start the sequence */
            HciResetCmd();
            service_pack_transfered = true;
        } else {
            /* send BT device hardware address write command */
            send_hci_vs_cmd(HCID_VS_WRITE_BD_ADDR);
            cmd_opcode_ack_expected = HCID_VS_WRITE_BD_ADDR;
        }
    }

    void hci_read_resolving_list_size(void)
    {
        /* if LL Privacy is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_PRIVACY) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_PRIVACY)) {
            /* send next command in sequence */
            HciLeReadResolvingListSize();
        } else {
            hciCoreCb.resListSize = 0;

            /* send next command in sequence */
            hci_read_max_data_len();
        }
    }

    void hci_read_max_data_len(void)
    {
        /* if LE Data Packet Length Extensions is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_DATA_LEN_EXT) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_DATA_LEN_EXT)) {
            /* send next command in sequence */
            HciLeReadMaxDataLen();
        } else {
            /* send next command in sequence */
            HciLeRandCmd();
        }
    }

    DigitalOut      shutdown;                       // power/shutdown pin for bt device
    DigitalOut      hci_rts;                        // request to sent pin
    size_t          service_pack_index;             // Index of command to be recently sent over hci
    bool            service_pack_transfered;        // Flag to notify if service pack is completely transferred or not
    uint16_t        cmd_opcode_ack_expected;        // Command against which acknowledgment is expected
    uint32_t        service_pack_size;              // size of service pack
    char            *odin_service_pack ;            // Service pack needs to be provided by driver
    vs_cmd_send_t   send_hci_vs_cmd ;               // callback function to call vendor specific call handler

};

} // namespace odin_w2
} // namespace vendor
} // namespace ble

void ble::vendor::odin_w2::HCIDriver::do_initialize()
{
    cordio_callback_s    callback;

    hci_rts = 1;            // Flow Control is OFF

    shutdown = 0;           // BT Power is OFF
    wait_ms(20);
    shutdown = 1;           // BT Power is ON
    wait_ms(500);

    hci_rts = 0;            // Flow Control is ON

    /* ODIN ble driver initialization function  */
    cbCordio_Btinit(&callback);

    odin_service_pack = callback.Service_pack;
    send_hci_vs_cmd = callback.vs_command_callback;
    service_pack_size = callback.service_pack_size;
}

void ble::vendor::odin_w2::HCIDriver::do_terminate()
{
    // TODO: ASRI
}

void ble::vendor::odin_w2::HCIDriver::start_reset_sequence()
{
    /* Update baudrate of BT to speed up setup time */
    send_hci_vs_cmd(HCID_VS_UPDATE_UART_BAUD_RATE);

}

void ble::vendor::odin_w2::HCIDriver::handle_reset_sequence(uint8_t *pMsg)
{
    uint16_t       opcode;
    static uint8_t randCnt;

    /* if event is a command complete event */
    if (*pMsg == HCI_CMD_CMPL_EVT) {
        /* parse parameters */
        pMsg += HCI_EVT_HDR_LEN;
        pMsg++;                   /* skip num packets */
        BSTREAM_TO_UINT16(opcode, pMsg);
        pMsg++;                   /* skip status */

        if (opcode == HCID_VS_UPDATE_UART_BAUD_RATE) {
            update_uart_baud_rate();
            start_service_pack_transfert();
            return;
        }

        if (service_pack_transfered == false) {
            ack_service_pack_command(opcode, pMsg);
            return;
        }

        /* decode opcode */
        switch (opcode) {

            case HCI_OPCODE_RESET:
                /* Send (fast and slow) clock configuration command */
                send_hci_vs_cmd(HCID_VS_FAST_CLOCK_CONFIG_BTIP);
                break;

            case HCID_VS_FAST_CLOCK_CONFIG_BTIP:
                /* Send deep-sleep behavior control command (setting retransmission, inactivity and rts pulse width for Bt) */
                send_hci_vs_cmd(HCID_VS_HCILL_PARS_CFG);
                break;

            case HCID_VS_HCILL_PARS_CFG:
                /* Send sleep mode configuration command */
                send_hci_vs_cmd(HCID_VS_SLEEP_PROTOCOLS_CFG);
                break;

            case HCID_VS_SLEEP_PROTOCOLS_CFG:
                /* initialize rand command count */
                randCnt = 0;

                /* send next command in sequence */
                HciSetEventMaskCmd((uint8_t *)hciEventMask);
                break;

            case HCI_OPCODE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciLeSetEventMaskCmd((uint8_t *)hciLeEventMask);
                break;

            case HCI_OPCODE_LE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciSetEventMaskPage2Cmd((uint8_t *)hciEventMaskPage2);
                break;

            case HCI_OPCODE_SET_EVENT_MASK_PAGE2:
                /* send next command in sequence */
                HciReadBdAddrCmd();
                break;

            case HCI_OPCODE_READ_BD_ADDR:
                /* parse and store event parameters */
                BdaCpy(hciCoreCb.bdAddr, pMsg);

                /* send next command in sequence */
                HciLeReadBufSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_BUF_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.bufSize, pMsg);
                BSTREAM_TO_UINT8(hciCoreCb.numBufs, pMsg);

                /* initialize ACL buffer accounting */
                hciCoreCb.availBufs = hciCoreCb.numBufs;

                /* send next command in sequence */
                HciLeReadSupStatesCmd();
                break;

            case HCI_OPCODE_LE_READ_SUP_STATES:
                /* parse and store event parameters */
                memcpy(hciCoreCb.leStates, pMsg, HCI_LE_STATES_LEN);

                /* send next command in sequence */
                HciLeReadWhiteListSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_WHITE_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.whiteListSize, pMsg);

                /* send next command in sequence */
                HciLeReadLocalSupFeatCmd();
                break;

            case HCI_OPCODE_LE_READ_LOCAL_SUP_FEAT:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.leSupFeat, pMsg);

                /* send next command in sequence */
                hci_read_resolving_list_size();
                break;

            case HCI_OPCODE_LE_READ_RES_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.resListSize, pMsg);

                /* send next command in sequence */
                hci_read_max_data_len();
                break;

            case HCI_OPCODE_LE_READ_MAX_DATA_LEN:
                uint16_t maxTxOctets;
                uint16_t maxTxTime;

                BSTREAM_TO_UINT16(maxTxOctets, pMsg);
                BSTREAM_TO_UINT16(maxTxTime, pMsg);

               /* use Controller's maximum supported payload octets and packet duration times
                * for transmission as Host's suggested values for maximum transmission number
                * of payload octets and maximum packet transmission time for new connections.
                */
                HciLeWriteDefDataLen(maxTxOctets, maxTxTime);
                break;

            case HCI_OPCODE_LE_WRITE_DEF_DATA_LEN:
                if (hciCoreCb.extResetSeq) {
                    /* send first extended command */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                } else {
                    /* initialize extended parameters */
                    hciCoreCb.maxAdvDataLen = 0;
                    hciCoreCb.numSupAdvSets = 0;
                    hciCoreCb.perAdvListSize = 0;

                    /* send next command in sequence */
                    HciLeRandCmd();
                }
                break;

            case HCI_OPCODE_LE_READ_MAX_ADV_DATA_LEN:
            case HCI_OPCODE_LE_READ_NUM_SUP_ADV_SETS:
            case HCI_OPCODE_LE_READ_PER_ADV_LIST_SIZE:
                if (hciCoreCb.extResetSeq) {
                    /* send next extended command in sequence */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                }
                break;

            case HCI_OPCODE_LE_RAND:
                /* check if need to send second rand command */
                if (randCnt < (HCI_RESET_RAND_CNT - 1)) {
                    randCnt++;
                    HciLeRandCmd();
                } else {
                    signal_reset_sequence_done();
                }
                break;

            default:
                break;
        }
    }
}

ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
    static ble::vendor::cordio::H4TransportDriver transport_driver (/* cbCFG_PIO_PIN_BT_HCI_TX */ PG_14,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RX */ PC_7,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_CTS */ PG_15,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12,
                                                                    115200);
    static ble::vendor::odin_w2::HCIDriver hci_driver ( transport_driver,
                                                        /* cbCFG_PIO_PIN_BT_ENABLE  */ PG_7,
                                                        /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12);

    return hci_driver;
}
<commit_msg>updating method name to make it more descriptive<commit_after>/*
 * Copyright (c) 2018 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CordioBLE.h"
#include "CordioHCIDriver.h"
#include "hci_defs.h"
#include "hci_api.h"
#include "hci_cmd.h"
#include "hci_core.h"
#include "bstream.h"
#include "wsf_buf.h"
#include <stdbool.h>
#include "hci_mbed_os_adaptation.h"
#include "H4TransportDriver.h"
#include "OdinCordioInterface.h"

namespace ble {
namespace vendor {
namespace odin_w2 {

class HCIDriver : public cordio::CordioHCIDriver {
public:
    HCIDriver(cordio::CordioHCITransportDriver &transport_driver, PinName shutdown_name, PinName hci_rts_name) :
        cordio::CordioHCIDriver(transport_driver),
        shutdown(shutdown_name, 0),
        hci_rts(hci_rts_name, 0),
        service_pack_index(0),
        service_pack_transfered(false) {
    };

    virtual void do_initialize();

    virtual void do_terminate();

    virtual void start_reset_sequence();

    virtual void handle_reset_sequence(uint8_t *pMsg);

private:
    void start_service_pack_transfer(void)
    {
        service_pack_index = 0;
        service_pack_transfered = false;
        send_service_pack_command();
    }

    void send_service_pack_command(void)
    {
        uint16_t cmd_len = odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN];
        cmd_opcode_ack_expected = (odin_service_pack[service_pack_index + 2] << 8) | odin_service_pack[service_pack_index + 1];
        uint8_t *pBuf = hciCmdAlloc(cmd_opcode_ack_expected, cmd_len);
        if (pBuf) {
            memcpy(pBuf, odin_service_pack + service_pack_index + 1, cmd_len + HCI_CMD_HDR_LEN);
            hciCmdSend(pBuf);
        } else {
            printf("Error cannot allocate memory for the buffer");
        }
    }

    void ack_service_pack_command(uint16_t opcode, uint8_t *msg)
    {
        /* check if response opcode is same as expected command opcode */
        MBED_ASSERT (cmd_opcode_ack_expected == opcode);

        /* update service pack index */
        service_pack_index += (1 + HCI_CMD_HDR_LEN + odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN]);

        if (service_pack_index < service_pack_size)
            send_service_pack_command();
        else if (opcode == HCID_VS_WRITE_BD_ADDR) {
           /* send an HCI Reset command to start the sequence */
            HciResetCmd();
            service_pack_transfered = true;
        } else {
            /* send BT device hardware address write command */
            send_hci_vs_cmd(HCID_VS_WRITE_BD_ADDR);
            cmd_opcode_ack_expected = HCID_VS_WRITE_BD_ADDR;
        }
    }

    void hci_read_resolving_list_size(void)
    {
        /* if LL Privacy is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_PRIVACY) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_PRIVACY)) {
            /* send next command in sequence */
            HciLeReadResolvingListSize();
        } else {
            hciCoreCb.resListSize = 0;

            /* send next command in sequence */
            hci_read_max_data_len();
        }
    }

    void hci_read_max_data_len(void)
    {
        /* if LE Data Packet Length Extensions is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_DATA_LEN_EXT) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_DATA_LEN_EXT)) {
            /* send next command in sequence */
            HciLeReadMaxDataLen();
        } else {
            /* send next command in sequence */
            HciLeRandCmd();
        }
    }

    DigitalOut      shutdown;                       // power/shutdown pin for bt device
    DigitalOut      hci_rts;                        // request to sent pin
    size_t          service_pack_index;             // Index of command to be recently sent over hci
    bool            service_pack_transfered;        // Flag to notify if service pack is completely transferred or not
    uint16_t        cmd_opcode_ack_expected;        // Command against which acknowledgment is expected
    uint32_t        service_pack_size;              // size of service pack
    char            *odin_service_pack ;            // Service pack needs to be provided by driver
    vs_cmd_send_t   send_hci_vs_cmd ;               // callback function to call vendor specific call handler

};

} // namespace odin_w2
} // namespace vendor
} // namespace ble

void ble::vendor::odin_w2::HCIDriver::do_initialize()
{
    cordio_callback_s    callback;

    hci_rts = 1;            // Flow Control is OFF

    shutdown = 0;           // BT Power is OFF
    wait_ms(20);
    shutdown = 1;           // BT Power is ON
    wait_ms(500);

    hci_rts = 0;            // Flow Control is ON

    /* ODIN ble driver initialization function  */
    cbCordio_Btinit(&callback);

    odin_service_pack = callback.Service_pack;
    send_hci_vs_cmd = callback.vs_command_callback;
    service_pack_size = callback.service_pack_size;
}

void ble::vendor::odin_w2::HCIDriver::do_terminate()
{

}

void ble::vendor::odin_w2::HCIDriver::start_reset_sequence()
{
    /* Update baudrate of ble to speed up setup time */
    send_hci_vs_cmd(HCID_VS_UPDATE_UART_BAUD_RATE);

}

void ble::vendor::odin_w2::HCIDriver::handle_reset_sequence(uint8_t *pMsg)
{
    uint16_t       opcode;
    static uint8_t randCnt;

    /* if event is a command complete event */
    if (*pMsg == HCI_CMD_CMPL_EVT) {
        /* parse parameters */
        pMsg += HCI_EVT_HDR_LEN;
        pMsg++;                   /* skip num packets */
        BSTREAM_TO_UINT16(opcode, pMsg);
        pMsg++;                   /* skip status */

        if (opcode == HCID_VS_UPDATE_UART_BAUD_RATE) {
            update_uart_baud_rate();
            start_service_pack_transfer();
            return;
        }

        if (service_pack_transfered == false) {
            ack_service_pack_command(opcode, pMsg);
            return;
        }

        /* decode opcode */
        switch (opcode) {

            case HCI_OPCODE_RESET:
                /* Send (fast and slow) clock configuration command */
                send_hci_vs_cmd(HCID_VS_FAST_CLOCK_CONFIG_BTIP);
                break;

            case HCID_VS_FAST_CLOCK_CONFIG_BTIP:
                /* Send deep-sleep behavior control command (setting retransmission, inactivity and rts pulse width for Bt) */
                send_hci_vs_cmd(HCID_VS_HCILL_PARS_CFG);
                break;

            case HCID_VS_HCILL_PARS_CFG:
                /* Send sleep mode configuration command */
                send_hci_vs_cmd(HCID_VS_SLEEP_PROTOCOLS_CFG);
                break;

            case HCID_VS_SLEEP_PROTOCOLS_CFG:
                /* initialize rand command count */
                randCnt = 0;

                /* send next command in sequence */
                HciSetEventMaskCmd((uint8_t *)hciEventMask);
                break;

            case HCI_OPCODE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciLeSetEventMaskCmd((uint8_t *)hciLeEventMask);
                break;

            case HCI_OPCODE_LE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciSetEventMaskPage2Cmd((uint8_t *)hciEventMaskPage2);
                break;

            case HCI_OPCODE_SET_EVENT_MASK_PAGE2:
                /* send next command in sequence */
                HciReadBdAddrCmd();
                break;

            case HCI_OPCODE_READ_BD_ADDR:
                /* parse and store event parameters */
                BdaCpy(hciCoreCb.bdAddr, pMsg);

                /* send next command in sequence */
                HciLeReadBufSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_BUF_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.bufSize, pMsg);
                BSTREAM_TO_UINT8(hciCoreCb.numBufs, pMsg);

                /* initialize ACL buffer accounting */
                hciCoreCb.availBufs = hciCoreCb.numBufs;

                /* send next command in sequence */
                HciLeReadSupStatesCmd();
                break;

            case HCI_OPCODE_LE_READ_SUP_STATES:
                /* parse and store event parameters */
                memcpy(hciCoreCb.leStates, pMsg, HCI_LE_STATES_LEN);

                /* send next command in sequence */
                HciLeReadWhiteListSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_WHITE_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.whiteListSize, pMsg);

                /* send next command in sequence */
                HciLeReadLocalSupFeatCmd();
                break;

            case HCI_OPCODE_LE_READ_LOCAL_SUP_FEAT:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.leSupFeat, pMsg);

                /* send next command in sequence */
                hci_read_resolving_list_size();
                break;

            case HCI_OPCODE_LE_READ_RES_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.resListSize, pMsg);

                /* send next command in sequence */
                hci_read_max_data_len();
                break;

            case HCI_OPCODE_LE_READ_MAX_DATA_LEN:
                uint16_t maxTxOctets;
                uint16_t maxTxTime;

                BSTREAM_TO_UINT16(maxTxOctets, pMsg);
                BSTREAM_TO_UINT16(maxTxTime, pMsg);

               /* use Controller's maximum supported payload octets and packet duration times
                * for transmission as Host's suggested values for maximum transmission number
                * of payload octets and maximum packet transmission time for new connections.
                */
                HciLeWriteDefDataLen(maxTxOctets, maxTxTime);
                break;

            case HCI_OPCODE_LE_WRITE_DEF_DATA_LEN:
                if (hciCoreCb.extResetSeq) {
                    /* send first extended command */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                } else {
                    /* initialize extended parameters */
                    hciCoreCb.maxAdvDataLen = 0;
                    hciCoreCb.numSupAdvSets = 0;
                    hciCoreCb.perAdvListSize = 0;

                    /* send next command in sequence */
                    HciLeRandCmd();
                }
                break;

            case HCI_OPCODE_LE_READ_MAX_ADV_DATA_LEN:
            case HCI_OPCODE_LE_READ_NUM_SUP_ADV_SETS:
            case HCI_OPCODE_LE_READ_PER_ADV_LIST_SIZE:
                if (hciCoreCb.extResetSeq) {
                    /* send next extended command in sequence */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                }
                break;

            case HCI_OPCODE_LE_RAND:
                /* check if need to send second rand command */
                if (randCnt < (HCI_RESET_RAND_CNT - 1)) {
                    randCnt++;
                    HciLeRandCmd();
                } else {
                    signal_reset_sequence_done();
                }
                break;

            default:
                break;
        }
    }
}

ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
    static ble::vendor::cordio::H4TransportDriver transport_driver (/* cbCFG_PIO_PIN_BT_HCI_TX */ PG_14,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RX */ PC_7,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_CTS */ PG_15,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12,
                                                                    115200);
    static ble::vendor::odin_w2::HCIDriver hci_driver ( transport_driver,
                                                        /* cbCFG_PIO_PIN_BT_ENABLE  */ PG_7,
                                                        /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12);

    return hci_driver;
}
<|endoftext|>