<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "TelepathyIMModule.h"
#include "CommunicationService.h"
#include "CommunicationUI/MasterWidget.h"
#include "CommunicationUI/OpenSimChatWidget.h"
#include "Test.h"
//#include "OpensimIM/ConnectionProvider.h"
//#include "OpensimIM/ChatController.h"
#include "TelepathyIM/ConnectionProvider.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "WorldStream.h"
#include "Interfaces/ProtocolModuleInterface.h"

#include <RexLogicModule.h>
#include <UiModule.h>
#include <Inworld/InworldSceneController.h>
#include <Inworld/View/UiProxyWidget.h>

#include "MemoryLeakCheck.h"

namespace Communication
{
    TelepathyIMModule::TelepathyIMModule()
        : ModuleInterfaceImpl(type_static_),
          im_ui_(0),
          im_ui_proxy_widget_(0),
          communication_service_(0),
          test_(0),
          event_category_networkstate_(0),
          event_category_framework_(0),
          os_chat_controller_(0)
    {
    }

    TelepathyIMModule::~TelepathyIMModule()
    {
    }

    void TelepathyIMModule::Load()
    {
    }

    void TelepathyIMModule::Unload()
    {
    }

    void TelepathyIMModule::Initialize()
    {
        event_category_framework_ = framework_->GetEventManager()->QueryEventCategory("Framework");
    }

    void TelepathyIMModule::PostInitialize()
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        CommunicationService::CreateInstance(framework_);
        communication_service_ = CommunicationService::GetInstance();
        if (communication_service_ == 0)
        {
            LogError("Cannot initialize CommunicationService object");
            return;
        }

        connect(communication_service_, SIGNAL( NewProtocolSupported(QString &) ),
                SLOT( OnNewProtocol(QString &) ));
        connect(communication_service_, SIGNAL( ProtocolSupportEnded(QString &) ),
                SLOT( OnProtocolSupportEnded(QString &) ));
        connect(communication_service_, SIGNAL( ConnectionOpened(Communication::ConnectionInterface*) ),
                SLOT( OnConnectionOpened(Communication::ConnectionInterface*) ));
        connect(communication_service_, SIGNAL( ConnectionClosed(Communication::ConnectionInterface*) ),
                SLOT( OnConnectionClosed(Communication::ConnectionInterface*) ));

        //OpensimIM::ConnectionProvider* opensim = new OpensimIM::ConnectionProvider(framework_);
        //communication_service_->RegisterConnectionProvider(opensim);

        TelepathyIM::ConnectionProvider* telepathy = new TelepathyIM::ConnectionProvider(framework_);
        communication_service_->RegisterConnectionProvider(telepathy);

        test_ = new CommunicationTest::Test(framework_);

        QStringList protocols = communication_service_->GetSupportedProtocols();
        if (protocols.size() == 0)
            LogInfo("No IM protocols supported");
        else
        {
            for (QStringList::iterator i = protocols.begin(); i != protocols.end(); ++i)
            {
                QString message = "IM protocol support for: ";
                message.append(*i);
                LogInfo( message.toStdString() );
            }
        }
    }

    void TelepathyIMModule::Uninitialize()
    {
        SAFE_DELETE(im_ui_);
        SAFE_DELETE(os_chat_controller_);
        SAFE_DELETE(test_);

        CommunicationService::CleanUp();
        communication_service_ = NULL;
    }

    void TelepathyIMModule::Update(f64 frametime)
    {

    }

    bool TelepathyIMModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data)
    {
        event_category_networkstate_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");

        if (category_id == event_category_networkstate_)
        {
            if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
            {
                boost::weak_ptr<ProtocolUtilities::ProtocolModuleInterface> current_protocol_module = framework_->GetModuleManager()->GetModule<RexLogic::RexLogicModule>(Foundation::Module::MT_WorldLogic).lock().get()->GetServerConnection()->GetCurrentProtocolModuleWeakPointer();
                if (current_protocol_module.lock().get())
                {
                    ProtocolUtilities::ClientParameters client_params = current_protocol_module.lock()->GetClientParameters();
//                    os_chat_controller_ = new OpensimIM::ChatController(client_params);
                }
            }
            else if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED || event_id == ProtocolUtilities::Events::EVENT_CONNECTION_FAILED)
            {
                SAFE_DELETE(os_chat_controller_);
            }
        }

        if (communication_service_)
            return dynamic_cast<CommunicationService*>( communication_service_ )->HandleEvent(category_id, event_id, data);
        return false;
    }

    void TelepathyIMModule::OnNewProtocol(QString &protocol)
    {
        if (protocol == "jabber")
        {
            im_ui_ = new CommunicationUI::MasterWidget(framework_);
            AddWidgetToUi("IM");
        }
    }

    void TelepathyIMModule::OnProtocolSupportEnded(QString &protocol)
    {
        if (protocol == "jabber")
        {
            SAFE_DELETE(im_ui_);
            return;
        }
    }

    void TelepathyIMModule::OnConnectionOpened(Communication::ConnectionInterface* connection)
    {
    }

    void TelepathyIMModule::OnConnectionClosed(Communication::ConnectionInterface* connection)
    {
    }

    void TelepathyIMModule::AddWidgetToUi(const QString &name)
    {
        //! @todo Define UIServiceInterface...
        boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices).lock();
        if (ui_module.get())
        {
            if (name == "IM")
            {
                UiServices::UiWidgetProperties widget_properties(name, UiServices::SceneWidget);
                im_ui_proxy_widget_ = ui_module->GetInworldSceneController()->AddWidgetToScene(im_ui_, widget_properties);
                if (im_ui_proxy_widget_)
                    ui_module->GetInworldSceneController()->SetImWidget(im_ui_proxy_widget_);
            }
        }
    }

    void TelepathyIMModule::RemoveProxyWidgetFromUi(UiServices::UiProxyWidget *proxy_widget)
    {
        boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices).lock();
        if (ui_module.get())
            ui_module->GetInworldSceneController()->RemoveProxyWidgetFromScene(proxy_widget);
    }
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

using namespace Communication;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(TelepathyIMModule)
POCO_END_MANIFEST
<commit_msg>*Fix couple of C4150 warnings (deletion of pointer to incomplete type) due to some commented out creation of objects<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "TelepathyIMModule.h"
#include "CommunicationService.h"
#include "CommunicationUI/MasterWidget.h"
#include "CommunicationUI/OpenSimChatWidget.h"
#include "Test.h"
//#include "OpensimIM/ConnectionProvider.h"
//#include "OpensimIM/ChatController.h"
#include "TelepathyIM/ConnectionProvider.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "WorldStream.h"
#include "Interfaces/ProtocolModuleInterface.h"

#include <RexLogicModule.h>
#include <UiModule.h>
#include <Inworld/InworldSceneController.h>
#include <Inworld/View/UiProxyWidget.h>

#include "MemoryLeakCheck.h"

namespace Communication
{
    TelepathyIMModule::TelepathyIMModule()
        : ModuleInterfaceImpl(type_static_),
          im_ui_(0),
          im_ui_proxy_widget_(0),
          communication_service_(0),
          test_(0),
          event_category_networkstate_(0),
          event_category_framework_(0),
          os_chat_controller_(0)
    {
    }

    TelepathyIMModule::~TelepathyIMModule()
    {
    }

    void TelepathyIMModule::Load()
    {
    }

    void TelepathyIMModule::Unload()
    {
    }

    void TelepathyIMModule::Initialize()
    {
        event_category_framework_ = framework_->GetEventManager()->QueryEventCategory("Framework");
    }

    void TelepathyIMModule::PostInitialize()
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        CommunicationService::CreateInstance(framework_);
        communication_service_ = CommunicationService::GetInstance();
        if (communication_service_ == 0)
        {
            LogError("Cannot initialize CommunicationService object");
            return;
        }

        connect(communication_service_, SIGNAL( NewProtocolSupported(QString &) ),
                SLOT( OnNewProtocol(QString &) ));
        connect(communication_service_, SIGNAL( ProtocolSupportEnded(QString &) ),
                SLOT( OnProtocolSupportEnded(QString &) ));
        connect(communication_service_, SIGNAL( ConnectionOpened(Communication::ConnectionInterface*) ),
                SLOT( OnConnectionOpened(Communication::ConnectionInterface*) ));
        connect(communication_service_, SIGNAL( ConnectionClosed(Communication::ConnectionInterface*) ),
                SLOT( OnConnectionClosed(Communication::ConnectionInterface*) ));

        //OpensimIM::ConnectionProvider* opensim = new OpensimIM::ConnectionProvider(framework_);
        //communication_service_->RegisterConnectionProvider(opensim);

        TelepathyIM::ConnectionProvider* telepathy = new TelepathyIM::ConnectionProvider(framework_);
        communication_service_->RegisterConnectionProvider(telepathy);

        test_ = new CommunicationTest::Test(framework_);

        QStringList protocols = communication_service_->GetSupportedProtocols();
        if (protocols.size() == 0)
            LogInfo("No IM protocols supported");
        else
        {
            for (QStringList::iterator i = protocols.begin(); i != protocols.end(); ++i)
            {
                QString message = "IM protocol support for: ";
                message.append(*i);
                LogInfo( message.toStdString() );
            }
        }
    }

    void TelepathyIMModule::Uninitialize()
    {
//        SAFE_DELETE(im_ui_);
//        SAFE_DELETE(os_chat_controller_);
        SAFE_DELETE(test_);

        CommunicationService::CleanUp();
        communication_service_ = NULL;
    }

    void TelepathyIMModule::Update(f64 frametime)
    {

    }

    bool TelepathyIMModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data)
    {
        event_category_networkstate_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");

        if (category_id == event_category_networkstate_)
        {
            if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
            {
                boost::weak_ptr<ProtocolUtilities::ProtocolModuleInterface> current_protocol_module = framework_->GetModuleManager()->GetModule<RexLogic::RexLogicModule>(Foundation::Module::MT_WorldLogic).lock().get()->GetServerConnection()->GetCurrentProtocolModuleWeakPointer();
                if (current_protocol_module.lock().get())
                {
                    ProtocolUtilities::ClientParameters client_params = current_protocol_module.lock()->GetClientParameters();
//                    os_chat_controller_ = new OpensimIM::ChatController(client_params);
                }
            }
            else if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED || event_id == ProtocolUtilities::Events::EVENT_CONNECTION_FAILED)
            {
//                SAFE_DELETE(os_chat_controller_);
            }
        }

        if (communication_service_)
            return static_cast<CommunicationService*>( communication_service_ )->HandleEvent(category_id, event_id, data);
        return false;
    }

    void TelepathyIMModule::OnNewProtocol(QString &protocol)
    {
        if (protocol == "jabber")
        {
            im_ui_ = new CommunicationUI::MasterWidget(framework_);
            AddWidgetToUi("IM");
        }
    }

    void TelepathyIMModule::OnProtocolSupportEnded(QString &protocol)
    {
        if (protocol == "jabber")
        {
            SAFE_DELETE(im_ui_);
            return;
        }
    }

    void TelepathyIMModule::OnConnectionOpened(Communication::ConnectionInterface* connection)
    {
    }

    void TelepathyIMModule::OnConnectionClosed(Communication::ConnectionInterface* connection)
    {
    }

    void TelepathyIMModule::AddWidgetToUi(const QString &name)
    {
        //! @todo Define UIServiceInterface...
        boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices).lock();
        if (ui_module.get())
        {
            if (name == "IM")
            {
                UiServices::UiWidgetProperties widget_properties(name, UiServices::SceneWidget);
                im_ui_proxy_widget_ = ui_module->GetInworldSceneController()->AddWidgetToScene(im_ui_, widget_properties);
                if (im_ui_proxy_widget_)
                    ui_module->GetInworldSceneController()->SetImWidget(im_ui_proxy_widget_);
            }
        }
    }

    void TelepathyIMModule::RemoveProxyWidgetFromUi(UiServices::UiProxyWidget *proxy_widget)
    {
        boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices).lock();
        if (ui_module.get())
            ui_module->GetInworldSceneController()->RemoveProxyWidgetFromScene(proxy_widget);
    }
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

using namespace Communication;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(TelepathyIMModule)
POCO_END_MANIFEST
<|endoftext|>


<commit_before>//#include "TestUtils.h"
//#include "gtest/gtest.h"
//
//#include <Tasks/TaskMeta.h>
//#include <Tasks/TaskSerializer.h>
//
//#include <Flatbuffers/generated/FlatData_generated.h>
//
//using namespace Hearthstonepp;
//
//TEST(TaskMeta, TraitConstructors)
//{
//    std::random_device rd;
//    std::default_random_engine gen(rd());
//
//    int sizeTaskID = static_cast<int>(TaskID::_size());
//    int sizeMetaData = static_cast<int>(MetaData::GAME_END);
//
//    TaskID randID = TaskID::_from_integral(gen() % sizeTaskID);
//    MetaData randMeta = static_cast<MetaData>(gen() % sizeMetaData);
//    BYTE randUser = gen() % 2;
//
//    // Empty Trait Test
//    TaskMetaTrait empty;
//    EXPECT_EQ(empty.id, +TaskID::INVALID);
//    EXPECT_EQ(empty.status, MetaData::INVALID);
//    EXPECT_EQ(empty.userID, TaskMetaTrait::USER_INVALID);
//
//    // TaskID Constructor
//    TaskMetaTrait traitID(randID);
//    EXPECT_EQ(traitID.id, randID);
//    EXPECT_EQ(traitID.status, MetaData::INVALID);
//    EXPECT_EQ(traitID.userID, TaskMetaTrait::USER_INVALID);
//
//    // TaskID, Status Constructor
//    TaskMetaTrait traitMeta(randID, randMeta);
//    EXPECT_EQ(traitMeta.id, randID);
//    EXPECT_EQ(traitMeta.status, randMeta);
//    EXPECT_EQ(traitMeta.userID, TaskMetaTrait::USER_INVALID);
//
//    // TaskID, Status, User Constructor
//    TaskMetaTrait traitUser(randID, randMeta, randUser);
//    EXPECT_EQ(traitUser.id, randID);
//    EXPECT_EQ(traitUser.status, randMeta);
//    EXPECT_EQ(traitUser.userID, randUser);
//
//    // Copy Assignment
//    TaskMetaTrait copied(traitUser);
//    EXPECT_EQ(copied.id, traitUser.id);
//    EXPECT_EQ(copied.status, traitUser.status);
//    EXPECT_EQ(copied.userID, traitUser.userID);
//}
//
//TEST(TaskMeta, Constructors)
//{
//    constexpr size_t zero = 0;
//    std::unique_ptr<BYTE[]> buffer;
//    size_t size = TestUtils::GenerateRandomBuffer(buffer);
//    TaskMetaTrait trait = TestUtils::GenerateRandomTrait();
//
//    // Empty Constructor
//    TaskMeta meta;
//    EXPECT_EQ(meta.id, +TaskID::INVALID);
//    EXPECT_EQ(meta.status, MetaData::INVALID);
//    EXPECT_EQ(meta.userID, TaskMeta::USER_INVALID);
//    EXPECT_EQ(meta.GetBufferSize(), zero);
//    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);
//
//    // Default Constructor
//    TaskMeta task(trait, size, buffer.get());
//    EXPECT_EQ(trait, task);
//    EXPECT_EQ(task.GetBufferSize(), size);
//    TestUtils::ExpectBufferEqual(task.GetConstBuffer(), buffer, size);
//
//    // Move Constructor
//    TaskMeta moved(trait, size, std::move(buffer));
//    EXPECT_EQ(trait, moved);
//    EXPECT_EQ(moved.GetBufferSize(), size);
//    TestUtils::ExpectBufferEqual(moved.GetConstBuffer(), task.GetConstBuffer(),
//                                 size);
//
//    // Move Assignment
//    meta = std::move(moved);
//    EXPECT_EQ(trait, meta);
//    EXPECT_EQ(meta.GetBufferSize(), size);
//    TestUtils::ExpectBufferEqual(meta.GetConstBuffer(), task.GetConstBuffer(),
//                                 size);
//}
//
//TEST(TaskMeta, UniquePtr)
//{
//    constexpr size_t zero = 0;
//    std::unique_ptr<BYTE[]> buffer;
//    size_t size = TestUtils::GenerateRandomBuffer(buffer);
//
//    TaskMetaTrait trait = TestUtils::GenerateRandomTrait();
//    TaskMeta meta(trait, size, buffer.get());
//
//    // MoveBuffer
//    std::unique_ptr<BYTE[]> moved = meta.MoveBuffer();
//    EXPECT_EQ(meta.GetBufferSize(), zero);
//    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);
//    TestUtils::ExpectBufferEqual(buffer, moved, size);
//
//    // reset
//    meta = TaskMeta(trait, size, buffer.get());
//    meta.reset();
//    EXPECT_EQ(meta.GetBufferSize(), zero);
//    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);
//}
//
//TEST(TaskMeta, CopyFrom)
//{
//    // CopyFrom
//    TaskMeta meta = TestUtils::GenerateRandomTaskMeta();
//    TaskMeta copied = TaskMeta::CopyFrom(meta);
//    EXPECT_EQ(meta, copied);
//}
//
//TEST(TaskMeta, ConvertFrom)
//{
//    TaskMeta meta = TestUtils::GenerateRandomTaskMeta();
//    const auto& buffer = meta.GetConstBuffer();
//    size_t size = meta.GetBufferSize();
//
//    flatbuffers::FlatBufferBuilder builder(512);
//    auto trait = FlatData::TaskMetaTrait(static_cast<int>(meta.id),
//                                         static_cast<status_t>(meta.status),
//                                         meta.userID);
//
//    auto data = builder.CreateVector(buffer.get(), size);
//    auto serialized = FlatData::CreateTaskMeta(builder, &trait, data);
//    builder.Finish(serialized);
//
//    auto deserialized =
//        flatbuffers::GetRoot<FlatData::TaskMeta>(builder.GetBufferPointer());
//
//    // ConvertFrom
//    TaskMeta converted = TaskMeta::ConvertFrom(deserialized);
//    EXPECT_EQ(meta, converted);
//}<commit_msg>[ci skip] Update TaskMetaTests - Add Tests for TaskMeta Move Constructor<commit_after>#include "TestUtils.hpp"
#include "gtest/gtest.h"

#include <Tasks/TaskMeta.h>
#include <Tasks/TaskSerializer.h>

#include <Flatbuffers/generated/FlatData_generated.h>

using namespace Hearthstonepp;

TEST(TaskMeta, TraitConstructors)
{
    std::random_device rd;
    std::default_random_engine gen(rd());

    int sizeTaskID = static_cast<int>(TaskID::_size());
    int sizeMetaData = static_cast<int>(MetaData::GAME_END);

    TaskID randID = TaskID::_from_integral(gen() % sizeTaskID);
    MetaData randMeta = static_cast<MetaData>(gen() % sizeMetaData);
    BYTE randUser = gen() % 2;

    // Empty Trait Test
    TaskMetaTrait empty;
    EXPECT_EQ(empty.id, +TaskID::INVALID);
    EXPECT_EQ(empty.status, MetaData::INVALID);
    EXPECT_EQ(empty.userID, TaskMetaTrait::USER_INVALID);

    // TaskID Constructor
    TaskMetaTrait traitID(randID);
    EXPECT_EQ(traitID.id, randID);
    EXPECT_EQ(traitID.status, MetaData::INVALID);
    EXPECT_EQ(traitID.userID, TaskMetaTrait::USER_INVALID);

    // TaskID, Status Constructor
    TaskMetaTrait traitMeta(randID, randMeta);
    EXPECT_EQ(traitMeta.id, randID);
    EXPECT_EQ(traitMeta.status, randMeta);
    EXPECT_EQ(traitMeta.userID, TaskMetaTrait::USER_INVALID);

    // TaskID, Status, User Constructor
    TaskMetaTrait traitUser(randID, randMeta, randUser);
    EXPECT_EQ(traitUser.id, randID);
    EXPECT_EQ(traitUser.status, randMeta);
    EXPECT_EQ(traitUser.userID, randUser);

    // Copy Assignment
    TaskMetaTrait copied(traitUser);
    EXPECT_EQ(copied.id, traitUser.id);
    EXPECT_EQ(copied.status, traitUser.status);
    EXPECT_EQ(copied.userID, traitUser.userID);
}

TEST(TaskMeta, Constructors)
{
    constexpr size_t zero = 0;
    std::unique_ptr<BYTE[]> buffer;
    size_t size = TestUtils::GenerateRandomBuffer(buffer);
    TaskMetaTrait trait = TestUtils::GenerateRandomTrait();

    // Empty Constructor
    TaskMeta meta;
    EXPECT_EQ(meta.id, +TaskID::INVALID);
    EXPECT_EQ(meta.status, MetaData::INVALID);
    EXPECT_EQ(meta.userID, TaskMeta::USER_INVALID);
    EXPECT_EQ(meta.GetBufferSize(), zero);
    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);

    // Default Constructor
    TaskMeta task(trait, size, buffer.get());
    EXPECT_EQ(trait, task);
    EXPECT_EQ(task.GetBufferSize(), size);
    TestUtils::ExpectBufferEqual(task.GetConstBuffer(), buffer, size);

    // Move Buffer
    TaskMeta moveBuffer(trait, size, std::move(buffer));
    EXPECT_EQ(trait, moveBuffer);
    EXPECT_EQ(moveBuffer.GetBufferSize(), size);
    TestUtils::ExpectBufferEqual(moveBuffer.GetConstBuffer(),
                                 task.GetConstBuffer(), size);

    // Move Constructor
    TaskMeta moved(std::move(moveBuffer));
    EXPECT_EQ(trait, moved);
    EXPECT_EQ(moved.GetBufferSize(), size);
    TestUtils::ExpectBufferEqual(moved.GetConstBuffer(), task.GetConstBuffer(),
                                 size);

    // Move Assignment
    meta = std::move(moved);
    EXPECT_EQ(trait, meta);
    EXPECT_EQ(meta.GetBufferSize(), size);
    TestUtils::ExpectBufferEqual(meta.GetConstBuffer(), task.GetConstBuffer(),
                                 size);
}

TEST(TaskMeta, UniquePtr)
{
    constexpr size_t zero = 0;
    std::unique_ptr<BYTE[]> buffer;
    size_t size = TestUtils::GenerateRandomBuffer(buffer);

    TaskMetaTrait trait = TestUtils::GenerateRandomTrait();
    TaskMeta meta(trait, size, buffer.get());

    // MoveBuffer
    std::unique_ptr<BYTE[]> moved = meta.MoveBuffer();
    EXPECT_EQ(meta.GetBufferSize(), zero);
    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);
    TestUtils::ExpectBufferEqual(buffer, moved, size);

    // reset
    meta = TaskMeta(trait, size, buffer.get());
    meta.reset();
    EXPECT_EQ(meta.GetBufferSize(), zero);
    EXPECT_EQ(meta.GetConstBuffer().get(), nullptr);
}

TEST(TaskMeta, CopyFrom)
{
    // CopyFrom
    TaskMeta meta = TestUtils::GenerateRandomTaskMeta();
    TaskMeta copied = TaskMeta::CopyFrom(meta);
    EXPECT_EQ(meta, copied);
}

TEST(TaskMeta, ConvertFrom)
{
    TaskMeta meta = TestUtils::GenerateRandomTaskMeta();
    const auto& buffer = meta.GetConstBuffer();
    size_t size = meta.GetBufferSize();

    flatbuffers::FlatBufferBuilder builder(512);
    auto trait = FlatData::TaskMetaTrait(static_cast<int>(meta.id),
                                         static_cast<status_t>(meta.status),
                                         meta.userID);

    auto data = builder.CreateVector(buffer.get(), size);
    auto serialized = FlatData::CreateTaskMeta(builder, &trait, data);
    builder.Finish(serialized);

    auto deserialized =
        flatbuffers::GetRoot<FlatData::TaskMeta>(builder.GetBufferPointer());

    // ConvertFrom
    TaskMeta converted = TaskMeta::ConvertFrom(deserialized);
    EXPECT_EQ(meta, converted);
}
<|endoftext|>


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

#include "vppinputdecode.h"
#include "vppinputoutput.h"
#include "vppoutputencode.h"
#include "encodeinput.h"
#include "tests/vppinputasync.h"
#include "common/log.h"
#include "VideoEncoderInterface.h"
#include "VideoEncoderHost.h"
#include "VideoPostProcessHost.h"
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

using namespace YamiMediaCodec;

static void print_help(const char* app)
{
    printf("%s <options>\n", app);
    printf("   -i <source filename> load a raw yuv file or a compressed video file\n");
    printf("   -W <width> -H <height>\n");
    printf("   -o <coded file> optional\n");
    printf("   -b <bitrate: kbps> optional\n");
    printf("   -f <frame rate> optional\n");
    printf("   -c <codec: HEVC|AVC|VP8|JPEG>\n");
    printf("   -s <fourcc: I420|NV12|IYUV|YV12>\n");
    printf("   -N <number of frames to encode(camera default 50), useful for camera>\n");
    printf("   --qp <initial qp> optional\n");
    printf("   --rcmode <CBR|CQP> optional\n");
    printf("   --ipperiod <0 (I frame only) | 1 (I and P frames) | N (I,P and B frames, B frame number is N-1)> optional\n");
    printf("   --intraperiod <Intra frame period(default 30)> optional\n");
    printf("   --refnum <number of referece frames(default 1)> optional\n");
    printf("   --idrinterval <AVC/HEVC IDR frame interval(default 0)> optional\n");
    printf("   --enablecabac <AVC is to use CABAC or not in Main Profile (default true)> optional\n");
    printf("   --enabledct8x8 <AVC is to use DCT8x8 transform or not in High Profile (default false)> optional\n");
    printf("   --enabledeblockfilter <AVC is to use Deblock filter or not (default true)> optional\n");
    printf("   --deblockalphadiv2 <AVC Alpha offset of debloking filter divided 2 (default 2)> optional\n");
    printf("   --deblockbetadiv2 <AVC Beta offset of debloking filter divided 2 (default 2)> optional\n");
}

static VideoRateControl string_to_rc_mode(char *str)
{
    VideoRateControl rcMode;

    if (!strcasecmp (str, "CBR"))
        rcMode = RATE_CONTROL_CBR;
    else if (!strcasecmp (str, "CQP"))
        rcMode = RATE_CONTROL_CQP;
    else {
        printf("Unsupport  RC mode\n");
        rcMode = RATE_CONTROL_NONE;
    }
    return rcMode;
}

static bool processCmdLine(int argc, char *argv[], TranscodeParams& para)
{
    char opt;
    const struct option long_opts[] = {
        {"help", no_argument, NULL, 'h' },
        {"qp", required_argument, NULL, 0 },
        {"rcmode", required_argument, NULL, 0 },
        {"ipperiod", required_argument, NULL, 0 },
        {"intraperiod", required_argument, NULL, 0 },
        {"refnum", required_argument, NULL, 0 },
        {"idrinterval", required_argument, NULL, 0 },
        {"enablecabac", required_argument, NULL, 0},
        {"enabledct8x8", required_argument, NULL, 0},
        {"enabledeblockfilter", required_argument, NULL, 0},
        {"deblockalphadiv2", required_argument, NULL, 0},
        {"deblockbetadiv2", required_argument, NULL, 0},
        {NULL, no_argument, NULL, 0 }};
    int option_index;

    if (argc < 2) {
        fprintf(stderr, "can not encode without option, please type 'yamitranscode -h' to help\n");
        return false;
    }

    while ((opt = getopt_long_only(argc, argv, "W:H:b:f:c:s:i:o:N:h:", long_opts,&option_index)) != -1)
    {
        switch (opt) {
        case 'h':
        case '?':
            print_help (argv[0]);
            return false;
        case 'i':
            para.inputFileName = optarg;
            break;
        case 'o':
            para.outputFileName = optarg;
            break;
        case 'W':
            para.oWidth = atoi(optarg);
            break;
        case 'H':
            para.oHeight = atoi(optarg);
            break;
        case 'b':
            para.m_encParams.bitRate = atoi(optarg) * 1024;//kbps to bps
            break;
        case 'f':
            para.m_encParams.fps = atoi(optarg);
            break;
        case 'c':
            para.m_encParams.codec = optarg;
            break;
        case 's':
            if (strlen(optarg) == 4)
                para.fourcc = VA_FOURCC(optarg[0], optarg[1], optarg[2], optarg[3]);
            break;
        case 'N':
            para.frameCount = atoi(optarg);
            break;
        case 0:
             switch (option_index) {
                case 1:
                    para.m_encParams.initQp = atoi(optarg);
                    break;
                case 2:
                    para.m_encParams.rcMode = string_to_rc_mode(optarg);
                    break;
                case 3:
                    para.m_encParams.ipPeriod = atoi(optarg);
                    break;
                case 4:
                    para.m_encParams.intraPeriod = atoi(optarg);
                    break;
                case 5:
                    para.m_encParams.numRefFrames= atoi(optarg);
                    break;
                case 6:
                    para.m_encParams.idrInterval = atoi(optarg);
                    break;
                case 7:
                    para.m_encParams.enableCabac = strncasecmp(optarg, "false", 5) != 0;
                    break;
                case 8:
                    para.m_encParams.enableDct8x8 = strncasecmp(optarg, "true", 4) == 0;
                    break;
                case 9:
                    para.m_encParams.enableDeblockFilter = strncasecmp(optarg, "false", 5) != 0;
                    break;
                case 10:
                    para.m_encParams.deblockAlphaOffsetDiv2 = atoi(optarg);
                    break;
                case 11:
                    para.m_encParams.deblockBetaOffsetDiv2 = atoi(optarg);
                    break;
            }
        }
    }

    if (para.inputFileName.empty()) {
        fprintf(stderr, "can not encode without input file\n");
        return false;
    }
    if (para.outputFileName.empty())
        para.outputFileName = "test.264";

    if ((para.m_encParams.rcMode == RATE_CONTROL_CBR) && (para.m_encParams.bitRate <= 0)) {
        fprintf(stderr, "please make sure bitrate is positive when CBR mode\n");
        return false;
    }

    if (!strncmp(para.inputFileName.c_str(), "/dev/video", strlen("/dev/video")) && !para.frameCount)
        para.frameCount = 50;

    return true;
}

SharedPtr<VppInput> createInput(TranscodeParams& para, const SharedPtr<VADisplay>& display)
{
    SharedPtr<VppInput> input(VppInput::create(para.inputFileName.c_str()));
    if (!input) {
        ERROR("creat input failed");
        return input;
    }
    SharedPtr<VppInputFile> inputFile = std::tr1::dynamic_pointer_cast<VppInputFile>(input);
    if (inputFile) {
        SharedPtr<FrameReader> reader(new VaapiFrameReader(display));
        SharedPtr<FrameAllocator> alloctor(new PooledFrameAllocator(display, 5));
        if(!inputFile->config(alloctor, reader)) {
            ERROR("config input failed");
            input.reset();
        }
    }
    SharedPtr<VppInputDecode> inputDecode = std::tr1::dynamic_pointer_cast<VppInputDecode>(input);
    if (inputDecode) {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*display;
        if(!inputDecode->config(nativeDisplay)) {
            ERROR("config input decode failed");
            input.reset();
        }
    }
    if (input)
        input = VppInputAsync::create(input, 3); //make input in other thread.
    return input;
}

SharedPtr<VppOutput> createOutput(TranscodeParams& para, const SharedPtr<VADisplay>& display)
{
    SharedPtr<VppOutput> output = VppOutput::create(para.outputFileName.c_str(), para.fourcc, para.oWidth, para.oHeight);
    SharedPtr<VppOutputFile> outputFile = std::tr1::dynamic_pointer_cast<VppOutputFile>(output);
    if (outputFile) {
        SharedPtr<FrameWriter> writer(new VaapiFrameWriter(display));
        if (!outputFile->config(writer)) {
            ERROR("config writer failed");
            output.reset();
        }
        return output;
    }
    SharedPtr<VppOutputEncode> outputEncode = std::tr1::dynamic_pointer_cast<VppOutputEncode>(output);
    if (outputEncode) {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*display;
        if (!outputEncode->config(nativeDisplay, &para.m_encParams)) {
            ERROR("config ouput encode failed");
            output.reset();
        }
        return output;
    }
    return output;
}

SharedPtr<FrameAllocator> createAllocator(const SharedPtr<VppOutput>& output, const SharedPtr<VADisplay>& display)
{
    uint32_t fourcc;
    int width, height;
    SharedPtr<FrameAllocator> allocator(new PooledFrameAllocator(display, 5));
    if (!output->getFormat(fourcc, width, height)
        || !allocator->setFormat(fourcc, width,height)) {
        allocator.reset();
        ERROR("get Format failed");
    }
    return allocator;
}

class TranscodeTest
{
public:
    bool init(int argc, char* argv[])
    {
        if (!processCmdLine(argc, argv, m_cmdParam))
            return false;

        m_display = createVADisplay();
        if (!m_display) {
            printf("create display failed");
            return false;
        }
        if (!createVpp()) {
            ERROR("create vpp failed");
            return false;
        }
        m_input = createInput(m_cmdParam, m_display);
        m_output =  createOutput(m_cmdParam, m_display);
        if (!m_input || !m_output) {
            ERROR("create input or output failed");
            return false;
        }
        m_allocator = createAllocator(m_output, m_display);
        return m_allocator;
    }

    bool run()
    {

        SharedPtr<VideoFrame> src;
        FpsCalc fps;
        uint32_t count = 0;
        while (m_input->read(src)) {
            SharedPtr<VideoFrame> dest = m_allocator->alloc();
            if (!dest) {
                ERROR("failed to get output frame");
                break;
            }
//disable scale for performance measure
//#define DISABLE_SCALE 1
#ifndef DISABLE_SCALE
            YamiStatus status = m_vpp->process(src, dest);
            if (status != YAMI_SUCCESS) {
                ERROR("failed to scale yami return %d", status);
                break;
            }
#else
            dest = src;
#endif
            if(!m_output->output(dest))
                break;
            count++;
            fps.addFrame();
            if(count >= m_cmdParam.frameCount)
                break;
        }
        fps.log();
        return true;
    }
private:
    bool createVpp()
    {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*m_display;
        m_vpp.reset(createVideoPostProcess(YAMI_VPP_SCALER), releaseVideoPostProcess);
        return m_vpp->setNativeDisplay(nativeDisplay) == YAMI_SUCCESS;
    }
    SharedPtr<VADisplay> m_display;
    SharedPtr<VppInput> m_input;
    SharedPtr<VppOutput> m_output;
    SharedPtr<FrameAllocator> m_allocator;
    SharedPtr<IVideoPostProcess> m_vpp;
    TranscodeParams m_cmdParam;
};

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

    TranscodeTest trans;
    if (!trans.init(argc, argv)) {
        ERROR("init transcode with command line parameters failed");
        return -1;
    }
    if (!trans.run()){
        ERROR("run transcode failed");
        return -1;
    }
    printf("transcode done\n");
    return  0;

}
<commit_msg>transcode: set ipPeriod to poolsize to fix issue #461<commit_after>/*
 * Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "vppinputdecode.h"
#include "vppinputoutput.h"
#include "vppoutputencode.h"
#include "encodeinput.h"
#include "tests/vppinputasync.h"
#include "common/log.h"
#include "VideoEncoderInterface.h"
#include "VideoEncoderHost.h"
#include "VideoPostProcessHost.h"
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

using namespace YamiMediaCodec;

static void print_help(const char* app)
{
    printf("%s <options>\n", app);
    printf("   -i <source filename> load a raw yuv file or a compressed video file\n");
    printf("   -W <width> -H <height>\n");
    printf("   -o <coded file> optional\n");
    printf("   -b <bitrate: kbps> optional\n");
    printf("   -f <frame rate> optional\n");
    printf("   -c <codec: HEVC|AVC|VP8|JPEG>\n");
    printf("   -s <fourcc: I420|NV12|IYUV|YV12>\n");
    printf("   -N <number of frames to encode(camera default 50), useful for camera>\n");
    printf("   --qp <initial qp> optional\n");
    printf("   --rcmode <CBR|CQP> optional\n");
    printf("   --ipperiod <0 (I frame only) | 1 (I and P frames) | N (I,P and B frames, B frame number is N-1)> optional\n");
    printf("   --intraperiod <Intra frame period(default 30)> optional\n");
    printf("   --refnum <number of referece frames(default 1)> optional\n");
    printf("   --idrinterval <AVC/HEVC IDR frame interval(default 0)> optional\n");
    printf("   --enablecabac <AVC is to use CABAC or not in Main Profile (default true)> optional\n");
    printf("   --enabledct8x8 <AVC is to use DCT8x8 transform or not in High Profile (default false)> optional\n");
    printf("   --enabledeblockfilter <AVC is to use Deblock filter or not (default true)> optional\n");
    printf("   --deblockalphadiv2 <AVC Alpha offset of debloking filter divided 2 (default 2)> optional\n");
    printf("   --deblockbetadiv2 <AVC Beta offset of debloking filter divided 2 (default 2)> optional\n");
}

static VideoRateControl string_to_rc_mode(char *str)
{
    VideoRateControl rcMode;

    if (!strcasecmp (str, "CBR"))
        rcMode = RATE_CONTROL_CBR;
    else if (!strcasecmp (str, "CQP"))
        rcMode = RATE_CONTROL_CQP;
    else {
        printf("Unsupport  RC mode\n");
        rcMode = RATE_CONTROL_NONE;
    }
    return rcMode;
}

static bool processCmdLine(int argc, char *argv[], TranscodeParams& para)
{
    char opt;
    const struct option long_opts[] = {
        {"help", no_argument, NULL, 'h' },
        {"qp", required_argument, NULL, 0 },
        {"rcmode", required_argument, NULL, 0 },
        {"ipperiod", required_argument, NULL, 0 },
        {"intraperiod", required_argument, NULL, 0 },
        {"refnum", required_argument, NULL, 0 },
        {"idrinterval", required_argument, NULL, 0 },
        {"enablecabac", required_argument, NULL, 0},
        {"enabledct8x8", required_argument, NULL, 0},
        {"enabledeblockfilter", required_argument, NULL, 0},
        {"deblockalphadiv2", required_argument, NULL, 0},
        {"deblockbetadiv2", required_argument, NULL, 0},
        {NULL, no_argument, NULL, 0 }};
    int option_index;

    if (argc < 2) {
        fprintf(stderr, "can not encode without option, please type 'yamitranscode -h' to help\n");
        return false;
    }

    while ((opt = getopt_long_only(argc, argv, "W:H:b:f:c:s:i:o:N:h:", long_opts,&option_index)) != -1)
    {
        switch (opt) {
        case 'h':
        case '?':
            print_help (argv[0]);
            return false;
        case 'i':
            para.inputFileName = optarg;
            break;
        case 'o':
            para.outputFileName = optarg;
            break;
        case 'W':
            para.oWidth = atoi(optarg);
            break;
        case 'H':
            para.oHeight = atoi(optarg);
            break;
        case 'b':
            para.m_encParams.bitRate = atoi(optarg) * 1024;//kbps to bps
            break;
        case 'f':
            para.m_encParams.fps = atoi(optarg);
            break;
        case 'c':
            para.m_encParams.codec = optarg;
            break;
        case 's':
            if (strlen(optarg) == 4)
                para.fourcc = VA_FOURCC(optarg[0], optarg[1], optarg[2], optarg[3]);
            break;
        case 'N':
            para.frameCount = atoi(optarg);
            break;
        case 0:
             switch (option_index) {
                case 1:
                    para.m_encParams.initQp = atoi(optarg);
                    break;
                case 2:
                    para.m_encParams.rcMode = string_to_rc_mode(optarg);
                    break;
                case 3:
                    para.m_encParams.ipPeriod = atoi(optarg);
                    break;
                case 4:
                    para.m_encParams.intraPeriod = atoi(optarg);
                    break;
                case 5:
                    para.m_encParams.numRefFrames= atoi(optarg);
                    break;
                case 6:
                    para.m_encParams.idrInterval = atoi(optarg);
                    break;
                case 7:
                    para.m_encParams.enableCabac = strncasecmp(optarg, "false", 5) != 0;
                    break;
                case 8:
                    para.m_encParams.enableDct8x8 = strncasecmp(optarg, "true", 4) == 0;
                    break;
                case 9:
                    para.m_encParams.enableDeblockFilter = strncasecmp(optarg, "false", 5) != 0;
                    break;
                case 10:
                    para.m_encParams.deblockAlphaOffsetDiv2 = atoi(optarg);
                    break;
                case 11:
                    para.m_encParams.deblockBetaOffsetDiv2 = atoi(optarg);
                    break;
            }
        }
    }

    if (para.inputFileName.empty()) {
        fprintf(stderr, "can not encode without input file\n");
        return false;
    }
    if (para.outputFileName.empty())
        para.outputFileName = "test.264";

    if ((para.m_encParams.rcMode == RATE_CONTROL_CBR) && (para.m_encParams.bitRate <= 0)) {
        fprintf(stderr, "please make sure bitrate is positive when CBR mode\n");
        return false;
    }

    if (!strncmp(para.inputFileName.c_str(), "/dev/video", strlen("/dev/video")) && !para.frameCount)
        para.frameCount = 50;

    return true;
}

SharedPtr<VppInput> createInput(TranscodeParams& para, const SharedPtr<VADisplay>& display)
{
    SharedPtr<VppInput> input(VppInput::create(para.inputFileName.c_str()));
    if (!input) {
        ERROR("creat input failed");
        return input;
    }
    SharedPtr<VppInputFile> inputFile = std::tr1::dynamic_pointer_cast<VppInputFile>(input);
    if (inputFile) {
        SharedPtr<FrameReader> reader(new VaapiFrameReader(display));
        SharedPtr<FrameAllocator> alloctor(new PooledFrameAllocator(display, 5));
        if(!inputFile->config(alloctor, reader)) {
            ERROR("config input failed");
            input.reset();
        }
    }
    SharedPtr<VppInputDecode> inputDecode = std::tr1::dynamic_pointer_cast<VppInputDecode>(input);
    if (inputDecode) {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*display;
        if(!inputDecode->config(nativeDisplay)) {
            ERROR("config input decode failed");
            input.reset();
        }
    }
    if (input)
        input = VppInputAsync::create(input, 3); //make input in other thread.
    return input;
}

SharedPtr<VppOutput> createOutput(TranscodeParams& para, const SharedPtr<VADisplay>& display)
{
    SharedPtr<VppOutput> output = VppOutput::create(para.outputFileName.c_str(), para.fourcc, para.oWidth, para.oHeight);
    SharedPtr<VppOutputFile> outputFile = std::tr1::dynamic_pointer_cast<VppOutputFile>(output);
    if (outputFile) {
        SharedPtr<FrameWriter> writer(new VaapiFrameWriter(display));
        if (!outputFile->config(writer)) {
            ERROR("config writer failed");
            output.reset();
        }
        return output;
    }
    SharedPtr<VppOutputEncode> outputEncode = std::tr1::dynamic_pointer_cast<VppOutputEncode>(output);
    if (outputEncode) {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*display;
        if (!outputEncode->config(nativeDisplay, &para.m_encParams)) {
            ERROR("config ouput encode failed");
            output.reset();
        }
        return output;
    }
    return output;
}

SharedPtr<FrameAllocator> createAllocator(const SharedPtr<VppOutput>& output, const SharedPtr<VADisplay>& display, int32_t extraSize)
{
    uint32_t fourcc;
    int width, height;
    SharedPtr<FrameAllocator> allocator(new PooledFrameAllocator(display, std::max(extraSize, 5)));
    if (!output->getFormat(fourcc, width, height)
        || !allocator->setFormat(fourcc, width,height)) {
        allocator.reset();
        ERROR("get Format failed");
    }
    return allocator;
}

class TranscodeTest
{
public:
    bool init(int argc, char* argv[])
    {
        if (!processCmdLine(argc, argv, m_cmdParam))
            return false;

        m_display = createVADisplay();
        if (!m_display) {
            printf("create display failed");
            return false;
        }
        if (!createVpp()) {
            ERROR("create vpp failed");
            return false;
        }
        m_input = createInput(m_cmdParam, m_display);
        m_output =  createOutput(m_cmdParam, m_display);
        if (!m_input || !m_output) {
            ERROR("create input or output failed");
            return false;
        }
        m_allocator = createAllocator(m_output, m_display, m_cmdParam.m_encParams.ipPeriod);
        return m_allocator;
    }

    bool run()
    {

        SharedPtr<VideoFrame> src;
        FpsCalc fps;
        uint32_t count = 0;
        while (m_input->read(src)) {
            SharedPtr<VideoFrame> dest = m_allocator->alloc();
            if (!dest) {
                ERROR("failed to get output frame");
                break;
            }
//disable scale for performance measure
//#define DISABLE_SCALE 1
#ifndef DISABLE_SCALE
            YamiStatus status = m_vpp->process(src, dest);
            if (status != YAMI_SUCCESS) {
                ERROR("failed to scale yami return %d", status);
                break;
            }
#else
            dest = src;
#endif
            if(!m_output->output(dest))
                break;
            count++;
            fps.addFrame();
            if(count >= m_cmdParam.frameCount)
                break;
        }
        fps.log();
        return true;
    }
private:
    bool createVpp()
    {
        NativeDisplay nativeDisplay;
        nativeDisplay.type = NATIVE_DISPLAY_VA;
        nativeDisplay.handle = (intptr_t)*m_display;
        m_vpp.reset(createVideoPostProcess(YAMI_VPP_SCALER), releaseVideoPostProcess);
        return m_vpp->setNativeDisplay(nativeDisplay) == YAMI_SUCCESS;
    }
    SharedPtr<VADisplay> m_display;
    SharedPtr<VppInput> m_input;
    SharedPtr<VppOutput> m_output;
    SharedPtr<FrameAllocator> m_allocator;
    SharedPtr<IVideoPostProcess> m_vpp;
    TranscodeParams m_cmdParam;
};

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

    TranscodeTest trans;
    if (!trans.init(argc, argv)) {
        ERROR("init transcode with command line parameters failed");
        return -1;
    }
    if (!trans.run()){
        ERROR("run transcode failed");
        return -1;
    }
    printf("transcode done\n");
    return  0;

}
<|endoftext|>


<commit_before><commit_msg>When we had upload data, but it was a zero-length upload data, we would not set the FIN flag, which would stall the request upload.<commit_after><|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    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 3 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, see <http://www.gnu.org/licenses/>.

 The full license is available in the file GPLv3.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

//!
//! @file   HopsanGUI/main.cpp
//!
//! @brief The main program for the HopsanGUI application
//!
//$Id$

#include <clocale>

#include <QApplication>
#include <QSplashScreen>
#include <QTimer>
#include <QLocale>
#include <QDebug>
#include <QFontDatabase>

#include "common.h"
#include "global.h"
#include "version_gui.h"
#include "MainWindow.h"
#include "Configuration.h"
#include "CopyStack.h"
#include "DesktopHandler.h"
#include "MessageHandler.h"
#include "CoreUtilities/HmfLoader.h"
#include "Widgets/HcomWidget.h"
#include "HcomHandler.h"
#include "Dialogs/LicenseDialog.h"

// Declare global pointers
MainWindow* gpMainWindow = 0;
QWidget *gpMainWindowWidget = 0;
Configuration *gpConfig = 0;
DesktopHandler *gpDesktopHandler = 0;
CopyStack *gpCopyStack = 0;
QSplashScreen *gpSplash = 0;
GUIMessageHandler *gpMessageHandler = 0;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qRegisterMetaType<GUIMessage>("GUIMessage");

    // Forcing numeric locale to C only using QLocale::setDefault() does not seem to help
    std::setlocale(LC_NUMERIC, "C");                // Set default C locale
    std::locale::global(std::locale::classic());    // Set default C++ locale (should also set default C locale)
    std::lconv* lc = std::localeconv();
    qDebug() << "Decimal point: " << lc->decimal_point << " thousand separator: \"" << lc->thousands_sep << "\"";
    //  Force QLocale to English/USA
    qDebug() << "QLocale: " << QLocale().languageToString(QLocale().language()) << " " << QLocale().countryToString(QLocale().country()) << " Decimal point: " << QLocale().decimalPoint();
    QLocale::setDefault(QLocale("C"));
    qDebug() << "Changing QLocale to: " << QLocale().languageToString(QLocale().language()) << " " << QLocale().countryToString(QLocale().country()) << " Decimal point: " << QLocale().decimalPoint();
    //! @todo this did not help before, DomElement.setAttribute still used comma decimal point on Swedish Ubuntu, now after adding std::setLocale above it might actually work.
    lc = std::localeconv();
    qDebug() << "C Decimal point: " << lc->decimal_point << " thousand separator: \"" << lc->thousands_sep << "\"";
    qDebug() << "C++ locale name: " << std::locale().name().c_str();
    qDebug() << "QLocale is: " << QLocale().name() << " " << " Decimal point: " << QLocale().decimalPoint();

    // Create the mainwindow
    MainWindow mainwindow;
    gpMainWindow = &mainwindow;
    gpMainWindowWidget = static_cast<QWidget*>(&mainwindow);

    // Create the splash screen
    QPixmap pixmap(QString(GRAPHICSPATH) + "splash.png");
    gpSplash = new QSplashScreen(&mainwindow, pixmap/*, Qt::WindowStaysOnTopHint*/);
    //! @todo We need to delete it somehow, but still be able to check if it has been deleted or not (perhaps a QPointer will work)
    //gpSplash->setAttribute(Qt::WA_DeleteOnClose);
    gpSplash->showMessage("Starting Hopsan...");
    gpSplash->show();

    // Create/set global objects
    gpDesktopHandler = new DesktopHandler();
    gpDesktopHandler->setupPaths();
    gpConfig = new Configuration();
    gpCopyStack = new CopyStack();
    gpMessageHandler = new GUIMessageHandler();

    gpConfig->connect(gpConfig, SIGNAL(recentModelsListChanged()), gpMainWindow, SLOT(updateRecentList()));

    //Create contents in MainWindow
    mainwindow.createContents();

    // Clear cache folders from left over junk (if Hopsan crashed last time, or was unable to cleanup)
    gpDesktopHandler->checkLogCacheForOldFiles();

    // Show main window and initialize workspace
    //QTimer::singleShot(20, &mainwindow, SLOT(showMaximized()));
    mainwindow.initializeWorkspace();
    mainwindow.showMaximized();

    // Process any received messages
    gpMessageHandler->startPublish();

    // Show license dialog
    if (gpConfig->getBoolSetting(CFG_SHOWLICENSEONSTARTUP))
    {
        (new LicenseDialog(gpMainWindowWidget))->show();
        // Note! it will delete on close automatically
    }

    // Read command line arguments, search for hcom scripts, ignore everything else
    //! @todo maybe use TCLAP here
    QStringList args = a.arguments();
    for(QString &arg : args)
    {
        if(arg.endsWith(".hcom"))
        {
            QFileInfo fi(arg);
            if (fi.isRelative())
            {
                arg = gpDesktopHandler->getExecPath()+"/"+arg;
            }
            gpTerminalWidget->mpHandler->executeCommand("exec "+arg);
        }
    }

    // Execute application
    int rc = a.exec();

    // Delete global objects after program execution is finished
    delete gpCopyStack;
    delete gpDesktopHandler;
    delete gpConfig;

    // Return application return code
    return rc;
}

//! @brief Returns the date and time when the HopsanGUI application was built
const char* getHopsanGUIBuildTime()
{
    return __DATE__ " " __TIME__;
}
<commit_msg>Add missing header for std::locale (was not a problem with GCC)<commit_after>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    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 3 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, see <http://www.gnu.org/licenses/>.

 The full license is available in the file GPLv3.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

//!
//! @file   HopsanGUI/main.cpp
//!
//! @brief The main program for the HopsanGUI application
//!
//$Id$

#include <locale>
#include <clocale>

#include <QApplication>
#include <QSplashScreen>
#include <QTimer>
#include <QLocale>
#include <QDebug>
#include <QFontDatabase>

#include "common.h"
#include "global.h"
#include "version_gui.h"
#include "MainWindow.h"
#include "Configuration.h"
#include "CopyStack.h"
#include "DesktopHandler.h"
#include "MessageHandler.h"
#include "CoreUtilities/HmfLoader.h"
#include "Widgets/HcomWidget.h"
#include "HcomHandler.h"
#include "Dialogs/LicenseDialog.h"

// Declare global pointers
MainWindow* gpMainWindow = 0;
QWidget *gpMainWindowWidget = 0;
Configuration *gpConfig = 0;
DesktopHandler *gpDesktopHandler = 0;
CopyStack *gpCopyStack = 0;
QSplashScreen *gpSplash = 0;
GUIMessageHandler *gpMessageHandler = 0;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qRegisterMetaType<GUIMessage>("GUIMessage");

    // Forcing numeric locale to C only using QLocale::setDefault() does not seem to help
    std::setlocale(LC_NUMERIC, "C");                // Set default C locale
    std::locale::global(std::locale::classic());    // Set default C++ locale (should also set default C locale)
    std::lconv* lc = std::localeconv();
    qDebug() << "Decimal point: " << lc->decimal_point << " thousand separator: \"" << lc->thousands_sep << "\"";
    //  Force QLocale to English/USA
    qDebug() << "QLocale: " << QLocale().languageToString(QLocale().language()) << " " << QLocale().countryToString(QLocale().country()) << " Decimal point: " << QLocale().decimalPoint();
    QLocale::setDefault(QLocale("C"));
    qDebug() << "Changing QLocale to: " << QLocale().languageToString(QLocale().language()) << " " << QLocale().countryToString(QLocale().country()) << " Decimal point: " << QLocale().decimalPoint();
    //! @todo this did not help before, DomElement.setAttribute still used comma decimal point on Swedish Ubuntu, now after adding std::setLocale above it might actually work.
    lc = std::localeconv();
    qDebug() << "C Decimal point: " << lc->decimal_point << " thousand separator: \"" << lc->thousands_sep << "\"";
    qDebug() << "C++ locale name: " << std::locale().name().c_str();
    qDebug() << "QLocale is: " << QLocale().name() << " " << " Decimal point: " << QLocale().decimalPoint();

    // Create the mainwindow
    MainWindow mainwindow;
    gpMainWindow = &mainwindow;
    gpMainWindowWidget = static_cast<QWidget*>(&mainwindow);

    // Create the splash screen
    QPixmap pixmap(QString(GRAPHICSPATH) + "splash.png");
    gpSplash = new QSplashScreen(&mainwindow, pixmap/*, Qt::WindowStaysOnTopHint*/);
    //! @todo We need to delete it somehow, but still be able to check if it has been deleted or not (perhaps a QPointer will work)
    //gpSplash->setAttribute(Qt::WA_DeleteOnClose);
    gpSplash->showMessage("Starting Hopsan...");
    gpSplash->show();

    // Create/set global objects
    gpDesktopHandler = new DesktopHandler();
    gpDesktopHandler->setupPaths();
    gpConfig = new Configuration();
    gpCopyStack = new CopyStack();
    gpMessageHandler = new GUIMessageHandler();

    gpConfig->connect(gpConfig, SIGNAL(recentModelsListChanged()), gpMainWindow, SLOT(updateRecentList()));

    //Create contents in MainWindow
    mainwindow.createContents();

    // Clear cache folders from left over junk (if Hopsan crashed last time, or was unable to cleanup)
    gpDesktopHandler->checkLogCacheForOldFiles();

    // Show main window and initialize workspace
    //QTimer::singleShot(20, &mainwindow, SLOT(showMaximized()));
    mainwindow.initializeWorkspace();
    mainwindow.showMaximized();

    // Process any received messages
    gpMessageHandler->startPublish();

    // Show license dialog
    if (gpConfig->getBoolSetting(CFG_SHOWLICENSEONSTARTUP))
    {
        (new LicenseDialog(gpMainWindowWidget))->show();
        // Note! it will delete on close automatically
    }

    // Read command line arguments, search for hcom scripts, ignore everything else
    //! @todo maybe use TCLAP here
    QStringList args = a.arguments();
    for(QString &arg : args)
    {
        if(arg.endsWith(".hcom"))
        {
            QFileInfo fi(arg);
            if (fi.isRelative())
            {
                arg = gpDesktopHandler->getExecPath()+"/"+arg;
            }
            gpTerminalWidget->mpHandler->executeCommand("exec "+arg);
        }
    }

    // Execute application
    int rc = a.exec();

    // Delete global objects after program execution is finished
    delete gpCopyStack;
    delete gpDesktopHandler;
    delete gpConfig;

    // Return application return code
    return rc;
}

//! @brief Returns the date and time when the HopsanGUI application was built
const char* getHopsanGUIBuildTime()
{
    return __DATE__ " " __TIME__;
}
<|endoftext|>


<commit_before>    /*
        open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#ifndef MAP_MATCHING_PLUGIN_H
#define MAP_MATCHING_PLUGIN_H

#include "plugin_base.hpp"

#include "../algorithms/bayes_classifier.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../util/integer_range.hpp"
#include "../data_structures/search_engine.hpp"
#include "../routing_algorithms/map_matching.hpp"
#include "../util/compute_angle.hpp"
#include "../util/simple_logger.hpp"
#include "../util/string_util.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/gpx_descriptor.hpp"
#include "../descriptors/json_descriptor.hpp"

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
  private:
    std::unordered_map<std::string, unsigned> descriptor_table;
    std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

    using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>;
    using TraceClassification = ClassifierT::ClassificationT;

  public:
    MapMatchingPlugin(DataFacadeT *facade)
    : descriptor_string("match")
    , facade(facade)
    // the values where derived from fitting a laplace distribution
    // to the values of manually classified traces
    , classifier(LaplaceDistribution(0.0057154021891018675, 0.020294704891166186),
                 LaplaceDistribution(0.11467696742821254, 0.49918444000368756),
                 0.7977883096366508) // valid apriori probability
    {
        descriptor_table.emplace("json", 0);
        search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
    }

    virtual ~MapMatchingPlugin() { search_engine_ptr.reset(); }

    const std::string GetDescriptor() const final { return descriptor_string; }

    TraceClassification classify(float trace_length, float matched_length, int removed_points) const
    {
        double distance_feature = -std::log(trace_length) + std::log(matched_length);

        // matched to the same point
        if (!std::isfinite(distance_feature))
        {
            return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
        }

        auto label_with_confidence =  classifier.classify(distance_feature);

        // "second stage classifier": if we need to remove points there is something fishy
        if (removed_points > 0)
        {
            return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
        }

        return label_with_confidence;
    }

    bool get_candiates(const std::vector<FixedPointCoordinate>& input_coords, std::vector<double>& sub_trace_lengths, Matching::CandidateLists& candidates_lists)
    {
        double last_distance = coordinate_calculation::great_circle_distance(
            input_coords[0],
            input_coords[1]);
        sub_trace_lengths.resize(input_coords.size());
        sub_trace_lengths[0] = 0;
        for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size()))
        {
            bool allow_uturn = false;
            if (0 < current_coordinate)
            {
                last_distance = coordinate_calculation::great_circle_distance(
                    input_coords[current_coordinate - 1],
                    input_coords[current_coordinate]);
                sub_trace_lengths[current_coordinate] += sub_trace_lengths[current_coordinate-1] + last_distance;
            }

            if (input_coords.size()-1 > current_coordinate && 0 < current_coordinate)
            {
                double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
                                                    input_coords[current_coordinate-1],
                                                    input_coords[current_coordinate],
                                                    input_coords[current_coordinate+1]);

                // sharp turns indicate a possible uturn
                if (turn_angle < 100.0 || turn_angle > 260.0)
                {
                    allow_uturn = true;
                }
            }

            std::vector<std::pair<PhantomNode, double>> candidates;
            if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance(
                    input_coords[current_coordinate],
                    candidates,
                    last_distance/2.0,
                    5,
                    Matching::max_number_of_candidates))
            {
                return false;
            }

            if (allow_uturn)
            {
                candidates_lists.push_back(candidates);
            }
            else
            {
                unsigned compact_size = candidates.size();
                for (const auto i : osrm::irange(0u, compact_size))
                {
                    // Split edge if it is bidirectional and append reverse direction to end of list
                    if (candidates[i].first.forward_node_id != SPECIAL_NODEID
                     && candidates[i].first.reverse_node_id != SPECIAL_NODEID)
                    {
                        PhantomNode reverse_node(candidates[i].first);
                        reverse_node.forward_node_id = SPECIAL_NODEID;
                        candidates.push_back(std::make_pair(reverse_node, candidates[i].second));

                        candidates[i].first.reverse_node_id = SPECIAL_NODEID;
                    }
                }
                candidates_lists.push_back(candidates);
            }

        }

        return true;
    }

    int HandleRequest(const RouteParameters &route_parameters, JSON::Object &json_result) final
    {
        // check number of parameters
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            return 400;
        }

        std::vector<double> sub_trace_lengths;
        Matching::CandidateLists candidates_lists;
        const auto& input_coords = route_parameters.coordinates;
        bool found_candidates = get_candiates(input_coords, sub_trace_lengths, candidates_lists);
        if (!found_candidates)
        {
            return 400;
        }

        // call the actual map matching
        JSON::Object debug_info;
        Matching::SubMatchingList sub_matchings;
        search_engine_ptr->map_matching(candidates_lists, input_coords, sub_matchings, debug_info);

        if (1 > sub_matchings.size())
        {
            return 400;
        }

        JSON::Array traces;
        for (auto& sub : sub_matchings)
        {
            // classify result
            double trace_length = sub_trace_lengths[sub.end_idx-1] - sub_trace_lengths[sub.begin_idx];
            TraceClassification classification = classify(trace_length,
                                                          sub.length,
                                                          (sub.end_idx - sub.begin_idx) - sub.nodes.size());
            if (classification.first == ClassifierT::ClassLabel::POSITIVE)
            {
                sub.confidence = classification.second;
            }
            else
            {
                sub.confidence = 1-classification.second;
            }

            // FIXME this is a pretty bad hack. Geometries should obtained directly
            // from map_matching.
            // run shortest path routing to obtain geometry
            InternalRouteResult raw_route;
            PhantomNodes current_phantom_node_pair;
            for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
            {
                current_phantom_node_pair.source_phantom = sub.nodes[i];
                current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
                raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
            }
            search_engine_ptr->shortest_path(
                raw_route.segment_end_coordinates,
                std::vector<bool>(raw_route.segment_end_coordinates.size(), true),
                raw_route);

            DescriptorConfig descriptor_config;

            auto iter = descriptor_table.find(route_parameters.output_format);
            unsigned descriptor_type = (iter != descriptor_table.end() ? iter->second : 0);

            descriptor_config.zoom_level = route_parameters.zoom_level;
            descriptor_config.instructions = false;
            descriptor_config.geometry = route_parameters.geometry;
            descriptor_config.encode_geometry = route_parameters.compression;

            std::shared_ptr<BaseDescriptor<DataFacadeT>> descriptor;
            switch (descriptor_type)
            {
            // case 0:
            //     descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>();
            //     break;
            case 1:
                descriptor = std::make_shared<GPXDescriptor<DataFacadeT>>(facade);
                break;
            // case 2:
            //      descriptor = std::make_shared<GEOJSONDescriptor<DataFacadeT>>();
            //      break;
            default:
                descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(facade);
                break;
            }

            JSON::Object temp_result;
            descriptor->SetConfig(descriptor_config);
            descriptor->Run(raw_route, temp_result);

            JSON::Object subtrace;
            // via_route compability
            subtrace.values["route_geometry"] = temp_result.values["route_geometry"];
            subtrace.values["confidence"] = sub.confidence;
            subtrace.values["via_indicies"] = temp_result.values["via_indicies"];
            subtrace.values["via_points"] = temp_result.values["via_points"];

            traces.values.push_back(subtrace);
        }

        json_result.values["debug"] = debug_info;
        json_result.values["traces"] = traces;

        return 200;
    }

  private:
    std::string descriptor_string;
    DataFacadeT *facade;
    ClassifierT classifier;
};

#endif /* MAP_MATCHING_PLUGIN_H */
<commit_msg>Simplify matching response<commit_after>    /*
        open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#ifndef MAP_MATCHING_PLUGIN_H
#define MAP_MATCHING_PLUGIN_H

#include "plugin_base.hpp"

#include "../algorithms/bayes_classifier.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../util/integer_range.hpp"
#include "../data_structures/search_engine.hpp"
#include "../routing_algorithms/map_matching.hpp"
#include "../util/compute_angle.hpp"
#include "../util/simple_logger.hpp"
#include "../util/string_util.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/gpx_descriptor.hpp"
#include "../descriptors/json_descriptor.hpp"

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
  private:
    std::unordered_map<std::string, unsigned> descriptor_table;
    std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

    using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>;
    using TraceClassification = ClassifierT::ClassificationT;

  public:
    MapMatchingPlugin(DataFacadeT *facade)
    : descriptor_string("match")
    , facade(facade)
    // the values where derived from fitting a laplace distribution
    // to the values of manually classified traces
    , classifier(LaplaceDistribution(0.0057154021891018675, 0.020294704891166186),
                 LaplaceDistribution(0.11467696742821254, 0.49918444000368756),
                 0.7977883096366508) // valid apriori probability
    {
        descriptor_table.emplace("json", 0);
        search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
    }

    virtual ~MapMatchingPlugin() { search_engine_ptr.reset(); }

    const std::string GetDescriptor() const final { return descriptor_string; }

    TraceClassification classify(float trace_length, float matched_length, int removed_points) const
    {
        double distance_feature = -std::log(trace_length) + std::log(matched_length);

        // matched to the same point
        if (!std::isfinite(distance_feature))
        {
            return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
        }

        auto label_with_confidence =  classifier.classify(distance_feature);

        // "second stage classifier": if we need to remove points there is something fishy
        if (removed_points > 0)
        {
            return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
        }

        return label_with_confidence;
    }

    bool get_candiates(const std::vector<FixedPointCoordinate>& input_coords, std::vector<double>& sub_trace_lengths, Matching::CandidateLists& candidates_lists)
    {
        double last_distance = coordinate_calculation::great_circle_distance(
            input_coords[0],
            input_coords[1]);
        sub_trace_lengths.resize(input_coords.size());
        sub_trace_lengths[0] = 0;
        for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size()))
        {
            bool allow_uturn = false;
            if (0 < current_coordinate)
            {
                last_distance = coordinate_calculation::great_circle_distance(
                    input_coords[current_coordinate - 1],
                    input_coords[current_coordinate]);
                sub_trace_lengths[current_coordinate] += sub_trace_lengths[current_coordinate-1] + last_distance;
            }

            if (input_coords.size()-1 > current_coordinate && 0 < current_coordinate)
            {
                double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
                                                    input_coords[current_coordinate-1],
                                                    input_coords[current_coordinate],
                                                    input_coords[current_coordinate+1]);

                // sharp turns indicate a possible uturn
                if (turn_angle < 100.0 || turn_angle > 260.0)
                {
                    allow_uturn = true;
                }
            }

            std::vector<std::pair<PhantomNode, double>> candidates;
            if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance(
                    input_coords[current_coordinate],
                    candidates,
                    last_distance/2.0,
                    5,
                    Matching::max_number_of_candidates))
            {
                return false;
            }

            if (allow_uturn)
            {
                candidates_lists.push_back(candidates);
            }
            else
            {
                unsigned compact_size = candidates.size();
                for (const auto i : osrm::irange(0u, compact_size))
                {
                    // Split edge if it is bidirectional and append reverse direction to end of list
                    if (candidates[i].first.forward_node_id != SPECIAL_NODEID
                     && candidates[i].first.reverse_node_id != SPECIAL_NODEID)
                    {
                        PhantomNode reverse_node(candidates[i].first);
                        reverse_node.forward_node_id = SPECIAL_NODEID;
                        candidates.push_back(std::make_pair(reverse_node, candidates[i].second));

                        candidates[i].first.reverse_node_id = SPECIAL_NODEID;
                    }
                }
                candidates_lists.push_back(candidates);
            }

        }

        return true;
    }

    int HandleRequest(const RouteParameters &route_parameters, JSON::Object &json_result) final
    {
        // check number of parameters
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            return 400;
        }

        std::vector<double> sub_trace_lengths;
        Matching::CandidateLists candidates_lists;
        const auto& input_coords = route_parameters.coordinates;
        bool found_candidates = get_candiates(input_coords, sub_trace_lengths, candidates_lists);
        if (!found_candidates)
        {
            return 400;
        }

        // call the actual map matching
        JSON::Object debug_info;
        Matching::SubMatchingList sub_matchings;
        search_engine_ptr->map_matching(candidates_lists, input_coords, sub_matchings, debug_info);

        if (1 > sub_matchings.size())
        {
            return 400;
        }

        JSON::Array traces;
        for (auto& sub : sub_matchings)
        {
            // classify result
            double trace_length = sub_trace_lengths[sub.end_idx-1] - sub_trace_lengths[sub.begin_idx];
            TraceClassification classification = classify(trace_length,
                                                          sub.length,
                                                          (sub.end_idx - sub.begin_idx) - sub.nodes.size());
            if (classification.first == ClassifierT::ClassLabel::POSITIVE)
            {
                sub.confidence = classification.second;
            }
            else
            {
                sub.confidence = 1-classification.second;
            }

            // FIXME this is a pretty bad hack. Geometries should obtained directly
            // from map_matching.
            // run shortest path routing to obtain geometry
            InternalRouteResult raw_route;
            PhantomNodes current_phantom_node_pair;
            for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
            {
                current_phantom_node_pair.source_phantom = sub.nodes[i];
                current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
                raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
            }
            search_engine_ptr->shortest_path(
                raw_route.segment_end_coordinates,
                std::vector<bool>(raw_route.segment_end_coordinates.size(), true),
                raw_route);

            DescriptorConfig descriptor_config;

            auto iter = descriptor_table.find(route_parameters.output_format);
            unsigned descriptor_type = (iter != descriptor_table.end() ? iter->second : 0);

            descriptor_config.zoom_level = route_parameters.zoom_level;
            descriptor_config.instructions = false;
            descriptor_config.geometry = route_parameters.geometry;
            descriptor_config.encode_geometry = route_parameters.compression;

            std::shared_ptr<BaseDescriptor<DataFacadeT>> descriptor;
            switch (descriptor_type)
            {
            // case 0:
            //     descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>();
            //     break;
            case 1:
                descriptor = std::make_shared<GPXDescriptor<DataFacadeT>>(facade);
                break;
            // case 2:
            //      descriptor = std::make_shared<GEOJSONDescriptor<DataFacadeT>>();
            //      break;
            default:
                descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(facade);
                break;
            }

            JSON::Object temp_result;
            descriptor->SetConfig(descriptor_config);
            descriptor->Run(raw_route, temp_result);

            JSON::Array input_points;
            for(const auto& n: sub.nodes) {
                JSON::Array coord;
                coord.values.emplace_back(n.location.lat / COORDINATE_PRECISION);
                coord.values.emplace_back(n.location.lon / COORDINATE_PRECISION);
                input_points.values.push_back(coord);
            }

            JSON::Object subtrace;
            subtrace.values["geometry"] = temp_result.values["route_geometry"];
            subtrace.values["confidence"] = sub.confidence;
            subtrace.values["input_points"] = input_points;
            subtrace.values["matched_points"] = temp_result.values["via_points"];

            traces.values.push_back(subtrace);
        }

        json_result.values["debug"] = debug_info;
        json_result.values["traces"] = traces;

        return 200;
    }

  private:
    std::string descriptor_string;
    DataFacadeT *facade;
    ClassifierT classifier;
};

#endif /* MAP_MATCHING_PLUGIN_H */
<|endoftext|>


<commit_before><commit_msg>fixed power on bug<commit_after><|endoftext|>


<commit_before><commit_msg>(The Eye): implement logging CPU1 load<commit_after><|endoftext|>


<commit_before>// Copyright 2015 Adam Grandquist

#include "./catch.hpp"
#include "./ReQL.hpp"

using namespace ReQL;

TEST_CASE("cpp connection", "[c++][connect]") {
  Connection conn;

  REQUIRE(conn.isOpen());

  const Types::array args({Query(std::string("libReQL"))});

  Cursor cur = db_create(args).run(conn);

  REQUIRE(cur.isOpen());

  Query res = cur.next();

  cur = db_drop(args).run(conn);
  res = cur.next();

  conn.close();

  REQUIRE(!conn.isOpen());
}
<commit_msg>Get all results from cursors.<commit_after>// Copyright 2015 Adam Grandquist

#include "./catch.hpp"
#include "./ReQL.hpp"

using namespace ReQL;

TEST_CASE("cpp connection", "[c++][connect]") {
  Connection conn;

  REQUIRE(conn.isOpen());

  const Types::array args({Query(std::string("libReQL"))});

  Cursor cur = db_create(args).run(conn);

  REQUIRE(cur.isOpen());

  Query res = cur.toVector();

  cur = db_drop(args).run(conn);
  res = cur.toVector();

  conn.close();

  REQUIRE(!conn.isOpen());
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "GeolocationService.h"
#include "Geoposition.h"
#include "GeolocationServiceMock.h"
#include "PositionError.h"

#include <wtf/CurrentTime.h>
#include <wtf/Assertions.h>

namespace WebCore {

#if !ENABLE(GEOLOCATION)
static GeolocationService* createGeolocationServiceNull(GeolocationServiceClient*)
{
    return 0;
}

GeolocationService::FactoryFunction* GeolocationService::s_factoryFunction = &createGeolocationServiceNull;
#endif

GeolocationService* GeolocationService::create(GeolocationServiceClient* client)
{
    return (*s_factoryFunction)(client);
}

void GeolocationService::useMock()
{
    s_factoryFunction = &GeolocationServiceMock::create;
}

GeolocationService::GeolocationService(GeolocationServiceClient* client)
    : m_geolocationServiceClient(client)
{
    ASSERT(m_geolocationServiceClient);
}

void GeolocationService::positionChanged()
{
    m_geolocationServiceClient->geolocationServicePositionChanged(this);
}

void GeolocationService::errorOccurred()
{
    m_geolocationServiceClient->geolocationServiceErrorOccurred(this);
}

} // namespace WebCore
<commit_msg>Mac build fix.<commit_after>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "GeolocationService.h"
#include "Geoposition.h"
#include "GeolocationServiceMock.h"
#include "PositionError.h"

#include <wtf/CurrentTime.h>
#include <wtf/Assertions.h>

namespace WebCore {

#if !ENABLE(GEOLOCATION) || ENABLE(CLIENT_BASED_GEOLOCATION)
static GeolocationService* createGeolocationServiceNull(GeolocationServiceClient*)
{
    return 0;
}

GeolocationService::FactoryFunction* GeolocationService::s_factoryFunction = &createGeolocationServiceNull;
#endif

GeolocationService* GeolocationService::create(GeolocationServiceClient* client)
{
    return (*s_factoryFunction)(client);
}

void GeolocationService::useMock()
{
    s_factoryFunction = &GeolocationServiceMock::create;
}

GeolocationService::GeolocationService(GeolocationServiceClient* client)
    : m_geolocationServiceClient(client)
{
    ASSERT(m_geolocationServiceClient);
}

void GeolocationService::positionChanged()
{
    m_geolocationServiceClient->geolocationServicePositionChanged(this);
}

void GeolocationService::errorOccurred()
{
    m_geolocationServiceClient->geolocationServiceErrorOccurred(this);
}

} // namespace WebCore
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestSeedWidget2.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
//
// This example tests the vtkBorderWidget.

// First include the required header files for the VTK classes we are using.
#include "vtkSeedWidget.h"
#include "vtkSeedRepresentation.h"
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCommand.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
#include "vtkCoordinate.h"
#include "vtkMath.h"
#include "vtkHandleWidget.h"
#include "vtkPointHandleRepresentation2D.h"
#include "vtkAxisActor2D.h"
#include "vtkProperty2D.h"
#include "vtkVolume16Reader.h"
#include "vtkImageMapToColors.h"
#include "vtkImageActor.h"
#include "vtkLookupTable.h"

// This callback is responsible for setting the seed label.
class vtkSeedCallback : public vtkCommand
{
public:
  static vtkSeedCallback *New()
    { return new vtkSeedCallback; }
  virtual void Execute(vtkObject*, unsigned long, void*)
    {
      cout << "point placed\n";
    }
};

// The actual test function
int TestSeedWidget2( int argc, char *argv[] )
{
  // Create the RenderWindow, Renderer and both Actors
  //
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  // Create a test pipeline
  //
  // Start by creatin a black/white lookup table.
  vtkLookupTable *bwLut = vtkLookupTable::New();
    bwLut->SetTableRange (0, 2000);
    bwLut->SetSaturationRange (0, 0);
    bwLut->SetHueRange (0, 0);
    bwLut->SetValueRange (0, 1);
    bwLut->Build(); //effective built
  vtkVolume16Reader *v16 = vtkVolume16Reader::New();
    v16->SetDataDimensions(64,64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetFilePrefix ("c:/D/VTK/VTKData/Data/headsq/quarter");
    v16->SetImageRange(1, 93);
    v16->SetDataSpacing (3.2, 3.2, 1.5);
  vtkImageMapToColors *saggitalColors = vtkImageMapToColors::New();
    saggitalColors->SetInputConnection(v16->GetOutputPort());
    saggitalColors->SetLookupTable(bwLut);
  vtkImageActor *saggital = vtkImageActor::New();
    saggital->SetInput(saggitalColors->GetOutput());
    saggital->SetDisplayExtent(32,32, 0,63, 0,92);

  // Create the widget and its representation
  vtkPointHandleRepresentation2D *handle = vtkPointHandleRepresentation2D::New();
  handle->GetProperty()->SetColor(1,0,0);
  vtkSeedRepresentation *rep = vtkSeedRepresentation::New();
  rep->SetHandleRepresentation(handle);

  vtkSeedWidget *widget = vtkSeedWidget::New();
  widget->SetInteractor(iren);
  widget->SetRepresentation(rep);

  vtkSeedCallback *mcbk = vtkSeedCallback::New();
  widget->AddObserver(vtkCommand::PlacePointEvent,mcbk);

  // Add the actors to the renderer, set the background and size
  //
  ren1->AddActor(saggital);
  ren1->SetBackground(0.1, 0.2, 0.4);
  renWin->SetSize(300, 300);

  // record events
  vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
  recorder->SetInteractor(iren);
  recorder->SetFileName("c:/record.log");
//  recorder->Record();
//  recorder->ReadFromInputStringOn();
//  recorder->SetInputString(eventLog);

  // render the image
  //
  iren->Initialize();
  renWin->Render();
  widget->On();
//  recorder->Play();

  // Remove the observers so we can go interactive. Without this the "-I"
  // testing option fails.
  recorder->Off();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  bwLut->Delete();
  v16->Delete();
  saggitalColors->Delete();
  saggital->Delete();
  handle->Delete();
  rep->Delete();
  widget->RemoveObserver(mcbk);
  mcbk->Delete();
  widget->Off();
  widget->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  recorder->Delete();

  return !retVal;
}
<commit_msg>BUG: fix filename<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestSeedWidget2.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
//
// This example tests the vtkBorderWidget.

// First include the required header files for the VTK classes we are using.
#include "vtkSeedWidget.h"
#include "vtkSeedRepresentation.h"
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCommand.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
#include "vtkCoordinate.h"
#include "vtkMath.h"
#include "vtkHandleWidget.h"
#include "vtkPointHandleRepresentation2D.h"
#include "vtkAxisActor2D.h"
#include "vtkProperty2D.h"
#include "vtkVolume16Reader.h"
#include "vtkImageMapToColors.h"
#include "vtkImageActor.h"
#include "vtkLookupTable.h"
#include "vtkTestUtilities.h"

// This callback is responsible for setting the seed label.
class vtkSeedCallback : public vtkCommand
{
public:
  static vtkSeedCallback *New()
    { return new vtkSeedCallback; }
  virtual void Execute(vtkObject*, unsigned long, void*)
    {
      cout << "point placed\n";
    }
};

// The actual test function
int TestSeedWidget2( int argc, char *argv[] )
{
  // Create the RenderWindow, Renderer and both Actors
  //
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  // Create a test pipeline
  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");

  // Start by creatin a black/white lookup table.
  vtkLookupTable *bwLut = vtkLookupTable::New();
    bwLut->SetTableRange (0, 2000);
    bwLut->SetSaturationRange (0, 0);
    bwLut->SetHueRange (0, 0);
    bwLut->SetValueRange (0, 1);
    bwLut->Build(); //effective built
  vtkVolume16Reader *v16 = vtkVolume16Reader::New();
    v16->SetDataDimensions(64,64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetFilePrefix(fname);
    v16->SetImageRange(1, 93);
    v16->SetDataSpacing (3.2, 3.2, 1.5);
  vtkImageMapToColors *saggitalColors = vtkImageMapToColors::New();
    saggitalColors->SetInputConnection(v16->GetOutputPort());
    saggitalColors->SetLookupTable(bwLut);
  vtkImageActor *saggital = vtkImageActor::New();
    saggital->SetInput(saggitalColors->GetOutput());
    saggital->SetDisplayExtent(32,32, 0,63, 0,92);

  // Create the widget and its representation
  vtkPointHandleRepresentation2D *handle = vtkPointHandleRepresentation2D::New();
  handle->GetProperty()->SetColor(1,0,0);
  vtkSeedRepresentation *rep = vtkSeedRepresentation::New();
  rep->SetHandleRepresentation(handle);

  vtkSeedWidget *widget = vtkSeedWidget::New();
  widget->SetInteractor(iren);
  widget->SetRepresentation(rep);

  vtkSeedCallback *mcbk = vtkSeedCallback::New();
  widget->AddObserver(vtkCommand::PlacePointEvent,mcbk);

  // Add the actors to the renderer, set the background and size
  //
  ren1->AddActor(saggital);
  ren1->SetBackground(0.1, 0.2, 0.4);
  renWin->SetSize(300, 300);

  // record events
  vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
  recorder->SetInteractor(iren);
  recorder->SetFileName("c:/record.log");
//  recorder->Record();
//  recorder->ReadFromInputStringOn();
//  recorder->SetInputString(eventLog);

  // render the image
  //
  iren->Initialize();
  renWin->Render();
  widget->On();
//  recorder->Play();

  // Remove the observers so we can go interactive. Without this the "-I"
  // testing option fails.
  recorder->Off();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  bwLut->Delete();
  v16->Delete();
  saggitalColors->Delete();
  saggital->Delete();
  handle->Delete();
  rep->Delete();
  widget->RemoveObserver(mcbk);
  mcbk->Delete();
  widget->Off();
  widget->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  recorder->Delete();

  return !retVal;
}
<|endoftext|>