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

#include "net/http/url_security_manager.h"

#include "base/basictypes.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_filter.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

struct TestData {
  const char* url;
  bool succeds_in_windows_default;
  bool succeeds_in_whitelist;
};

const char* kTestAuthWhitelist = "*example.com,*foobar.com,baz";

// Under Windows the following will be allowed by default:
//    localhost
//    host names without a period.
// In Posix systems (or on Windows if a whitelist is specified explicitly),
// everything depends on the whitelist.
const TestData kTestDataList[] = {
  { "http://localhost", true, false },
  { "http://bat", true, false },
  { "http://www.example.com", false, true },
  { "http://example.com", false, true },
  { "http://foobar.com", false, true },
  { "http://boo.foobar.com", false, true },
  { "http://baz", true, true },
  { "http://www.exampl.com", false, false },
  { "http://example.org", false, false },
  { "http://foobar.net", false, false },
  { "http://boo.fubar.com", false, false },
};

}  // namespace

TEST(URLSecurityManager, CreateWhitelist) {
  HttpAuthFilterWhitelist* auth_filter = new HttpAuthFilterWhitelist(
      kTestAuthWhitelist);
  ASSERT_TRUE(auth_filter);
  // The URL security manager takes ownership of |auth_filter|.
  scoped_ptr<URLSecurityManager> url_security_manager(
      URLSecurityManager::Create(auth_filter, NULL));
  ASSERT_TRUE(url_security_manager.get());

  for (size_t i = 0; i < arraysize(kTestDataList); ++i) {
    GURL gurl(kTestDataList[i].url);
    bool can_use_default =
        url_security_manager->CanUseDefaultCredentials(gurl);

    EXPECT_EQ(kTestDataList[i].succeeds_in_whitelist, can_use_default)
        << " Run: " << i << " URL: '" << gurl << "'";
  }
}

}  // namespace net
<commit_msg>Unit tests for CanDelegate on URLSecurityManager.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/url_security_manager.h"

#include "base/basictypes.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_filter.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

struct TestData {
  const char* url;
  bool succeds_in_windows_default;
  bool succeeds_in_whitelist;
};

const char* kTestAuthWhitelist = "*example.com,*foobar.com,baz";

// Under Windows the following will be allowed by default:
//    localhost
//    host names without a period.
// In Posix systems (or on Windows if a whitelist is specified explicitly),
// everything depends on the whitelist.
const TestData kTestDataList[] = {
  { "http://localhost", true, false },
  { "http://bat", true, false },
  { "http://www.example.com", false, true },
  { "http://example.com", false, true },
  { "http://foobar.com", false, true },
  { "http://boo.foobar.com", false, true },
  { "http://baz", true, true },
  { "http://www.exampl.com", false, false },
  { "http://example.org", false, false },
  { "http://foobar.net", false, false },
  { "http://boo.fubar.com", false, false },
};

}  // namespace

TEST(URLSecurityManager, UseDefaultCredentials) {
  HttpAuthFilterWhitelist* auth_filter = new HttpAuthFilterWhitelist(
      kTestAuthWhitelist);
  ASSERT_TRUE(auth_filter);
  // The URL security manager takes ownership of |auth_filter|.
  scoped_ptr<URLSecurityManager> url_security_manager(
      URLSecurityManager::Create(auth_filter, NULL));
  ASSERT_TRUE(url_security_manager.get());

  for (size_t i = 0; i < arraysize(kTestDataList); ++i) {
    GURL gurl(kTestDataList[i].url);
    bool can_use_default =
        url_security_manager->CanUseDefaultCredentials(gurl);

    EXPECT_EQ(kTestDataList[i].succeeds_in_whitelist, can_use_default)
        << " Run: " << i << " URL: '" << gurl << "'";
  }
}

TEST(URLSecurityManager, CanDelegate) {
  HttpAuthFilterWhitelist* auth_filter = new HttpAuthFilterWhitelist(
      kTestAuthWhitelist);
  ASSERT_TRUE(auth_filter);
  // The URL security manager takes ownership of |auth_filter|.
  scoped_ptr<URLSecurityManager> url_security_manager(
      URLSecurityManager::Create(NULL, auth_filter));
  ASSERT_TRUE(url_security_manager.get());

  for (size_t i = 0; i < arraysize(kTestDataList); ++i) {
    GURL gurl(kTestDataList[i].url);
    bool can_delegate = url_security_manager->CanDelegate(gurl);
    EXPECT_EQ(kTestDataList[i].succeeds_in_whitelist, can_delegate)
        << " Run: " << i << " URL: '" << gurl << "'";
  }
}

TEST(URLSecurityManager, CanDelegate_NoWhitelist) {
  // Nothing can delegate in this case.
  scoped_ptr<URLSecurityManager> url_security_manager(
      URLSecurityManager::Create(NULL, NULL));
  ASSERT_TRUE(url_security_manager.get());

  for (size_t i = 0; i < arraysize(kTestDataList); ++i) {
    GURL gurl(kTestDataList[i].url);
    bool can_delegate = url_security_manager->CanDelegate(gurl);
    EXPECT_EQ(false, can_delegate);
  }
}

}  // namespace net
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * 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 "testsettings.hpp"

#include <realm/util/optional.hpp>

#include "test.hpp"

using namespace realm::util;

TEST(Optional_DefaultConstructor)
{
    Optional<int> x{};
    CHECK(!bool(x));
}

TEST(Optional_NoneConstructor)
{
    Optional<int> x{realm::none};
    CHECK(!bool(x));
}

TEST(Optional_ValueConstructor)
{
    Optional<std::string> a{"foo"};
    CHECK(bool(a));
}

TEST(Optional_MoveConstructor)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b{std::move(a)};
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "");
    CHECK_EQUAL(*b, "foo");
}

TEST(Optional_CopyConstructor)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b{a};
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "foo");
    CHECK_EQUAL(*b, "foo");
}

TEST(Optional_MoveValueConstructor)
{
    std::string a = "foo";
    Optional<std::string> b{std::move(a)};
    CHECK(bool(b));
    CHECK_EQUAL(*b, "foo");
    CHECK_EQUAL(a, "");
}

TEST(Optional_CopyAssignment)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b;
    b = a;
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "foo");
    CHECK_EQUAL(*b, "foo");

    Optional<std::string> c{"foo"};
    Optional<std::string> d{"bar"};
    d = c;
    CHECK(bool(c));
    CHECK(bool(d));
    CHECK_EQUAL(*c, "foo");
    CHECK_EQUAL(*d, "foo");

    Optional<std::string> e;
    Optional<std::string> f{"foo"};
    f = e;
    CHECK(!bool(e));
    CHECK(!bool(f));
}

TEST(Optional_MoveAssignment)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b;
    b = std::move(a);
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*b, "foo");

    Optional<std::string> c{"foo"};
    Optional<std::string> d{"bar"};
    d = std::move(c);
    CHECK(bool(c));
    CHECK(bool(d));
    CHECK_EQUAL(*d, "foo");

    Optional<std::string> e;
    Optional<std::string> f{"foo"};
    f = std::move(e);
    CHECK(!bool(e));
    CHECK(!bool(f));
}

TEST(Optional_ValueAssignment)
{
    Optional<std::string> o;
    o = std::string{"foo"};
    CHECK(bool(o));
    CHECK_EQUAL(*o, "foo");

    o = std::string{"bar"};
    CHECK(bool(o));
    CHECK_EQUAL(*o, "bar");
}

namespace {

struct SetBooleanOnDestroy {
    bool& m_b;
    explicit SetBooleanOnDestroy(bool& b)
        : m_b(b)
    {
    }
    ~SetBooleanOnDestroy()
    {
        m_b = true;
    }
};

} // unnamed namespace

TEST(Optional_Destructor)
{
    bool b = false;
    {
        Optional<SetBooleanOnDestroy> x{SetBooleanOnDestroy(b)};
    }
    CHECK(b);
}

TEST(Optional_DestroyOnAssignNone)
{
    bool b = false;
    {
        Optional<SetBooleanOnDestroy> x{SetBooleanOnDestroy(b)};
        x = realm::none;
        CHECK(b);
    }
    CHECK(b);
}

TEST(Optional_References)
{
    int n = 0;
    Optional<int&> x{n};
    if (x) {
        x.value() = 123;
    }
    CHECK(x);
    CHECK_EQUAL(x.value(), 123);
    x = realm::none;
    CHECK(!x);
}

TEST(Optional_PolymorphicReferences)
{
    struct Foo {
        virtual ~Foo()
        {
        }
    };
    struct Bar : Foo {
        virtual ~Bar()
        {
        }
    };

    Bar bar;
    Optional<Bar&> bar_ref{bar};
    Optional<Foo&> foo_ref{bar_ref};
    CHECK(foo_ref);
    CHECK_EQUAL(&foo_ref.value(), &bar);
}

namespace {

int make_rvalue()
{
    return 1;
}

} // unnamed namespace

TEST(Optional_RvalueReferences)
{
    // Should compile:
    const int foo = 1;
    Optional<const int&> x{foo};
    static_cast<void>(x);

    static_cast<void>(make_rvalue());
    // Should not compile (would generate references to temporaries):
    // Optional<const int&> y{1};
    // Optional<const int&> z = 1;
    // Optional<const int&> w = make_rvalue();
}

namespace {

/// See:
/// http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/dependencies_and_portability/optional_reference_binding.html

const int global_i = 0;

struct TestingReferenceBinding {
    TestingReferenceBinding(const int& ii)
    {
        static_cast<void>(ii);
        REALM_ASSERT(&ii == &global_i);
    }

    void operator=(const int& ii)
    {
        static_cast<void>(ii);
        REALM_ASSERT(&ii == &global_i);
    }

    void operator=(int&&)
    {
        REALM_ASSERT(false);
    }
};

} // unnamed namespace

TEST(Optional_ReferenceBinding)
{
    const int& iref = global_i;
    CHECK_EQUAL(&iref, &global_i);
    TestingReferenceBinding ttt = global_i;
    ttt = global_i;
    TestingReferenceBinding ttt2 = iref;
    ttt2 = iref;
}

TEST(Optional_ValueDoesntGenerateWarning)
{
    // Shouldn't generate any warnings:
    const Optional<int> i{1};
    CHECK(*i);
    int one = 1;
    const Optional<int&> ii{one};
    CHECK(*ii);
}

TEST(Optional_ConstExpr)
{
    // Should compile:
    constexpr Optional<int> a;
    constexpr Optional<int> b{none};
    constexpr Optional<int> c{1};
    CHECK_EQUAL(bool(c), true);
    constexpr int d = *c;
    CHECK_EQUAL(1, d);
// FIXME: Visual Studio 2015's constexpr support isn't sufficient to allow this to compile.
#ifndef _WIN32
    constexpr bool e = bool(Optional<int>{1});
    CHECK_EQUAL(true, e);
    constexpr bool f = bool(Optional<int>{none});
    CHECK_EQUAL(false, f);
#endif
    constexpr int g = b.value_or(1234);
    CHECK_EQUAL(1234, g);
}

// FIXME: Visual Studio 2015's constexpr support isn't sufficient to allow Optional<T&> to compile.
#ifndef _WIN32
TEST(Optional_ReferenceConstExpr)
{
    // Should compile:
    constexpr Optional<const int&> a;
    constexpr Optional<const int&> b{none};
    constexpr Optional<const int&> c{global_i};
    CHECK_EQUAL(bool(c), true);
    constexpr int d = *c;
    CHECK_EQUAL(0, d);
    constexpr bool e = bool(Optional<const int&>{global_i});
    CHECK_EQUAL(true, e);
    constexpr bool f = bool(Optional<const int&>{none});
    CHECK_EQUAL(false, f);
}
#endif

// Disabled for compliance with std::optional
// TEST(Optional_VoidIsEquivalentToBool)
// {
//     auto a = some<void>();
//     CHECK_EQUAL(sizeof(a), sizeof(bool));
//     CHECK(a);
//     Optional<void> b = none;
//     CHECK_EQUAL(sizeof(b), sizeof(bool));
//     CHECK(!b);
// }
<commit_msg>Enable constexpr tests for Optional on Windows now that we're using a version of Visual Studio that has sufficient constexpr support.<commit_after>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * 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 "testsettings.hpp"

#include <realm/util/optional.hpp>

#include "test.hpp"

using namespace realm::util;

TEST(Optional_DefaultConstructor)
{
    Optional<int> x{};
    CHECK(!bool(x));
}

TEST(Optional_NoneConstructor)
{
    Optional<int> x{realm::none};
    CHECK(!bool(x));
}

TEST(Optional_ValueConstructor)
{
    Optional<std::string> a{"foo"};
    CHECK(bool(a));
}

TEST(Optional_MoveConstructor)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b{std::move(a)};
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "");
    CHECK_EQUAL(*b, "foo");
}

TEST(Optional_CopyConstructor)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b{a};
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "foo");
    CHECK_EQUAL(*b, "foo");
}

TEST(Optional_MoveValueConstructor)
{
    std::string a = "foo";
    Optional<std::string> b{std::move(a)};
    CHECK(bool(b));
    CHECK_EQUAL(*b, "foo");
    CHECK_EQUAL(a, "");
}

TEST(Optional_CopyAssignment)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b;
    b = a;
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*a, "foo");
    CHECK_EQUAL(*b, "foo");

    Optional<std::string> c{"foo"};
    Optional<std::string> d{"bar"};
    d = c;
    CHECK(bool(c));
    CHECK(bool(d));
    CHECK_EQUAL(*c, "foo");
    CHECK_EQUAL(*d, "foo");

    Optional<std::string> e;
    Optional<std::string> f{"foo"};
    f = e;
    CHECK(!bool(e));
    CHECK(!bool(f));
}

TEST(Optional_MoveAssignment)
{
    Optional<std::string> a{"foo"};
    Optional<std::string> b;
    b = std::move(a);
    CHECK(bool(a));
    CHECK(bool(b));
    CHECK_EQUAL(*b, "foo");

    Optional<std::string> c{"foo"};
    Optional<std::string> d{"bar"};
    d = std::move(c);
    CHECK(bool(c));
    CHECK(bool(d));
    CHECK_EQUAL(*d, "foo");

    Optional<std::string> e;
    Optional<std::string> f{"foo"};
    f = std::move(e);
    CHECK(!bool(e));
    CHECK(!bool(f));
}

TEST(Optional_ValueAssignment)
{
    Optional<std::string> o;
    o = std::string{"foo"};
    CHECK(bool(o));
    CHECK_EQUAL(*o, "foo");

    o = std::string{"bar"};
    CHECK(bool(o));
    CHECK_EQUAL(*o, "bar");
}

namespace {

struct SetBooleanOnDestroy {
    bool& m_b;
    explicit SetBooleanOnDestroy(bool& b)
        : m_b(b)
    {
    }
    ~SetBooleanOnDestroy()
    {
        m_b = true;
    }
};

} // unnamed namespace

TEST(Optional_Destructor)
{
    bool b = false;
    {
        Optional<SetBooleanOnDestroy> x{SetBooleanOnDestroy(b)};
    }
    CHECK(b);
}

TEST(Optional_DestroyOnAssignNone)
{
    bool b = false;
    {
        Optional<SetBooleanOnDestroy> x{SetBooleanOnDestroy(b)};
        x = realm::none;
        CHECK(b);
    }
    CHECK(b);
}

TEST(Optional_References)
{
    int n = 0;
    Optional<int&> x{n};
    if (x) {
        x.value() = 123;
    }
    CHECK(x);
    CHECK_EQUAL(x.value(), 123);
    x = realm::none;
    CHECK(!x);
}

TEST(Optional_PolymorphicReferences)
{
    struct Foo {
        virtual ~Foo()
        {
        }
    };
    struct Bar : Foo {
        virtual ~Bar()
        {
        }
    };

    Bar bar;
    Optional<Bar&> bar_ref{bar};
    Optional<Foo&> foo_ref{bar_ref};
    CHECK(foo_ref);
    CHECK_EQUAL(&foo_ref.value(), &bar);
}

namespace {

int make_rvalue()
{
    return 1;
}

} // unnamed namespace

TEST(Optional_RvalueReferences)
{
    // Should compile:
    const int foo = 1;
    Optional<const int&> x{foo};
    static_cast<void>(x);

    static_cast<void>(make_rvalue());
    // Should not compile (would generate references to temporaries):
    // Optional<const int&> y{1};
    // Optional<const int&> z = 1;
    // Optional<const int&> w = make_rvalue();
}

namespace {

/// See:
/// http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/dependencies_and_portability/optional_reference_binding.html

const int global_i = 0;

struct TestingReferenceBinding {
    TestingReferenceBinding(const int& ii)
    {
        static_cast<void>(ii);
        REALM_ASSERT(&ii == &global_i);
    }

    void operator=(const int& ii)
    {
        static_cast<void>(ii);
        REALM_ASSERT(&ii == &global_i);
    }

    void operator=(int&&)
    {
        REALM_ASSERT(false);
    }
};

} // unnamed namespace

TEST(Optional_ReferenceBinding)
{
    const int& iref = global_i;
    CHECK_EQUAL(&iref, &global_i);
    TestingReferenceBinding ttt = global_i;
    ttt = global_i;
    TestingReferenceBinding ttt2 = iref;
    ttt2 = iref;
}

TEST(Optional_ValueDoesntGenerateWarning)
{
    // Shouldn't generate any warnings:
    const Optional<int> i{1};
    CHECK(*i);
    int one = 1;
    const Optional<int&> ii{one};
    CHECK(*ii);
}

TEST(Optional_ConstExpr)
{
    // Should compile:
    constexpr Optional<int> a;
    constexpr Optional<int> b{none};
    constexpr Optional<int> c{1};
    CHECK_EQUAL(bool(c), true);
    constexpr int d = *c;
    CHECK_EQUAL(1, d);
    constexpr bool e = bool(Optional<int>{1});
    CHECK_EQUAL(true, e);
    constexpr bool f = bool(Optional<int>{none});
    CHECK_EQUAL(false, f);
    constexpr int g = b.value_or(1234);
    CHECK_EQUAL(1234, g);
}

TEST(Optional_ReferenceConstExpr)
{
    // Should compile:
    constexpr Optional<const int&> a;
    constexpr Optional<const int&> b{none};
    constexpr Optional<const int&> c{global_i};
    CHECK_EQUAL(bool(c), true);
    constexpr int d = *c;
    CHECK_EQUAL(0, d);
    constexpr bool e = bool(Optional<const int&>{global_i});
    CHECK_EQUAL(true, e);
    constexpr bool f = bool(Optional<const int&>{none});
    CHECK_EQUAL(false, f);
}

// Disabled for compliance with std::optional
// TEST(Optional_VoidIsEquivalentToBool)
// {
//     auto a = some<void>();
//     CHECK_EQUAL(sizeof(a), sizeof(bool));
//     CHECK(a);
//     Optional<void> b = none;
//     CHECK_EQUAL(sizeof(b), sizeof(bool));
//     CHECK(!b);
// }
<|endoftext|>


<commit_before>// Example low level rendering Unity plugin

#include <math.h>
#include <stdio.h>
#include <boost/thread.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/offset_ptr.hpp>
#include <vector>
#include <algorithm>

#include "CubemapExtractionPlugin.h"
#include "FrameD3D9.hpp"
#include "FrameD3D11.hpp"
#include "FrameOpenGL.hpp"
#include "AlloShared/config.h"
#include "AlloShared/Process.h"
#include "AlloServer/AlloServer.h"
#include "AlloShared/Binoculars.hpp"

Frame* getFrameFromTexture(void* texturePtr);

// --------------------------------------------------------------------------
// Helper utilities

static ShmAllocator* shmAllocator = nullptr;
static Process* thisProcess = nullptr;
static Process alloServerProcess(ALLOSERVER_ID, false);
static boost::chrono::system_clock::time_point presentationTime;
static boost::mutex d3D11DeviceContextMutex;
static boost::interprocess::managed_shared_memory shm;
static Binoculars* binoculars = nullptr;
static StereoCubemap::Ptr cubemap;

struct CubemapConfig
{
    void** texturePtrs;
    size_t facesCount;
    int resolution;
};
static CubemapConfig* cubemapConfig = nullptr;

struct BinocularsConfig
{
    void* texturePtr;
    int width;
    int height;
};
static BinocularsConfig* binocularsConfig = nullptr;

GLuint tex;

// Prints a string
static void DebugLog (const char* str)
{
	#if UNITY_WIN
	OutputDebugStringA (str);
	#else
	printf ("%s", str);
	#endif
}

void allocateCubemap(CubemapConfig* cubemapConfig)
{
    shm.destroy<StereoCubemap::Ptr>("Cubemap");

    if (cubemapConfig)
    {
        std::vector<CubemapFace*> leftFaces;
        for (int i = 0; i < (std::min)((size_t)Cubemap::MAX_FACES_COUNT, cubemapConfig->facesCount); i++)
        {
            CubemapFace* face = CubemapFace::create(getFrameFromTexture(cubemapConfig->texturePtrs[i]),
                                                    i,
                                                    *shmAllocator);
			leftFaces.push_back(face);
        }

		std::vector<CubemapFace*> rightFaces;
		for (int i = Cubemap::MAX_FACES_COUNT; i < cubemapConfig->facesCount; i++)
		{
			CubemapFace* face = CubemapFace::create(getFrameFromTexture(cubemapConfig->texturePtrs[i]),
				i,
				*shmAllocator);
			rightFaces.push_back(face);
		}

		std::vector<Cubemap*> eyes;
		eyes.push_back(Cubemap::create(leftFaces, *shmAllocator));
		eyes.push_back(Cubemap::create(rightFaces, *shmAllocator));

		cubemap = StereoCubemap::create(eyes, *shmAllocator);
        StereoCubemap::Ptr cubemapPtr = *shm.construct<StereoCubemap::Ptr>("Cubemap")(cubemap.get());
    }
    else
    {
        cubemap = nullptr;
    }
}

void allocateBinoculars(BinocularsConfig* binocularsConfig)
{
    shm.destroy<Binoculars::Ptr>("Binoculars");

    if (binocularsConfig)
    {
        binoculars = Binoculars::create(getFrameFromTexture(binocularsConfig->texturePtr),
                                        *shmAllocator);
        Binoculars::Ptr binocarlsPtr = *shm.construct<Binoculars::Ptr>("Binoculars")(binoculars);
    }
    else
    {
        binoculars = nullptr;
    }
}

void allocateSHM(CubemapConfig* cubemapConfig, BinocularsConfig* binocularsConfig)
{
    unsigned long shmSize = 65536;
    if (cubemapConfig)
    {
        shmSize += cubemapConfig->resolution * cubemapConfig->resolution * 4 * cubemapConfig->facesCount +
                   sizeof(Cubemap) + cubemapConfig->facesCount * sizeof(CubemapFace);
    }
    if (binocularsConfig)
    {
        shmSize += binocularsConfig->width * binocularsConfig->height * 4 + sizeof(Frame);
    }

    boost::interprocess::shared_memory_object::remove(SHM_NAME);

    shm = boost::interprocess::managed_shared_memory(boost::interprocess::open_or_create,
                                                     SHM_NAME,
                                                     shmSize);

    shmAllocator = new ShmAllocator(*(new ShmAllocator::BoostShmAllocator(shm.get_segment_manager())));

    allocateCubemap(cubemapConfig);
    allocateBinoculars(binocularsConfig);

    thisProcess = new Process(CUBEMAPEXTRACTIONPLUGIN_ID, true);
}

void releaseSHM()
{
    shm.destroy<Cubemap::Ptr>("Cubemap");
    cubemap = nullptr;
    cubemapConfig = nullptr;
    shm.destroy<Cubemap::Ptr>("Binoculars");
    binoculars = nullptr;
    binocularsConfig = nullptr;
    boost::interprocess::shared_memory_object::remove(SHM_NAME);
    delete thisProcess;
    thisProcess = nullptr;
}

// --------------------------------------------------------------------------
// UnitySetGraphicsDevice

static int g_DeviceType = -1;

// Actual setup/teardown functions defined below
#if SUPPORT_D3D9
IDirect3DDevice9* g_D3D9Device;
#endif
#if SUPPORT_D3D11
ID3D11Device* g_D3D11Device;
#endif

extern "C" void EXPORT_API UnitySetGraphicsDevice (void* device, int deviceType, int eventType)
{
	// Set device type to -1, i.e. "not recognized by our plugin"
	g_DeviceType = -1;

	#if SUPPORT_D3D9
	// D3D9 device, remember device pointer and device type.
	// The pointer we get is IDirect3DDevice9.
	if (deviceType == kGfxRendererD3D9)
	{
		DebugLog ("Set D3D9 graphics device\n");
		g_DeviceType = deviceType;
		g_D3D9Device = (IDirect3DDevice9*)device;
	}
	#endif

	#if SUPPORT_D3D11
	// D3D11 device, remember device pointer and device type.
	// The pointer we get is ID3D11Device.
	if (deviceType == kGfxRendererD3D11)
	{
		DebugLog ("Set D3D11 graphics device\n");
		g_DeviceType = deviceType;
		g_D3D11Device = (ID3D11Device*)device;
	}
	#endif

	#if SUPPORT_OPENGL
	// If we've got an OpenGL device, remember device type. There's no OpenGL
	// "device pointer" to remember since OpenGL always operates on a currently set
	// global context.
	if (deviceType == kGfxRendererOpenGL)
	{
		DebugLog ("Set OpenGL graphics device\n");
		g_DeviceType = deviceType;
	}
	#endif
}

Frame* getFrameFromTexture(void* texturePtr)
{
	// A script calls this at initialization time; just remember the texture pointer here.
	// Will update texture pixels each frame from the plugin rendering event (texture update
	// needs to happen on the rendering thread).

    Frame* frame = nullptr;

#if SUPPORT_D3D9
	// D3D9 case
	if (g_DeviceType == kGfxRendererD3D9)
	{
        /*frame = FrameD3D9::create(
			(IDirect3DTexture9*)texturePtr,
			index,
			*shmAllocator);*/
	}
#endif

#if SUPPORT_D3D11
	// D3D11 case
	if (g_DeviceType == kGfxRendererD3D11)
	{
		frame = FrameD3D11::create((ID3D11Texture2D*)texturePtr,
			                       *shmAllocator);
	}
#endif

#if SUPPORT_OPENGL
	// OpenGL case
	if (g_DeviceType == kGfxRendererOpenGL)
	{
        frame = FrameOpenGL::create((GLuint)(size_t)texturePtr,
                                    *shmAllocator);
	}
#endif

    return frame;
}

void copyFromGPUToCPU(Frame* frame)
{
    frame->setPresentationTime(presentationTime);

    // PREPARE COPYING

#if SUPPORT_D3D9
    // D3D9 case
    if (g_DeviceType == kGfxRendererD3D9)
    {
        //CubemapFaceD3D9* faceD3D9 = (CubemapFaceD3D9*)face;
        // copy data from GPU to CPU
        //HRESULT hr = g_D3D9Device->GetRenderTargetData(faceD3D9->gpuSurfacePtr, faceD3D9->cpuSurfacePtr);
    }
#endif

#if SUPPORT_D3D11
    // D3D11 case
    if (g_DeviceType == kGfxRendererD3D11)
    {
		FrameD3D11* frameD3D11 = (FrameD3D11*)frame;

        // DirectX 11 is not thread-safe
        boost::mutex::scoped_lock lock(d3D11DeviceContextMutex);

        ID3D11DeviceContext* g_D3D11DeviceContext = NULL;
        g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext);

        // copy data from GPU to CPU
		g_D3D11DeviceContext->CopyResource(frameD3D11->cpuTexturePtr, frameD3D11->gpuTexturePtr);
    }
#endif

#if SUPPORT_OPENGL
    // OpenGL case
    if (g_DeviceType == kGfxRendererOpenGL)
    {
        FrameOpenGL* frameOpenGL = (FrameOpenGL*)frame;
        glBindTexture(GL_TEXTURE_2D, frameOpenGL->getGPUTextureID());
        //glBindTexture(GL_TEXTURE_2D, tex);
    }
#endif

    while (!frame->getMutex().timed_lock(boost::get_system_time() + boost::posix_time::milliseconds(100)))
    {
        if (!alloServerProcess.isAlive())
        {
            // Reset the mutex otherwise it will block forever
            // Reset the condition otherwise it my be in inconsistent state
            // Hacky solution indeed
            void* mutexAddr     = &frame->getMutex();
            void* conditionAddr = &frame->getNewPixelsCondition();
            // That's not possible unfortunately since the mutex is locked and abandoned
            //face->getMutex().~interprocess_mutex();
            memset(mutexAddr, 0, sizeof(boost::interprocess::interprocess_mutex));
            memset(conditionAddr, 0, sizeof(boost::interprocess::interprocess_condition));
            new (mutexAddr)     boost::interprocess::interprocess_mutex;
            new (conditionAddr) boost::interprocess::interprocess_condition;
            return;
        }
    }

    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(frame->getMutex(),
                                                                                boost::interprocess::accept_ownership);
    // COPY

#if SUPPORT_D3D9
    // D3D9 case
    if (g_DeviceType == kGfxRendererD3D9)
    {
        /*CubemapFaceD3D9* faceD3D9 = (CubemapFaceD3D9*)face;
        memcpy(faceD3D9->getPixels(),
			   faceD3D9->lockedRect.pBits,
			   faceD3D9->getWidth() * faceD3D9->getHeight() * 4);*/
    }
#endif

#if SUPPORT_D3D11
    // D3D11 case
    if (g_DeviceType == kGfxRendererD3D11)
    {
		FrameD3D11* frameD3D11 = (FrameD3D11*)frame;
		memcpy(frameD3D11->getPixels(),
			   frameD3D11->resource.pData,
			   frameD3D11->getWidth() * frameD3D11->getHeight() * 3 / 2);
    }
#endif

#if SUPPORT_OPENGL
    // OpenGL case
    if (g_DeviceType == kGfxRendererOpenGL)
    {
        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, frame->getPixels());
    }
#endif

    frame->getNewPixelsCondition().notify_all();
}

void copyFromGPUtoCPU (std::vector<Frame*>& frames)
{
    if (g_DeviceType == kGfxRendererD3D9 || g_DeviceType == kGfxRendererD3D11)
    {
        boost::thread* threads = new boost::thread[frames.size()];

        for (int i = 0; i < frames.size(); i++)
        {
            threads[i] = boost::thread(boost::bind(&copyFromGPUToCPU, frames[i]));
        }

        for (int i = 0; i < frames.size(); i++)
        {
            threads[i].join();
        }
    }
    else
    {
        for (int i = 0; i < frames.size(); i++)
        {
            copyFromGPUToCPU(frames[i]);
        }
    }
}

// --------------------------------------------------------------------------
// UnityRenderEvent
// This will be called for GL.IssuePluginEvent script calls; eventID will
// be the integer passed to IssuePluginEvent. In this example, we just ignore
// that value.

extern "C" void EXPORT_API UnityRenderEvent (int eventID)
{
    // When we use the RenderCubemap.cs and RenderBinoculars.cs scripts
    // This function will get called twice (with different eventIDs).
    // We have to make sure that the extraction only happens once!
    static int extractionEventID = -1;
    if (extractionEventID == -1)
    {
        extractionEventID = eventID;
    }

    if (extractionEventID == eventID)
    {
        // Allocate cubemap the first time we render a frame.
        // By doing so, we can make sure that both
        // the cubemap and the binoculars are fully configured.
        if (!thisProcess)
        {
            allocateSHM(cubemapConfig, binocularsConfig);
        }

        presentationTime = boost::chrono::system_clock::now();

        std::vector<Frame*> frames;
        if (cubemap)
        {
			for (int j = 0; j < cubemap->getEyesCount(); j++)
			{
				Cubemap* eye = cubemap->getEye(j);
				for (int i = 0; i < eye->getFacesCount(); i++)
				{
					frames.push_back(eye->getFace(i)->getContent());
				}
			}
        }

        if (binoculars)
        {
            frames.push_back(binoculars->getContent());
        }

        copyFromGPUtoCPU(frames);
    }
}

// --------------------------------------------------------------------------
// Start stop management

extern "C" void EXPORT_API ConfigureCubemapFromUnity(void** texturePtrs, int cubemapFacesCount, int resolution)
{

    /*glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    char* pixels = new char[resolution * resolution * 3];
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, resolution, resolution, 0, GL_RGB, GL_BYTE, pixels);
    delete[] pixels;*/

    cubemapConfig              = new CubemapConfig;
    cubemapConfig->texturePtrs = texturePtrs;
    cubemapConfig->facesCount  = cubemapFacesCount;
    cubemapConfig->resolution  = resolution;
}

extern "C" void EXPORT_API ConfigureBinocularsFromUnity(void* texturePtr, int width, int height)
{
    binocularsConfig             = new BinocularsConfig;
    binocularsConfig->texturePtr = texturePtr;
    binocularsConfig->width      = width;
    binocularsConfig->height     = height;
}

extern "C" void EXPORT_API StopFromUnity()
{
    releaseSHM();
}<commit_msg>CubemapExtractionPlugin copies less bytesfrom the GPU since YUV420p has less data<commit_after>// Example low level rendering Unity plugin

#include <math.h>
#include <stdio.h>
#include <boost/thread.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/offset_ptr.hpp>
#include <vector>
#include <algorithm>

#include "CubemapExtractionPlugin.h"
#include "FrameD3D9.hpp"
#include "FrameD3D11.hpp"
#include "FrameOpenGL.hpp"
#include "AlloShared/config.h"
#include "AlloShared/Process.h"
#include "AlloServer/AlloServer.h"
#include "AlloShared/Binoculars.hpp"

Frame* getFrameFromTexture(void* texturePtr);

// --------------------------------------------------------------------------
// Helper utilities

static ShmAllocator* shmAllocator = nullptr;
static Process* thisProcess = nullptr;
static Process alloServerProcess(ALLOSERVER_ID, false);
static boost::chrono::system_clock::time_point presentationTime;
static boost::mutex d3D11DeviceContextMutex;
static boost::interprocess::managed_shared_memory shm;
static Binoculars* binoculars = nullptr;
static StereoCubemap::Ptr cubemap;

struct CubemapConfig
{
    void** texturePtrs;
    size_t facesCount;
    int resolution;
};
static CubemapConfig* cubemapConfig = nullptr;

struct BinocularsConfig
{
    void* texturePtr;
    int width;
    int height;
};
static BinocularsConfig* binocularsConfig = nullptr;

GLuint tex;

// Prints a string
static void DebugLog (const char* str)
{
	#if UNITY_WIN
	OutputDebugStringA (str);
	#else
	printf ("%s", str);
	#endif
}

void allocateCubemap(CubemapConfig* cubemapConfig)
{
    shm.destroy<StereoCubemap::Ptr>("Cubemap");

    if (cubemapConfig)
    {
        std::vector<CubemapFace*> leftFaces;
        for (int i = 0; i < (std::min)((size_t)Cubemap::MAX_FACES_COUNT, cubemapConfig->facesCount); i++)
        {
            CubemapFace* face = CubemapFace::create(getFrameFromTexture(cubemapConfig->texturePtrs[i]),
                                                    i,
                                                    *shmAllocator);
			leftFaces.push_back(face);
        }

		std::vector<CubemapFace*> rightFaces;
		for (int i = Cubemap::MAX_FACES_COUNT; i < cubemapConfig->facesCount; i++)
		{
			CubemapFace* face = CubemapFace::create(getFrameFromTexture(cubemapConfig->texturePtrs[i]),
				i,
				*shmAllocator);
			rightFaces.push_back(face);
		}

		std::vector<Cubemap*> eyes;
		eyes.push_back(Cubemap::create(leftFaces, *shmAllocator));
		eyes.push_back(Cubemap::create(rightFaces, *shmAllocator));

		cubemap = StereoCubemap::create(eyes, *shmAllocator);
        StereoCubemap::Ptr cubemapPtr = *shm.construct<StereoCubemap::Ptr>("Cubemap")(cubemap.get());
    }
    else
    {
        cubemap = nullptr;
    }
}

void allocateBinoculars(BinocularsConfig* binocularsConfig)
{
    shm.destroy<Binoculars::Ptr>("Binoculars");

    if (binocularsConfig)
    {
        binoculars = Binoculars::create(getFrameFromTexture(binocularsConfig->texturePtr),
                                        *shmAllocator);
        Binoculars::Ptr binocarlsPtr = *shm.construct<Binoculars::Ptr>("Binoculars")(binoculars);
    }
    else
    {
        binoculars = nullptr;
    }
}

void allocateSHM(CubemapConfig* cubemapConfig, BinocularsConfig* binocularsConfig)
{
    unsigned long shmSize = 65536;
    if (cubemapConfig)
    {
        shmSize += cubemapConfig->resolution * cubemapConfig->resolution * 4 * cubemapConfig->facesCount +
                   sizeof(Cubemap) + cubemapConfig->facesCount * sizeof(CubemapFace);
    }
    if (binocularsConfig)
    {
        shmSize += binocularsConfig->width * binocularsConfig->height * 4 + sizeof(Frame);
    }

    boost::interprocess::shared_memory_object::remove(SHM_NAME);

    shm = boost::interprocess::managed_shared_memory(boost::interprocess::open_or_create,
                                                     SHM_NAME,
                                                     shmSize);

    shmAllocator = new ShmAllocator(*(new ShmAllocator::BoostShmAllocator(shm.get_segment_manager())));

    allocateCubemap(cubemapConfig);
    allocateBinoculars(binocularsConfig);

    thisProcess = new Process(CUBEMAPEXTRACTIONPLUGIN_ID, true);
}

void releaseSHM()
{
    shm.destroy<Cubemap::Ptr>("Cubemap");
    cubemap = nullptr;
    cubemapConfig = nullptr;
    shm.destroy<Cubemap::Ptr>("Binoculars");
    binoculars = nullptr;
    binocularsConfig = nullptr;
    boost::interprocess::shared_memory_object::remove(SHM_NAME);
    delete thisProcess;
    thisProcess = nullptr;
}

// --------------------------------------------------------------------------
// UnitySetGraphicsDevice

static int g_DeviceType = -1;

// Actual setup/teardown functions defined below
#if SUPPORT_D3D9
IDirect3DDevice9* g_D3D9Device;
#endif
#if SUPPORT_D3D11
ID3D11Device* g_D3D11Device;
#endif

extern "C" void EXPORT_API UnitySetGraphicsDevice (void* device, int deviceType, int eventType)
{
	// Set device type to -1, i.e. "not recognized by our plugin"
	g_DeviceType = -1;

	#if SUPPORT_D3D9
	// D3D9 device, remember device pointer and device type.
	// The pointer we get is IDirect3DDevice9.
	if (deviceType == kGfxRendererD3D9)
	{
		DebugLog ("Set D3D9 graphics device\n");
		g_DeviceType = deviceType;
		g_D3D9Device = (IDirect3DDevice9*)device;
	}
	#endif

	#if SUPPORT_D3D11
	// D3D11 device, remember device pointer and device type.
	// The pointer we get is ID3D11Device.
	if (deviceType == kGfxRendererD3D11)
	{
		DebugLog ("Set D3D11 graphics device\n");
		g_DeviceType = deviceType;
		g_D3D11Device = (ID3D11Device*)device;
	}
	#endif

	#if SUPPORT_OPENGL
	// If we've got an OpenGL device, remember device type. There's no OpenGL
	// "device pointer" to remember since OpenGL always operates on a currently set
	// global context.
	if (deviceType == kGfxRendererOpenGL)
	{
		DebugLog ("Set OpenGL graphics device\n");
		g_DeviceType = deviceType;
	}
	#endif
}

Frame* getFrameFromTexture(void* texturePtr)
{
	// A script calls this at initialization time; just remember the texture pointer here.
	// Will update texture pixels each frame from the plugin rendering event (texture update
	// needs to happen on the rendering thread).

    Frame* frame = nullptr;

#if SUPPORT_D3D9
	// D3D9 case
	if (g_DeviceType == kGfxRendererD3D9)
	{
        /*frame = FrameD3D9::create(
			(IDirect3DTexture9*)texturePtr,
			index,
			*shmAllocator);*/
	}
#endif

#if SUPPORT_D3D11
	// D3D11 case
	if (g_DeviceType == kGfxRendererD3D11)
	{
		frame = FrameD3D11::create((ID3D11Texture2D*)texturePtr,
			                       *shmAllocator);
	}
#endif

#if SUPPORT_OPENGL
	// OpenGL case
	if (g_DeviceType == kGfxRendererOpenGL)
	{
        frame = FrameOpenGL::create((GLuint)(size_t)texturePtr,
                                    *shmAllocator);
	}
#endif

    return frame;
}

void copyFromGPUToCPU(Frame* frame)
{
    frame->setPresentationTime(presentationTime);

    // PREPARE COPYING

#if SUPPORT_D3D9
    // D3D9 case
    if (g_DeviceType == kGfxRendererD3D9)
    {
        //CubemapFaceD3D9* faceD3D9 = (CubemapFaceD3D9*)face;
        // copy data from GPU to CPU
        //HRESULT hr = g_D3D9Device->GetRenderTargetData(faceD3D9->gpuSurfacePtr, faceD3D9->cpuSurfacePtr);
    }
#endif

#if SUPPORT_D3D11
    // D3D11 case
    if (g_DeviceType == kGfxRendererD3D11)
    {
		FrameD3D11* frameD3D11 = (FrameD3D11*)frame;

        // DirectX 11 is not thread-safe
        boost::mutex::scoped_lock lock(d3D11DeviceContextMutex);

        ID3D11DeviceContext* g_D3D11DeviceContext = NULL;
        g_D3D11Device->GetImmediateContext(&g_D3D11DeviceContext);

        // Copy data from GPU to CPU
		// Since the texture is YUV420p encoded we only need 3/8 the amount of data
		D3D11_BOX region =
		{
			0, 0, 0,
			frameD3D11->getWidth(), frameD3D11->getHeight() * 3 / 8, 1
		};
		g_D3D11DeviceContext->CopySubresourceRegion(frameD3D11->cpuTexturePtr, 0, 0, 0, 0, frameD3D11->gpuTexturePtr, 0, &region);
    }
#endif

#if SUPPORT_OPENGL
    // OpenGL case
    if (g_DeviceType == kGfxRendererOpenGL)
    {
        FrameOpenGL* frameOpenGL = (FrameOpenGL*)frame;
        glBindTexture(GL_TEXTURE_2D, frameOpenGL->getGPUTextureID());
        //glBindTexture(GL_TEXTURE_2D, tex);
    }
#endif

    while (!frame->getMutex().timed_lock(boost::get_system_time() + boost::posix_time::milliseconds(100)))
    {
        if (!alloServerProcess.isAlive())
        {
            // Reset the mutex otherwise it will block forever
            // Reset the condition otherwise it my be in inconsistent state
            // Hacky solution indeed
            void* mutexAddr     = &frame->getMutex();
            void* conditionAddr = &frame->getNewPixelsCondition();
            // That's not possible unfortunately since the mutex is locked and abandoned
            //face->getMutex().~interprocess_mutex();
            memset(mutexAddr, 0, sizeof(boost::interprocess::interprocess_mutex));
            memset(conditionAddr, 0, sizeof(boost::interprocess::interprocess_condition));
            new (mutexAddr)     boost::interprocess::interprocess_mutex;
            new (conditionAddr) boost::interprocess::interprocess_condition;
            return;
        }
    }

    boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(frame->getMutex(),
                                                                                boost::interprocess::accept_ownership);
    // COPY

#if SUPPORT_D3D9
    // D3D9 case
    if (g_DeviceType == kGfxRendererD3D9)
    {
        /*CubemapFaceD3D9* faceD3D9 = (CubemapFaceD3D9*)face;
        memcpy(faceD3D9->getPixels(),
			   faceD3D9->lockedRect.pBits,
			   faceD3D9->getWidth() * faceD3D9->getHeight() * 4);*/
    }
#endif

#if SUPPORT_D3D11
    // D3D11 case
    if (g_DeviceType == kGfxRendererD3D11)
    {
		FrameD3D11* frameD3D11 = (FrameD3D11*)frame;
		memcpy(frameD3D11->getPixels(),
			   frameD3D11->resource.pData,
			   frameD3D11->getWidth() * frameD3D11->getHeight() * 3 / 2);
    }
#endif

#if SUPPORT_OPENGL
    // OpenGL case
    if (g_DeviceType == kGfxRendererOpenGL)
    {
        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, frame->getPixels());
    }
#endif

    frame->getNewPixelsCondition().notify_all();
}

void copyFromGPUtoCPU (std::vector<Frame*>& frames)
{
    if (g_DeviceType == kGfxRendererD3D9 || g_DeviceType == kGfxRendererD3D11)
    {
        boost::thread* threads = new boost::thread[frames.size()];

        for (int i = 0; i < frames.size(); i++)
        {
            threads[i] = boost::thread(boost::bind(&copyFromGPUToCPU, frames[i]));
        }

        for (int i = 0; i < frames.size(); i++)
        {
            threads[i].join();
        }
    }
    else
    {
        for (int i = 0; i < frames.size(); i++)
        {
            copyFromGPUToCPU(frames[i]);
        }
    }
}

// --------------------------------------------------------------------------
// UnityRenderEvent
// This will be called for GL.IssuePluginEvent script calls; eventID will
// be the integer passed to IssuePluginEvent. In this example, we just ignore
// that value.

extern "C" void EXPORT_API UnityRenderEvent (int eventID)
{
    // When we use the RenderCubemap.cs and RenderBinoculars.cs scripts
    // This function will get called twice (with different eventIDs).
    // We have to make sure that the extraction only happens once!
    static int extractionEventID = -1;
    if (extractionEventID == -1)
    {
        extractionEventID = eventID;
    }

    if (extractionEventID == eventID)
    {
        // Allocate cubemap the first time we render a frame.
        // By doing so, we can make sure that both
        // the cubemap and the binoculars are fully configured.
        if (!thisProcess)
        {
            allocateSHM(cubemapConfig, binocularsConfig);
        }

        presentationTime = boost::chrono::system_clock::now();

        std::vector<Frame*> frames;
        if (cubemap)
        {
			for (int j = 0; j < cubemap->getEyesCount(); j++)
			{
				Cubemap* eye = cubemap->getEye(j);
				for (int i = 0; i < eye->getFacesCount(); i++)
				{
					frames.push_back(eye->getFace(i)->getContent());
				}
			}
        }

        if (binoculars)
        {
            frames.push_back(binoculars->getContent());
        }

        copyFromGPUtoCPU(frames);
    }
}

// --------------------------------------------------------------------------
// Start stop management

extern "C" void EXPORT_API ConfigureCubemapFromUnity(void** texturePtrs, int cubemapFacesCount, int resolution)
{

    /*glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    char* pixels = new char[resolution * resolution * 3];
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, resolution, resolution, 0, GL_RGB, GL_BYTE, pixels);
    delete[] pixels;*/

    cubemapConfig              = new CubemapConfig;
    cubemapConfig->texturePtrs = texturePtrs;
    cubemapConfig->facesCount  = cubemapFacesCount;
    cubemapConfig->resolution  = resolution;
}

extern "C" void EXPORT_API ConfigureBinocularsFromUnity(void* texturePtr, int width, int height)
{
    binocularsConfig             = new BinocularsConfig;
    binocularsConfig->texturePtr = texturePtr;
    binocularsConfig->width      = width;
    binocularsConfig->height     = height;
}

extern "C" void EXPORT_API StopFromUnity()
{
    releaseSHM();
}<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/graph/graphattr.h"

#include <boost/thread/thread.hpp>
#include <boost/make_shared.hpp>

#include "elm/core/debug_utils.h"
#include "elm/core/exception.h"
#include "elm/core/graph/graphattr_impl.h"

using namespace boost;
using namespace cv;
using namespace elm;

GraphAttr::~GraphAttr()
{
    impl.reset();
}

GraphAttr::GraphAttr()
    : impl(new GraphAttr_Impl())
{
}

GraphAttr::GraphAttr(const Mat1f &map_img, const Mat1b &mask)
    : impl(new GraphAttr_Impl(map_img, mask))
{
}

size_t GraphAttr::num_vertices() const
{
    return static_cast<size_t>(boost::num_vertices(impl->g));
}

float GraphAttr::operator ()(int idx_u, int idx_v) const
{
    GraphAttrTraits::vertex_descriptor u(idx_u);
    GraphAttrTraits::vertex_descriptor v(idx_v);

    typename boost::property_map < GraphAttrType, boost::edge_weight_t >::type
            weight = get(boost::edge_weight, impl->g);

    GraphAttrTraits::edge_descriptor e;
    bool found;

    boost::tie(e, found) = edge(u, v, impl->g);
    return found? get(weight, e) : 0.f;
}

void GraphAttr::AdjacencyMat(Mat1f &adj) const
{
    int nb_vertices = static_cast<int>(num_vertices());
    if(adj.rows < nb_vertices || adj.cols < nb_vertices) {

        adj = Mat1f(nb_vertices, nb_vertices);
    }

    for(int idx_u=0; idx_u<nb_vertices; idx_u++) {

        for(int idx_v=0; idx_v<nb_vertices; idx_v++) {

            adj(idx_u, idx_v) = operator ()(idx_u, idx_v);
        }
    }
}

VecF GraphAttr::VerticesIds() const
{
    VecF vtx_ids(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);
    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;
        vtx_ids[i++] = vertex_color_id[*vi];
    }

    return vtx_ids;
}

void GraphAttr::addAttributes(float vtx_id, const Mat1f &attr)
{
    VtxDescriptor descriptor;
    if(impl->findVtxDescriptor(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        vertex_attributes[descriptor] = attr;
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::getAttributes(float vtx_id) const
{
    VtxDescriptor descriptor;
    if(impl->findVtxDescriptor(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        return vertex_attributes[descriptor];
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::applyVertexToMap(float vtx_id, Mat1f (*func)(const Mat1f &img, const Mat1b &mask)) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVtxDescriptor(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        float vtx_color = vertex_color_id[vtx_descriptor];
        Mat1b _mask = impl->src_map_img == vtx_color;
        vtx_result = func(impl->src_map_img, _mask);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

void noop_del(VecMat1f *)
{
    return;
}

VecMat1f GraphAttr::applyVerticesToMap(Mat1f (*func)(const Mat1f &img, const Mat1b &mask)) const
{
    VecMat1f results(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);

    thread_group group;

    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;

        float vtx_color = vertex_color_id[*vi];

        group.create_thread(boost::bind(&elm::apply_masked,
                                        func,
                                        vtx_color, impl->src_map_img, boost::ref(results[i++]))
                            );
    }

    group.join_all();

    return results;
}

// non member functions

void elm::apply_masked(cv::Mat1f (*func) (const cv::Mat1f &img, const cv::Mat1b &mask),
                       float color,
                       const Mat1f &img,
                       Mat1f &dst)
{
    Mat1b _mask = img == color;
    dst = func(img, _mask);
}

<commit_msg>remove unsused noop_deleter()<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/graph/graphattr.h"

#include <boost/thread/thread.hpp>

#include "elm/core/debug_utils.h"
#include "elm/core/exception.h"
#include "elm/core/graph/graphattr_impl.h"

using namespace boost;
using namespace cv;
using namespace elm;

GraphAttr::~GraphAttr()
{
    impl.reset();
}

GraphAttr::GraphAttr()
    : impl(new GraphAttr_Impl())
{
}

GraphAttr::GraphAttr(const Mat1f &map_img, const Mat1b &mask)
    : impl(new GraphAttr_Impl(map_img, mask))
{
}

size_t GraphAttr::num_vertices() const
{
    return static_cast<size_t>(boost::num_vertices(impl->g));
}

float GraphAttr::operator ()(int idx_u, int idx_v) const
{
    GraphAttrTraits::vertex_descriptor u(idx_u);
    GraphAttrTraits::vertex_descriptor v(idx_v);

    typename boost::property_map < GraphAttrType, boost::edge_weight_t >::type
            weight = get(boost::edge_weight, impl->g);

    GraphAttrTraits::edge_descriptor e;
    bool found;

    boost::tie(e, found) = edge(u, v, impl->g);
    return found? get(weight, e) : 0.f;
}

void GraphAttr::AdjacencyMat(Mat1f &adj) const
{
    int nb_vertices = static_cast<int>(num_vertices());
    if(adj.rows < nb_vertices || adj.cols < nb_vertices) {

        adj = Mat1f(nb_vertices, nb_vertices);
    }

    for(int idx_u=0; idx_u<nb_vertices; idx_u++) {

        for(int idx_v=0; idx_v<nb_vertices; idx_v++) {

            adj(idx_u, idx_v) = operator ()(idx_u, idx_v);
        }
    }
}

VecF GraphAttr::VerticesIds() const
{
    VecF vtx_ids(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);
    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;
        vtx_ids[i++] = vertex_color_id[*vi];
    }

    return vtx_ids;
}

void GraphAttr::addAttributes(float vtx_id, const Mat1f &attr)
{
    VtxDescriptor descriptor;
    if(impl->findVtxDescriptor(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        vertex_attributes[descriptor] = attr;
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::getAttributes(float vtx_id) const
{
    VtxDescriptor descriptor;
    if(impl->findVtxDescriptor(vtx_id, descriptor)) {

        property_map<GraphAttrType, vertex_index2_t>::type
                vertex_attributes = get(vertex_index2, impl->g);

        return vertex_attributes[descriptor];
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }
}

Mat1f GraphAttr::applyVertexToMap(float vtx_id, Mat1f (*func)(const Mat1f &img, const Mat1b &mask)) const
{
    Mat1f vtx_result;

    VtxDescriptor vtx_descriptor;
    if(impl->findVtxDescriptor(vtx_id, vtx_descriptor)) {

        property_map<GraphAttrType, vertex_color_t>::type
                vertex_color_id = get(vertex_color, impl->g);

        float vtx_color = vertex_color_id[vtx_descriptor];
        Mat1b _mask = impl->src_map_img == vtx_color;
        vtx_result = func(impl->src_map_img, _mask);
    }
    else {
        std::stringstream s;
        s << "No vertex with id (" << vtx_id << ").";
        ELM_THROW_KEY_ERROR(s.str());
    }

    return vtx_result;
}

VecMat1f GraphAttr::applyVerticesToMap(Mat1f (*func)(const Mat1f &img, const Mat1b &mask)) const
{
    VecMat1f results(num_vertices());

    property_map<GraphAttrType, vertex_color_t>::type
            vertex_color_id = get(vertex_color, impl->g);

    GraphAttrTraits::vertex_iterator vi, vi_end, next;
    tie(vi, vi_end) = vertices(impl->g);

    thread_group group;

    int i=0;
    for (next = vi; vi != vi_end; vi = next) {

        ++next;

        float vtx_color = vertex_color_id[*vi];

        group.create_thread(boost::bind(&elm::apply_masked,
                                        func,
                                        vtx_color, impl->src_map_img, boost::ref(results[i++]))
                            );
    }

    group.join_all();

    return results;
}

// non member functions

void elm::apply_masked(cv::Mat1f (*func) (const cv::Mat1f &img, const cv::Mat1b &mask),
                       float color,
                       const Mat1f &img,
                       Mat1f &dst)
{
    Mat1b _mask = img == color;
    dst = func(img, _mask);
}

<|endoftext|>


<commit_before>#include "nevil/trial_controller.hpp"

nevil::trial_controller::trial_controller() {}

nevil::trial_controller::trial_controller(int id, unsigned seed, nevil::args &cl_args)
  : _trial_id(id)
{
  srand(seed);

  //Default Values
  _population_size = 80;
  _max_generation_num = 200;
  _max_step_num = 1000;
  std::string trial_name = "SiblingParentNeuronTrial";
  float mutation_rate = 0.25;
  float bracket_ratio = 0.10;

  // Reading the command line arguments
  nevil::args::const_iterator it;

  if ((it = cl_args.find("xn")) != cl_args.end())
    trial_name = it->second;

  if ((it = cl_args.find("mg")) != cl_args.end())
    _max_generation_num = stoi(it->second);

  if ((it = cl_args.find("ms")) != cl_args.end())
    _max_step_num = stoi(it->second);

  if ((it = cl_args.find("ps")) != cl_args.end())
    _population_size = stoi(it->second);
  else
    cl_args["ps"] = std::to_string(_population_size);

  if ((it = cl_args.find("br")) != cl_args.end())
  {
    bracket_ratio = stof(it->second);
    if (bracket_ratio < 0 || bracket_ratio > 1)
    {
      printf("Bracket ratio must be between 0 and 1. '%.2f' was given.\nTerminating ...", bracket_ratio);
      exit(-1);
    }
  }
  else
    cl_args["br"] = std::to_string(bracket_ratio);

  if ((it = cl_args.find("mr")) != cl_args.end())
  {
    mutation_rate = stof(it->second);
    if (mutation_rate < 0 || mutation_rate > 1)
    {
      printf("Mutation rate must be between 0 and 1. '%.2f' was given.\nTerminating ...", mutation_rate);
      exit(-1);
    }
  }
  else
    cl_args["mr"] = std::to_string(mutation_rate);

  // Sibling Neuron Parameter
  if ((it = cl_args.find("sn")) != cl_args.end())
    _root["config"]["siblingNeuron"] = (it->second == "true");
  else
    cl_args["sn"] = "false";

  //Speed Parameter
  if ((it = cl_args.find("speedA")) != cl_args.end())
    _root["config"]["speedA"] = std::stod(it->second);
  else
    cl_args["speedA"] = "12";

  if ((it = cl_args.find("speedB")) != cl_args.end())
    _root["config"]["speedB"] = std::stod(it->second);
  else
    cl_args["speedB"] = "12";

  if ((it = cl_args.find("speedP")) != cl_args.end())
    _root["config"]["speedP"] = std::stod(it->second);
  else
    cl_args["speedP"] = "12";

  //Angle Parameter
  if ((it = cl_args.find("angleA")) != cl_args.end())
    _root["config"]["angleA"] = std::stod(it->second);
  else
    cl_args["angleA"] = "0";

  if ((it = cl_args.find("angleB")) != cl_args.end())
    _root["config"]["angleB"] = std::stod(it->second);
  else
    cl_args["angleB"] = "0";

  if ((it = cl_args.find("angleP")) != cl_args.end())
    _root["config"]["angleP"] = std::stod(it->second);
  else
    cl_args["angleB"] = "0";

  // Creating a log file
  _trial_logger.start_new_file(cl_args["xp_path"], "Trial_" + std::to_string(_trial_id) + ".json");
  _generational_data = Json::Value(Json::arrayValue);

  // JSON style
  _root["config"]["trialName"] = trial_name;
  _root["config"]["randomSeed"] = seed;
  _root["config"]["numberOfGenerations"] = _max_generation_num;
  _root["config"]["numberOfTimesteps"] = _max_step_num;
  _root["config"]["populationSize"] = _population_size;
  _root["config"]["bracketRatio"] = bracket_ratio;
  _root["config"]["mutationRate"] = mutation_rate;

  // Instantiating a trial
  if (trial_name == "SiblingParentNeuronTrial"){
    cl_args["angleA"] = "0";
    cl_args["angleB"] = "0";
    cl_args["angleP"] = "0";
    _trial = new nevil::sibling_parent_trial(cl_args);
  }
  else if (trial_name == "SiblingParentAsymTrial")
  {
    cl_args["sn"] = "false";
    _trial = new nevil::sibling_parent_trial(cl_args);
  }
  else if (trial_name == "SiblingParentDetectionTrial")
  {
    cl_args["sn"] = "false";
    _trial = new nevil::sibling_sibling_trial(cl_args); // Change this
  }
  else
  {
    printf("Trial '%s' is not defined.\nTerminating...\n", trial_name.c_str());
    exit(1);
  }

  _current_generation = 0;
  _current_individual = 0;
  _current_step = 0;
  printf("-Trial %d: starting\n", _trial_id);
  printf("-Trial %d: running generation %d\n", _trial_id, _current_generation);
}

nevil::trial_controller::~trial_controller()
{
  delete _trial;
}

Enki::World *nevil::trial_controller::get_trial_world()
{
  return _trial->get_trial_world();
}

bool nevil::trial_controller::run()
{
  if (_current_generation < _max_generation_num)
  {
    if (_current_individual < _population_size)
    {
      if (_current_step == 0 && _current_individual != _population_size)
        _trial->reset();

      if (_current_step < _max_step_num)
      {
        _trial->update();
        ++_current_step;
      }
      else
      {
        ++_current_individual;
        _current_step = 0;
      }
    }
    else
    {
      _evaluate();
      ++_current_generation;
      _current_individual = 0;
      _current_step = 0;
      printf("-Trial %d: running generation %d\n", _trial_id, _current_generation);
    }
    return true;
  }

  _end();
  return false;
}

void nevil::trial_controller::_evaluate()
{
  Json::Value data;
  data["generationNumber"] = _current_generation;
  data["individualList"] = _trial->get_generation_data();

  _trial->epoch();

  data["bestIndividual"] = _trial->get_best_individual().json();
  _generational_data.append(data);
}

void nevil::trial_controller::_end()
{
  printf("-Trial %d: finished\n", _trial_id);
  _root["generationalData"] = _generational_data;
  _trial_logger.write(_root);
  _trial_logger.close_file();
}
<commit_msg>Updated the project to include the parent of each generation in the arena. Tested - it runs.<commit_after>#include "nevil/trial_controller.hpp"

nevil::trial_controller::trial_controller() {}

nevil::trial_controller::trial_controller(int id, unsigned seed, nevil::args &cl_args)
  : _trial_id(id)
{
  srand(seed);

  //Default Values
  _population_size = 80;
  _max_generation_num = 200;
  _max_step_num = 1000;
  std::string trial_name = "SiblingParentNeuronTrial";
  float mutation_rate = 0.25;
  float bracket_ratio = 0.10;

  // Reading the command line arguments
  nevil::args::const_iterator it;

  if ((it = cl_args.find("xn")) != cl_args.end())
    trial_name = it->second;

  if ((it = cl_args.find("mg")) != cl_args.end())
    _max_generation_num = stoi(it->second);

  if ((it = cl_args.find("ms")) != cl_args.end())
    _max_step_num = stoi(it->second);

  if ((it = cl_args.find("ps")) != cl_args.end())
    _population_size = stoi(it->second);
  else
    cl_args["ps"] = std::to_string(_population_size);

  if ((it = cl_args.find("br")) != cl_args.end())
  {
    bracket_ratio = stof(it->second);
    if (bracket_ratio < 0 || bracket_ratio > 1)
    {
      printf("Bracket ratio must be between 0 and 1. '%.2f' was given.\nTerminating ...", bracket_ratio);
      exit(-1);
    }
  }
  else
    cl_args["br"] = std::to_string(bracket_ratio);

  if ((it = cl_args.find("mr")) != cl_args.end())
  {
    mutation_rate = stof(it->second);
    if (mutation_rate < 0 || mutation_rate > 1)
    {
      printf("Mutation rate must be between 0 and 1. '%.2f' was given.\nTerminating ...", mutation_rate);
      exit(-1);
    }
  }
  else
    cl_args["mr"] = std::to_string(mutation_rate);

  // Sibling Neuron Parameter
  if ((it = cl_args.find("sn")) != cl_args.end())
    _root["config"]["siblingNeuron"] = (it->second == "true");
  else
    cl_args["sn"] = "false";

  //Speed Parameter
  if ((it = cl_args.find("speedA")) != cl_args.end())
    _root["config"]["speedA"] = std::stod(it->second);
  else
    cl_args["speedA"] = "12";

  if ((it = cl_args.find("speedB")) != cl_args.end())
    _root["config"]["speedB"] = std::stod(it->second);
  else
    cl_args["speedB"] = "12";

  if ((it = cl_args.find("speedP")) != cl_args.end())
    _root["config"]["speedP"] = std::stod(it->second);
  else
    cl_args["speedP"] = "12";

  //Angle Parameter
  if ((it = cl_args.find("angleA")) != cl_args.end())
    _root["config"]["angleA"] = std::stod(it->second);
  else
    cl_args["angleA"] = "0";

  if ((it = cl_args.find("angleB")) != cl_args.end())
    _root["config"]["angleB"] = std::stod(it->second);
  else
    cl_args["angleB"] = "0";

  if ((it = cl_args.find("angleP")) != cl_args.end())
    _root["config"]["angleP"] = std::stod(it->second);
  else
    cl_args["angleB"] = "0";

  // Creating a log file
  _trial_logger.start_new_file(cl_args["xp_path"], "Trial_" + std::to_string(_trial_id) + ".json");
  _generational_data = Json::Value(Json::arrayValue);

  // JSON style
  _root["config"]["trialName"] = trial_name;
  _root["config"]["randomSeed"] = seed;
  _root["config"]["numberOfGenerations"] = _max_generation_num;
  _root["config"]["numberOfTimesteps"] = _max_step_num;
  _root["config"]["populationSize"] = _population_size;
  _root["config"]["bracketRatio"] = bracket_ratio;
  _root["config"]["mutationRate"] = mutation_rate;

  // Instantiating a trial
  if (trial_name == "SiblingParentNeuronTrial"){
    cl_args["angleA"] = "0";
    cl_args["angleB"] = "0";
    cl_args["angleP"] = "0";
    _trial = new nevil::sibling_parent_trial(cl_args);
  }
  else if (trial_name == "SiblingParentAsymTrial")
  {
    cl_args["sn"] = "false";
    _trial = new nevil::sibling_parent_trial(cl_args);
  }
  else if (trial_name == "SiblingParentDetectionTrial")
  {
    cl_args["sn"] = "false";
    _trial = new nevil::sibling_parent_trial(cl_args); // Change this
  }
  else
  {
    printf("Trial '%s' is not defined.\nTerminating...\n", trial_name.c_str());
    exit(1);
  }

  _current_generation = 0;
  _current_individual = 0;
  _current_step = 0;
  printf("-Trial %d: starting\n", _trial_id);
  printf("-Trial %d: running generation %d\n", _trial_id, _current_generation);
}

nevil::trial_controller::~trial_controller()
{
  delete _trial;
}

Enki::World *nevil::trial_controller::get_trial_world()
{
  return _trial->get_trial_world();
}

bool nevil::trial_controller::run()
{
  if (_current_generation < _max_generation_num)
  {
    if (_current_individual < _population_size)
    {
      if (_current_step == 0 && _current_individual != _population_size)
        _trial->reset();

      if (_current_step < _max_step_num)
      {
        _trial->update();
        ++_current_step;
      }
      else
      {
        ++_current_individual;
        _current_step = 0;
      }
    }
    else
    {
      _evaluate();
      ++_current_generation;
      _current_individual = 0;
      _current_step = 0;
      printf("-Trial %d: running generation %d\n", _trial_id, _current_generation);
    }
    return true;
  }

  _end();
  return false;
}

void nevil::trial_controller::_evaluate()
{
  Json::Value data;
  data["generationNumber"] = _current_generation;
  data["individualList"] = _trial->get_generation_data();

  _trial->epoch();

  data["bestIndividual"] = _trial->get_best_individual().json();
  _generational_data.append(data);
}

void nevil::trial_controller::_end()
{
  printf("-Trial %d: finished\n", _trial_id);
  _root["generationalData"] = _generational_data;
  _trial_logger.write(_root);
  _trial_logger.close_file();
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * main_inteface.cpp : Main interface
 ****************************************************************************
 * Copyright (C) 2006 the VideoLAN team
 * $Id$
 *
 * Authors: Clément Stenac <zorglub@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/

#include "qt4.hpp"
#include <QEvent>
#include "dialogs_provider.hpp"
#include "dialogs/playlist.hpp"
#include "dialogs/prefs_dialog.hpp"
#include "dialogs/streaminfo.hpp"
#include "dialogs/messages.hpp"
#include <QApplication>
#include <QSignalMapper>
#include "menus.hpp"
#include <vlc_intf_strings.h>

DialogsProvider* DialogsProvider::instance = NULL;

DialogsProvider::DialogsProvider( intf_thread_t *_p_intf ) :
                                      QObject( NULL ), p_intf( _p_intf )
{
//    idle_timer = new QTimer( this );
//    idle_timer->start( 0 );

    fixed_timer = new QTimer( this );
    fixed_timer->start( 150 /* milliseconds */ );

    menusMapper = new QSignalMapper();
    connect( menusMapper, SIGNAL( mapped(QObject *) ), this,
            SLOT(menuAction( QObject *)) );

    menusUpdateMapper = new QSignalMapper();
    connect( menusUpdateMapper, SIGNAL( mapped(QObject *) ), this,
            SLOT(menuUpdateAction( QObject *)) );
}

DialogsProvider::~DialogsProvider()
{
}
void DialogsProvider::customEvent( QEvent *event )
{
    if( event->type() == DialogEvent_Type )
    {
        DialogEvent *de = static_cast<DialogEvent*>(event);
        switch( de->i_dialog )
        {
            case INTF_DIALOG_FILE:
            case INTF_DIALOG_DISC:
            case INTF_DIALOG_NET:
            case INTF_DIALOG_CAPTURE:
                openDialog( de->i_dialog ); break;
            case INTF_DIALOG_PLAYLIST:
                playlistDialog(); break;
            case INTF_DIALOG_MESSAGES:
                messagesDialog(); break;
            case INTF_DIALOG_PREFS:
               prefsDialog(); break;
            case INTF_DIALOG_POPUPMENU:
            case INTF_DIALOG_AUDIOPOPUPMENU:
            case INTF_DIALOG_VIDEOPOPUPMENU:
            case INTF_DIALOG_MISCPOPUPMENU:
               popupMenu( de->i_dialog ); break;
            case INTF_DIALOG_FILEINFO:
               streaminfoDialog(); break;
            case INTF_DIALOG_INTERACTION:
               doInteraction( de->p_arg ); break;
            case INTF_DIALOG_VLM:
            case INTF_DIALOG_BOOKMARKS:
               bookmarksDialog(); break;
            case INTF_DIALOG_WIZARD:
            default:
               msg_Warn( p_intf, "unimplemented dialog\n" );
        }
    }
}

void DialogsProvider::playlistDialog()
{
    PlaylistDialog::getInstance( p_intf )->toggleVisible();
}

void DialogsProvider::openDialog()
{
    openDialog( 0 );
}
void DialogsProvider::PLAppendDialog()
{
}
void DialogsProvider::MLAppendDialog()
{
}
void DialogsProvider::openDialog( int i_dialog )
{
}

void DialogsProvider::doInteraction( intf_dialog_args_t *p_arg )
{
    InteractionDialog *qdialog;
    interaction_dialog_t *p_dialog = p_arg->p_dialog;
    switch( p_dialog->i_action )
    {
    case INTERACT_NEW:
        qdialog = new InteractionDialog( p_intf, p_dialog );
        p_dialog->p_private = (void*)qdialog;
        qdialog->show();
        break;
    case INTERACT_UPDATE:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        if( qdialog)
            qdialog->Update();
        break;
    case INTERACT_HIDE:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        if( qdialog )
            qdialog->hide();
        p_dialog->i_status = HIDDEN_DIALOG;
        break;
    case INTERACT_DESTROY:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        delete qdialog;
        p_dialog->i_status = DESTROYED_DIALOG;
        break;
    }
}

void DialogsProvider::quit()
{
    p_intf->b_die = VLC_TRUE;
    QApplication::quit();
}

void DialogsProvider::streaminfoDialog()
{
    StreamInfoDialog::getInstance( p_intf, true )->toggleVisible();
}

void DialogsProvider::streamingDialog()
{
}

void DialogsProvider::prefsDialog()
{
    PrefsDialog::getInstance( p_intf )->toggleVisible();
}

void DialogsProvider::messagesDialog()
{
    MessagesDialog::getInstance( p_intf, true )->toggleVisible();
}

void DialogsProvider::menuAction( QObject *data )
{
    QVLCMenu::DoAction( p_intf, data );
}

void DialogsProvider::menuUpdateAction( QObject *data )
{
    MenuFunc * f = qobject_cast<MenuFunc *>(data);
    f->doFunc( p_intf );
}

void DialogsProvider::simplePLAppendDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    foreach( file, files )
    {
        const char * psz_utf8 = file.toUtf8().data();
        playlist_PlaylistAdd( THEPL, psz_utf8, psz_utf8,
                     PLAYLIST_APPEND | PLAYLIST_PREPARSE, PLAYLIST_END );
    }
}

void DialogsProvider::simpleMLAppendDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    foreach( file, files )
    {
        const char * psz_utf8 = file.toUtf8().data();
        playlist_MLAdd( THEPL, psz_utf8, psz_utf8,
                        PLAYLIST_APPEND | PLAYLIST_PREPARSE, PLAYLIST_END );
    }
}

void DialogsProvider::simpleOpenDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    for( size_t i = 0 ; i< files.size(); i++ )
    {
        const char * psz_utf8 = files[i].toUtf8().data();
        /* Play the first one, parse and enqueue the other ones */
        playlist_PlaylistAdd( THEPL, psz_utf8, psz_utf8,
                     PLAYLIST_APPEND | (i ? 0 : PLAYLIST_GO) |
                     ( i ? PLAYLIST_PREPARSE : 0 ),
                     PLAYLIST_END );
    }
}

QStringList DialogsProvider::showSimpleOpen()
{
    QString FileTypes;
    FileTypes = "Video Files ( ";
    FileTypes += EXTENSIONS_VIDEO;
    FileTypes += ");; Sound Files ( ";
    FileTypes += EXTENSIONS_AUDIO;
    FileTypes += ");; PlayList Files ( ";
    FileTypes += EXTENSIONS_PLAYLIST;
    FileTypes += ");; All Files (*.*) " ;
    FileTypes.replace(QString(";*"), QString(" *"));
    return QFileDialog::getOpenFileNames( NULL, qfu(I_POP_SEL_FILES ),
                    p_intf->p_vlc->psz_homedir, FileTypes );
}

void DialogsProvider::bookmarksDialog()
{
}

void DialogsProvider::popupMenu( int i_dialog )
{

}
<commit_msg>Fix "All files"<commit_after>/*****************************************************************************
 * main_inteface.cpp : Main interface
 ****************************************************************************
 * Copyright (C) 2006 the VideoLAN team
 * $Id$
 *
 * Authors: Clément Stenac <zorglub@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/

#include "qt4.hpp"
#include <QEvent>
#include "dialogs_provider.hpp"
#include "dialogs/playlist.hpp"
#include "dialogs/prefs_dialog.hpp"
#include "dialogs/streaminfo.hpp"
#include "dialogs/messages.hpp"
#include <QApplication>
#include <QSignalMapper>
#include "menus.hpp"
#include <vlc_intf_strings.h>

DialogsProvider* DialogsProvider::instance = NULL;

DialogsProvider::DialogsProvider( intf_thread_t *_p_intf ) :
                                      QObject( NULL ), p_intf( _p_intf )
{
//    idle_timer = new QTimer( this );
//    idle_timer->start( 0 );

    fixed_timer = new QTimer( this );
    fixed_timer->start( 150 /* milliseconds */ );

    menusMapper = new QSignalMapper();
    connect( menusMapper, SIGNAL( mapped(QObject *) ), this,
            SLOT(menuAction( QObject *)) );

    menusUpdateMapper = new QSignalMapper();
    connect( menusUpdateMapper, SIGNAL( mapped(QObject *) ), this,
            SLOT(menuUpdateAction( QObject *)) );
}

DialogsProvider::~DialogsProvider()
{
}
void DialogsProvider::customEvent( QEvent *event )
{
    if( event->type() == DialogEvent_Type )
    {
        DialogEvent *de = static_cast<DialogEvent*>(event);
        switch( de->i_dialog )
        {
            case INTF_DIALOG_FILE:
            case INTF_DIALOG_DISC:
            case INTF_DIALOG_NET:
            case INTF_DIALOG_CAPTURE:
                openDialog( de->i_dialog ); break;
            case INTF_DIALOG_PLAYLIST:
                playlistDialog(); break;
            case INTF_DIALOG_MESSAGES:
                messagesDialog(); break;
            case INTF_DIALOG_PREFS:
               prefsDialog(); break;
            case INTF_DIALOG_POPUPMENU:
            case INTF_DIALOG_AUDIOPOPUPMENU:
            case INTF_DIALOG_VIDEOPOPUPMENU:
            case INTF_DIALOG_MISCPOPUPMENU:
               popupMenu( de->i_dialog ); break;
            case INTF_DIALOG_FILEINFO:
               streaminfoDialog(); break;
            case INTF_DIALOG_INTERACTION:
               doInteraction( de->p_arg ); break;
            case INTF_DIALOG_VLM:
            case INTF_DIALOG_BOOKMARKS:
               bookmarksDialog(); break;
            case INTF_DIALOG_WIZARD:
            default:
               msg_Warn( p_intf, "unimplemented dialog\n" );
        }
    }
}

void DialogsProvider::playlistDialog()
{
    PlaylistDialog::getInstance( p_intf )->toggleVisible();
}

void DialogsProvider::openDialog()
{
    openDialog( 0 );
}
void DialogsProvider::PLAppendDialog()
{
}
void DialogsProvider::MLAppendDialog()
{
}
void DialogsProvider::openDialog( int i_dialog )
{
}

void DialogsProvider::doInteraction( intf_dialog_args_t *p_arg )
{
    InteractionDialog *qdialog;
    interaction_dialog_t *p_dialog = p_arg->p_dialog;
    switch( p_dialog->i_action )
    {
    case INTERACT_NEW:
        qdialog = new InteractionDialog( p_intf, p_dialog );
        p_dialog->p_private = (void*)qdialog;
        qdialog->show();
        break;
    case INTERACT_UPDATE:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        if( qdialog)
            qdialog->Update();
        break;
    case INTERACT_HIDE:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        if( qdialog )
            qdialog->hide();
        p_dialog->i_status = HIDDEN_DIALOG;
        break;
    case INTERACT_DESTROY:
        qdialog = (InteractionDialog*)(p_dialog->p_private);
        delete qdialog;
        p_dialog->i_status = DESTROYED_DIALOG;
        break;
    }
}

void DialogsProvider::quit()
{
    p_intf->b_die = VLC_TRUE;
    QApplication::quit();
}

void DialogsProvider::streaminfoDialog()
{
    StreamInfoDialog::getInstance( p_intf, true )->toggleVisible();
}

void DialogsProvider::streamingDialog()
{
}

void DialogsProvider::prefsDialog()
{
    PrefsDialog::getInstance( p_intf )->toggleVisible();
}

void DialogsProvider::messagesDialog()
{
    MessagesDialog::getInstance( p_intf, true )->toggleVisible();
}

void DialogsProvider::menuAction( QObject *data )
{
    QVLCMenu::DoAction( p_intf, data );
}

void DialogsProvider::menuUpdateAction( QObject *data )
{
    MenuFunc * f = qobject_cast<MenuFunc *>(data);
    f->doFunc( p_intf );
}

void DialogsProvider::simplePLAppendDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    foreach( file, files )
    {
        const char * psz_utf8 = file.toUtf8().data();
        playlist_PlaylistAdd( THEPL, psz_utf8, psz_utf8,
                     PLAYLIST_APPEND | PLAYLIST_PREPARSE, PLAYLIST_END );
    }
}

void DialogsProvider::simpleMLAppendDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    foreach( file, files )
    {
        const char * psz_utf8 = file.toUtf8().data();
        playlist_MLAdd( THEPL, psz_utf8, psz_utf8,
                        PLAYLIST_APPEND | PLAYLIST_PREPARSE, PLAYLIST_END );
    }
}

void DialogsProvider::simpleOpenDialog()
{
    QStringList files = showSimpleOpen();
    QString file;
    for( size_t i = 0 ; i< files.size(); i++ )
    {
        const char * psz_utf8 = files[i].toUtf8().data();
        /* Play the first one, parse and enqueue the other ones */
        playlist_PlaylistAdd( THEPL, psz_utf8, psz_utf8,
                     PLAYLIST_APPEND | (i ? 0 : PLAYLIST_GO) |
                     ( i ? PLAYLIST_PREPARSE : 0 ),
                     PLAYLIST_END );
    }
}

QStringList DialogsProvider::showSimpleOpen()
{
    QString FileTypes;
    FileTypes = "Video Files ( ";
    FileTypes += EXTENSIONS_VIDEO;
    FileTypes += ");; Sound Files ( ";
    FileTypes += EXTENSIONS_AUDIO;
    FileTypes += ");; PlayList Files ( ";
    FileTypes += EXTENSIONS_PLAYLIST;
    FileTypes += ");; All Files (*.*)" ;
    FileTypes.replace(QString(";*"), QString(" *"));
    return QFileDialog::getOpenFileNames( NULL, qfu(I_POP_SEL_FILES ),
                    p_intf->p_vlc->psz_homedir, FileTypes );
}

void DialogsProvider::bookmarksDialog()
{
}

void DialogsProvider::popupMenu( int i_dialog )
{

}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "command_args_parser.h"

#include <string.h>
#include <iostream>

// Windows Specific
#ifdef _WIN32
#include "getopt.h"
#include "windows.h"
#else
#include <unistd.h>
#endif

#include <core/graph/constants.h>
#include <core/framework/path_lib.h>
#include <core/optimizer/graph_transformer_level.h>

#include "test_configuration.h"

namespace onnxruntime {
namespace perftest {

/*static*/ void CommandLineParser::ShowUsage() {
  printf(
      "perf_test [options...] model_path result_file\n"
      "Options:\n"
      "\t-m [test_mode]: Specifies the test mode. Value could be 'duration' or 'times'.\n"
      "\t\tProvide 'duration' to run the test for a fix duration, and 'times' to repeated for a certain times. "
      "\t-M: Disable memory pattern.\n"
      "\t-A: Disable memory arena\n"
      "\t-c [parallel runs]: Specifies the (max) number of runs to invoke simultaneously. Default:1.\n"
      "\t-e [cpu|cuda|mkldnn|tensorrt|ngraph]: Specifies the provider 'cpu','cuda','mkldnn','tensorrt', 'ngraph' or 'openvino'. "
      "Default:'cpu'.\n"
      "\t-b [tf|ort]: backend to use. Default:ort\n"
      "\t-r [repeated_times]: Specifies the repeated times if running in 'times' test mode.Default:1000.\n"
      "\t-t [seconds_to_run]: Specifies the seconds to run for 'duration' mode. Default:600.\n"
      "\t-p [profile_file]: Specifies the profile name to enable profiling and dump the profile data to the file.\n"
      "\t-s: Show statistics result, like P75, P90.\n"
      "\t-v: Show verbose information.\n"
      "\t-x [thread_size]: Session thread pool size.\n"
      "\t-P: Use parallel executor instead of sequential executor.\n"
      "\t-o [optimization level]: 0: disable optimization, 1: basic optimization, 2: extended optimization, 3: extended+layout optimization. \n"
      "\t-h: help\n");
}

/*static*/ bool CommandLineParser::ParseArguments(PerformanceTestConfig& test_config, int argc, ORTCHAR_T* argv[]) {
  int ch;
  while ((ch = getopt(argc, argv, ORT_TSTR("b:m:e:r:t:p:x:c:o:AMPvhs"))) != -1) {
    switch (ch) {
      case 'm':
        if (!CompareCString(optarg, ORT_TSTR("duration"))) {
          test_config.run_config.test_mode = TestMode::kFixDurationMode;
        } else if (!CompareCString(optarg, ORT_TSTR("times"))) {
          test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode;
        } else {
          return false;
        }
        break;
      case 'b':
        test_config.backend = optarg;
        break;
      case 'p':
        test_config.run_config.profile_file = optarg;
        break;
      case 'M':
        test_config.run_config.enable_memory_pattern = false;
        break;
      case 'A':
        test_config.run_config.enable_cpu_mem_arena = false;
        break;
      case 'e':
        if (!CompareCString(optarg, ORT_TSTR("cpu"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kCpuExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("cuda"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kCudaExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("mkldnn"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kMklDnnExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("ngraph"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kNGraphExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("brainslice"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kBrainSliceExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("tensorrt"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kTensorrtExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("openvino"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kOpenVINOExecutionProvider;
        } else {
          return false;
        }
        break;
      case 'r':
        test_config.run_config.repeated_times = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.repeated_times <= 0) {
          return false;
        }
        test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode;
        break;
      case 't':
        test_config.run_config.duration_in_seconds = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.repeated_times <= 0) {
          return false;
        }
        test_config.run_config.test_mode = TestMode::kFixDurationMode;
        break;
      case 's':
        test_config.run_config.f_dump_statistics = true;
        break;
      case 'v':
        test_config.run_config.f_verbose = true;
        break;
      case 'x':
        test_config.run_config.session_thread_pool_size = static_cast<int>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.session_thread_pool_size <= 0) {
          return false;
        }
        break;
      case 'P':
        test_config.run_config.enable_sequential_execution = false;
        break;
      case 'c':
        test_config.run_config.concurrent_session_runs =
            static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.concurrent_session_runs <= 0) {
          return false;
        }
        break;
      case 'o':
        test_config.run_config.optimization_level = static_cast<uint32_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.optimization_level >= static_cast<uint32_t>(TransformerLevel::MaxTransformerLevel)) {
          return false;
        }
        break;
      case '?':
      case 'h':
      default:
        return false;
    }
  }

  // parse model_path and result_file_path
  argc -= optind;
  argv += optind;
  if (argc != 2) return false;

  test_config.model_info.model_file_path = argv[0];
  test_config.model_info.result_file_path = argv[1];

  return true;
}

}  // namespace perftest
}  // namespace onnxruntime
<commit_msg>Add missing 'openvino' option in perftest Usage message (#1367)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "command_args_parser.h"

#include <string.h>
#include <iostream>

// Windows Specific
#ifdef _WIN32
#include "getopt.h"
#include "windows.h"
#else
#include <unistd.h>
#endif

#include <core/graph/constants.h>
#include <core/framework/path_lib.h>
#include <core/optimizer/graph_transformer_level.h>

#include "test_configuration.h"

namespace onnxruntime {
namespace perftest {

/*static*/ void CommandLineParser::ShowUsage() {
  printf(
      "perf_test [options...] model_path result_file\n"
      "Options:\n"
      "\t-m [test_mode]: Specifies the test mode. Value could be 'duration' or 'times'.\n"
      "\t\tProvide 'duration' to run the test for a fix duration, and 'times' to repeated for a certain times. "
      "\t-M: Disable memory pattern.\n"
      "\t-A: Disable memory arena\n"
      "\t-c [parallel runs]: Specifies the (max) number of runs to invoke simultaneously. Default:1.\n"
      "\t-e [cpu|cuda|mkldnn|tensorrt|ngraph|openvino]: Specifies the provider 'cpu','cuda','mkldnn','tensorrt', 'ngraph' or 'openvino'. "
      "Default:'cpu'.\n"
      "\t-b [tf|ort]: backend to use. Default:ort\n"
      "\t-r [repeated_times]: Specifies the repeated times if running in 'times' test mode.Default:1000.\n"
      "\t-t [seconds_to_run]: Specifies the seconds to run for 'duration' mode. Default:600.\n"
      "\t-p [profile_file]: Specifies the profile name to enable profiling and dump the profile data to the file.\n"
      "\t-s: Show statistics result, like P75, P90.\n"
      "\t-v: Show verbose information.\n"
      "\t-x [thread_size]: Session thread pool size.\n"
      "\t-P: Use parallel executor instead of sequential executor.\n"
      "\t-o [optimization level]: 0: disable optimization, 1: basic optimization, 2: extended optimization, 3: extended+layout optimization. \n"
      "\t-h: help\n");
}

/*static*/ bool CommandLineParser::ParseArguments(PerformanceTestConfig& test_config, int argc, ORTCHAR_T* argv[]) {
  int ch;
  while ((ch = getopt(argc, argv, ORT_TSTR("b:m:e:r:t:p:x:c:o:AMPvhs"))) != -1) {
    switch (ch) {
      case 'm':
        if (!CompareCString(optarg, ORT_TSTR("duration"))) {
          test_config.run_config.test_mode = TestMode::kFixDurationMode;
        } else if (!CompareCString(optarg, ORT_TSTR("times"))) {
          test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode;
        } else {
          return false;
        }
        break;
      case 'b':
        test_config.backend = optarg;
        break;
      case 'p':
        test_config.run_config.profile_file = optarg;
        break;
      case 'M':
        test_config.run_config.enable_memory_pattern = false;
        break;
      case 'A':
        test_config.run_config.enable_cpu_mem_arena = false;
        break;
      case 'e':
        if (!CompareCString(optarg, ORT_TSTR("cpu"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kCpuExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("cuda"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kCudaExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("mkldnn"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kMklDnnExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("ngraph"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kNGraphExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("brainslice"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kBrainSliceExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("tensorrt"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kTensorrtExecutionProvider;
        } else if (!CompareCString(optarg, ORT_TSTR("openvino"))) {
          test_config.machine_config.provider_type_name = onnxruntime::kOpenVINOExecutionProvider;
        } else {
          return false;
        }
        break;
      case 'r':
        test_config.run_config.repeated_times = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.repeated_times <= 0) {
          return false;
        }
        test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode;
        break;
      case 't':
        test_config.run_config.duration_in_seconds = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.repeated_times <= 0) {
          return false;
        }
        test_config.run_config.test_mode = TestMode::kFixDurationMode;
        break;
      case 's':
        test_config.run_config.f_dump_statistics = true;
        break;
      case 'v':
        test_config.run_config.f_verbose = true;
        break;
      case 'x':
        test_config.run_config.session_thread_pool_size = static_cast<int>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.session_thread_pool_size <= 0) {
          return false;
        }
        break;
      case 'P':
        test_config.run_config.enable_sequential_execution = false;
        break;
      case 'c':
        test_config.run_config.concurrent_session_runs =
            static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.concurrent_session_runs <= 0) {
          return false;
        }
        break;
      case 'o':
        test_config.run_config.optimization_level = static_cast<uint32_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr));
        if (test_config.run_config.optimization_level >= static_cast<uint32_t>(TransformerLevel::MaxTransformerLevel)) {
          return false;
        }
        break;
      case '?':
      case 'h':
      default:
        return false;
    }
  }

  // parse model_path and result_file_path
  argc -= optind;
  argv += optind;
  if (argc != 2) return false;

  test_config.model_info.model_file_path = argv[0];
  test_config.model_info.result_file_path = argv[1];

  return true;
}

}  // namespace perftest
}  // namespace onnxruntime
<|endoftext|>