Example #1
0
CubebStream::~CubebStream()
{
  SetRunning(false);
  cubeb_stream_destroy(m_stream);
  m_ctx.reset();
}
Example #2
0
void ExternalStreamHandler::run(void)
{
    QString    cmd;
    QString    result;
    QString    xon;
    QByteArray buffer;
    uint       len;

    RunProlog();

    LOG(VB_RECORD, LOG_INFO, LOC + "run(): begin");

    SetRunning(true, true, false);

    if (m_poll_mode)
        xon = QString("SendBytes:%1").arg(PACKET_SIZE);
    else
        xon = "XON";

    uint remainder = 0;
    while (_running_desired && !_error)
    {
        if (!IsOpen())
        {
            if (!Open())
            {
                LOG(VB_RECORD, LOG_WARNING, LOC + QString("TS not open yet: %1")
                    .arg(m_error));
                usleep(750000);
                continue;
            }
        }

        if (StreamingCount() == 0)
        {
            usleep(5000);
            continue;
        }

        UpdateFiltersFromStreamData();

        ProcessCommand(xon, 1000, result);
        if (result.startsWith("ERR"))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + QString("Aborting: %1 -> %2")
                .arg(xon).arg(result));
            _error = true;
        }

        while ((len = m_IO->Read(buffer, PACKET_SIZE, 10)) > 0 ||
               buffer.size() > 188*50)
        {
            if (m_IO->Error())
            {
                m_error = m_IO->ErrorString();
                _error = true;
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Failed to read from Extern recorder: %1")
                    .arg(m_error));
                break;
            }

            if (!_running_desired)
                break;

            if (!_listener_lock.tryLock())
                continue;

            if (_stream_data_list.empty())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "_stream_data_list is empty");
                _listener_lock.unlock();
                continue;
            }

            if (!m_poll_mode)
            {
                ProcessCommand(QString("XOFF"), 50, result);
                if (result.startsWith("ERR"))
                {
                    LOG(VB_GENERAL, LOG_ERR, LOC + QString("Aborting: %1 -> %2")
                        .arg(xon).arg(result));
                    _error = true;
                }
            }

            StreamDataList::const_iterator sit = _stream_data_list.begin();
            for (; sit != _stream_data_list.end(); ++sit)
                remainder = sit.key()->ProcessData
                            (reinterpret_cast<const uint8_t *>
                             (buffer.constData()), buffer.size());

            _listener_lock.unlock();

            len = buffer.size();

            if (m_replay)
            {
                m_replay_buffer += buffer.left(len - remainder);
                if (m_replay_buffer.size() > (5000 * PACKET_SIZE))
                {
                    m_replay_buffer.remove(0, len - remainder);
                    LOG(VB_RECORD, LOG_WARNING, LOC +
                        QString("Replay size truncated to %1 bytes")
                        .arg(m_replay_buffer.size()));
                }
            }

            if (remainder > 0 && (len > remainder)) // leftover bytes
                buffer.remove(0, len - remainder);
            else
                buffer.clear();
        }
        usleep(10);
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "run(): " + "shutdown");

    RemoveAllPIDFilters();
    SetRunning(false, true, false);

    LOG(VB_RECORD, LOG_INFO, LOC + "run(): " + "end");

    RunEpilog();
}
Example #3
0
void Game::Quit(void) {
  SetRunning(false);
  delete _titleScreen;
}
Example #4
0
void HDHRStreamHandler::Run(void)
{
    SetRunning(true);
    RunTS();
}
Example #5
0
/** \fn HDHRStreamHandler::run(void)
 *  \brief Reads HDHomeRun socket for tables & data
 */
void HDHRStreamHandler::run(void)
{
    RunProlog();
    /* Create TS socket. */
    if (!hdhomerun_device_stream_start(_hdhomerun_device))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "Starting recording (set target failed). Aborting.");
        _error = true;
        RunEpilog();
        return;
    }
    hdhomerun_device_stream_flush(_hdhomerun_device);

    SetRunning(true, false, false);

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): begin");

    int remainder = 0;
    QTime last_update;
    while (_running_desired && !_error)
    {
        int elapsed = !last_update.isValid() ? -1 : last_update.elapsed();
        elapsed = (elapsed < 0) ? 1000 : elapsed;
        if (elapsed > 100)
        {
            UpdateFiltersFromStreamData();
            if (_tune_mode != hdhrTuneModeVChannel)
                UpdateFilters();
            last_update.restart();
        }

        size_t read_size = 64 * 1024; // read about 64KB
        read_size /= VIDEO_DATA_PACKET_SIZE;
        read_size *= VIDEO_DATA_PACKET_SIZE;

        size_t data_length;
        unsigned char *data_buffer = hdhomerun_device_stream_recv(
            _hdhomerun_device, read_size, &data_length);

        if (!data_buffer)
        {
            usleep(20000);
            continue;
        }

        // Assume data_length is a multiple of 188 (packet size)

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData(data_buffer, data_length);

        _listener_lock.unlock();
        if (remainder != 0)
        {
            LOG(VB_RECORD, LOG_INFO, LOC +
                QString("RunTS(): data_length = %1 remainder = %2")
                    .arg(data_length).arg(remainder));
        }
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "shutdown");

    RemoveAllPIDFilters();

    hdhomerun_device_stream_stop(_hdhomerun_device);
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "end");

    SetRunning(false, false, false);
    RunEpilog();
}
Example #6
0
void CMapFileFinderBase::RunL()
{
    switch (iStatus.Int()) {
    case KErrNone:
        switch (iDIState) {
        case EFindFiles:
            if (!iFirstFile && iDirList && iDirList->Count() > 0) {
                // We have done at least one search, we can
                // remove item 0 in iDirList and continue
                // searching in next dir.
                iDirList->Delete(0);
            }
            InternalFindFilesL();
            break;
        case EMoveFiles:
            // Report to the observer how many files that were found.
            ReportNbrMapFilesFound(iFileList ? iFileList->MdcaCount() : 0);
            // Search has been done in at least one
            // directory, move the files that were
            // found, one at a time.
            InternalMoveFiles();
            break;
        case EAddCacheFile:
            AddCacheFile();
            break;
        case EFileCacheAdded:
            if (iFileList && iFileList->Count() > 0) {
                // Delete the recently moved file from the
                // file list. Continue moving the next file.
                iFileList->Delete(0);
            }
            InternalMoveFiles();
            break;
        case EFileManMoveError:
            if (iFileList && iFileList->Count() > 0) {
                // Delete the file that couldnt be moved
                // and continue with the next one.
                iFileList->Delete(0);
            }
            InternalMoveFiles();
            break;
        case EFindAndMoveFilesRequestCompleted:
            SetRunning(EFalse);
            FindAndMoveFilesRequestCompleted();
            break;
        case ERequestDenied:
            SignalMapFileFinderBusy();
            break;
        case ECancelRequest:
            RequestAborted();
            break;
        case EDeleteFileFailed:
        case EFileDeleted:
            DeleteFileRequestCompleted(iState);
            break;
        case ECopyFileFailed:
        case EFileCopied:
            CopyFileRequestCompleted(iState);
            break;
        }
        break;
    case KErrPathNotFound:
    case KErrInUse:
        // Either a path is wrong or a file is in
        // use. We should try with the next one, or
        // should we inform the user that an error
        // has occured?
        iDIState = EFileCacheAdded;
        CompleteRequest(KErrNone);
        break;
    default:
        RequestAborted();
        break;
    }
}
Example #7
0
bool CViewer::ExecuteFreeModeAction(float _fDeltaSeconds, float _fDelta, const char* _pcAction)
{
  if(strcmp(_pcAction, "Run") == 0)
  {
    SetRunning();
    return true;
  }

  if(strcmp(_pcAction, "MoveFwd") == 0)
  {
    MoveFwd();
	
    return true;
  }

 if(strcmp(_pcAction, "MoveBack") == 0)
  {
    MoveBack();
	
    return true;
  }

  if(strcmp(_pcAction, "MoveLeft") == 0)
  {
    MoveLeft();
	
    return true;
  }

  if(strcmp(_pcAction, "MoveRight") == 0)
  {
    MoveRight();
	
    return true;
  }

  if(strcmp(_pcAction, "MoveUp") == 0)
  {
    m_bMoveUp = true;
	
    return true;
  }

  if(strcmp(_pcAction, "MoveDown") == 0)
  {
    m_bMoveDown = true;
	
    return true;
  }

  //if(strcmp(_pcAction, "AugmentaAmbient") == 0)
  //{
  //  IncrementAmbientLight();
  //  return true;
  //}

  //if(strcmp(_pcAction, "DisminueixAmbient") == 0)
  //{
  //  DecrementAmbientLight();
  //  return true;
  //}

  //if(strcmp(_pcAction, "ShootBOT") == 0)
  //{
  //  if(m_pCharacter)
  //  {
  //    CRenderableAnimatedInstanceModel* l_pAnim = (CRenderableAnimatedInstanceModel*)m_pCharacter;
  //    l_pAnim->GetAnimatedInstanceModel()->ExecuteAction(3,1);
  //  }

  //  return true;
  //}

  //if(strcmp(_pcAction, "AimBot") == 0)
  //{
  //  if(m_pCharacter)
  //  {
  //    CRenderableAnimatedInstanceModel* l_pAnim = (CRenderableAnimatedInstanceModel*)m_pCharacter;
  //    if ((l_pAnim->GetAnimatedInstanceModel()->GetCurrentCycle() == 1) ||
		//  (l_pAnim->GetAnimatedInstanceModel()->GetCurrentCycle() == 0))
  //    {
  //      l_pAnim->GetAnimatedInstanceModel()->ClearCycle(0.5f);
  //      l_pAnim->GetAnimatedInstanceModel()->BlendCycle(2,0.5f);
  //    }
  //    else if (l_pAnim->GetAnimatedInstanceModel()->GetCurrentCycle() == 2)
  //    {
  //      l_pAnim->GetAnimatedInstanceModel()->ClearCycle(0.5f);
  //      l_pAnim->GetAnimatedInstanceModel()->BlendCycle(1,0.5f);
  //    }
  //  }

  //  return true;
  //}

  return false;
}
void IPTVStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, LOC + "run()");

    SetRunning(true, false, false);

    // TODO Error handling..

    // Setup
    CetonRTSP *rtsp = nullptr;
    IPTVTuningData tuning = m_tuning;
    if(m_tuning.IsRTSP())
    {
        rtsp = new CetonRTSP(m_tuning.GetURL(0));

        // Check RTSP capabilities
        QStringList options;
        if (!(rtsp->GetOptions(options)     && options.contains("DESCRIBE") &&
              options.contains("SETUP")     && options.contains("PLAY")     &&
              options.contains("TEARDOWN")))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP interface did not support the necessary options");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        if (!rtsp->Describe())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP Describe command failed");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        m_use_rtp_streaming = true;

        QUrl urltuned = m_tuning.GetURL(0);
        urltuned.setScheme("rtp");
        urltuned.setPort(0);
        tuning = IPTVTuningData(urltuned.toString(), 0, IPTVTuningData::kNone,
                                urltuned.toString(), 0, "", 0);
    }

    bool error = false;

    int start_port = 0;
    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        QUrl url = tuning.GetURL(i);
        if (url.port() < 0)
            continue;

        LOG(VB_RECORD, LOG_DEBUG, LOC +
            QString("setting up url[%1]:%2").arg(i).arg(url.toString()));

        // always ensure we use consecutive port numbers
        int port = start_port ? start_port + 1 : url.port();
        QString host = url.host();
        QHostAddress dest_addr(host);

        if (!host.isEmpty() && dest_addr.isNull())
        {
            // address is a hostname, attempts to resolve it
            QHostInfo info = QHostInfo::fromName(host);
            QList<QHostAddress> list = info.addresses();

            if (list.isEmpty())
            {
                LOG(VB_RECORD, LOG_ERR, LOC +
                    QString("Can't resolve hostname:'%1'").arg(host));
            }
            else
            {
                for (int j=0; j < list.size(); j++)
                {
                    dest_addr = list[j];
                    if (list[j].protocol() == QAbstractSocket::IPv6Protocol)
                    {
                        // We prefer first IPv4
                        break;
                    }
                }
                LOG(VB_RECORD, LOG_DEBUG, LOC +
                    QString("resolved %1 as %2").arg(host).arg(dest_addr.toString()));
            }
        }
        bool ipv6 = dest_addr.protocol() == QAbstractSocket::IPv6Protocol;
        bool is_multicast = ipv6 ?
            dest_addr.isInSubnet(QHostAddress::parseSubnet("ff00::/8")) :
            (dest_addr.toIPv4Address() & 0xf0000000) == 0xe0000000;

        m_sockets[i] = new QUdpSocket();
        if (!is_multicast)
        {
            // this allow to filter incoming traffic, and make sure it's from
            // the requested server
            m_sender[i] = dest_addr;
        }
        m_read_helpers[i] = new IPTVStreamHandlerReadHelper(
            this, m_sockets[i], i);

        // we need to open the descriptor ourselves so we
        // can set some socket options
        int fd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0); // create IPv4 socket
        if (fd < 0)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "Unable to create socket " + ENO);
            continue;
        }
        int buf_size = 2 * 1024 * max(tuning.GetBitrate(i)/1000, 500U);
        if (!tuning.GetBitrate(i))
            buf_size = 2 * 1024 * 1024;
        int err = setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
                            (char *)&buf_size, sizeof(buf_size));
        if (err)
        {
            LOG(VB_GENERAL, LOG_INFO, LOC +
                QString("Increasing buffer size to %1 failed")
                .arg(buf_size) + ENO);
        }

        m_sockets[i]->setSocketDescriptor(
            fd, QAbstractSocket::UnconnectedState, QIODevice::ReadOnly);

        // we bind to destination address if it's a multicast address, or
        // the local ones otherwise
        if (!m_sockets[i]->bind(is_multicast ?
                                dest_addr :
                                (ipv6 ? QHostAddress::AnyIPv6 : QHostAddress::Any),
                                port))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Binding to port failed.");
            error = true;
        }
        else
        {
            start_port = m_sockets[i]->localPort();
        }

        if (is_multicast)
        {
            m_sockets[i]->joinMulticastGroup(dest_addr);
            LOG(VB_GENERAL, LOG_INFO, LOC + QString("Joining %1")
                .arg(dest_addr.toString()));
        }

        if (!is_multicast && rtsp && i == 1)
        {
            m_rtcp_dest = dest_addr;
        }
    }

    if (!error)
    {
        if (m_tuning.IsRTP() || m_tuning.IsRTSP())
            m_buffer = new RTPPacketBuffer(tuning.GetBitrate(0));
        else
            m_buffer = new UDPPacketBuffer(tuning.GetBitrate(0));
        m_write_helper =
            new IPTVStreamHandlerWriteHelper(this);
        m_write_helper->Start();
    }

    if (!error && rtsp)
    {
        // Start Streaming
        if (!rtsp->Setup(m_sockets[0]->localPort(), m_sockets[1]->localPort(),
                         m_rtsp_rtp_port, m_rtsp_rtcp_port, m_rtsp_ssrc) ||
            !rtsp->Play())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (RTP initialization failed). Aborting.");
            error = true;
        }
        if (m_rtsp_rtcp_port > 0)
        {
            m_write_helper->SendRTCPReport();
            m_write_helper->StartRTCPRR();
        }
    }

    if (!error)
    {
        // Enter event loop
        exec();
    }

    // Clean up
    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        if (m_sockets[i])
        {
            delete m_sockets[i];
            m_sockets[i] = nullptr;
            delete m_read_helpers[i];
            m_read_helpers[i] = nullptr;
        }
    }
    delete m_buffer;
    m_buffer = nullptr;
    delete m_write_helper;
    m_write_helper = nullptr;

    if (rtsp)
    {
        rtsp->Teardown();
        delete rtsp;
    }

    SetRunning(false, false, false);
    RunEpilog();
}
Example #9
0
/** \brief Initializers the event handlers
 *
 * \return void
 *
 */
void CShooterGame::InitHandlers() {

    ///////////////////////////////////////////////////
    //
    // On User Events
    //
    ///////////////////////////////////////////////////
    m_Handlers["OnUserEvent"] = {
        {
            //
            // STATE::SPLASH_SCREEN
            //
            (int)STATE::SPLASH_SCREEN,
            [&](SDL_Event& ev){
                int nEventType = ev.user.code;
                if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) {
                    int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nScene ) {
                    case SCENE_0_Intro:
                        //
                        // SCENE::INTRO
                        //
                        if ( nState == (int)SceneSplashScreen::STATE::FADE_OUT )
                        {
                            if ( !CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) ) {
                                LoadAndRunScene( SCENE_1_Game );
                                SetState( (int)STATE::GAME );
                            }
                        }
                        if ( nState == (int)SceneSplashScreen::STATE::END )
                        {
                            if ( CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) ) {
                                SetRunning( false );
                            }
                        }
                        break;
                    default:
                        break;

                    }

                }
                if ( nEventType == DemoEngine::EVENTTYPE::CUSTOM_EVENT ) {
                    int nEventID = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nEventID ) {
                    case (int)EVENT::START_NEW_GAME:
                        SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT );
                        LoadAndRunScene( SCENE_1_Game );
                        SetState( (int)STATE::GAME );
                        break;
                    case (int)EVENT::SHOW_HIGHSCORES:
                        SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT_NOMUSIC );
                        LoadAndRunScene( SCENE_3_Highscores );
                        SetState( (int)STATE::HIGHSCORES );
                        break;
                    case (int)EVENT::SHOW_HELP:
                        SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT_NOMUSIC );
                        LoadAndRunScene( SCENE_4_Help );
                        SetState( (int)STATE::HELP );
                        break;
                    case (int)EVENT::END_GAME:
                        SetSceneState( nScene, (int)SceneSplashScreen::STATE::PRE_FADE_OUT );
                        CSingleton<CProperties>::Instance()->Property( "Game", "Quit" ) = (bool)true;
                        break;
                    default:
                        break;
                    }

                }
            }
        },
        {
            //
            // STATE::HIGHSCORES
            //
            (int)STATE::HIGHSCORES,
            [&](SDL_Event& ev){
                int nEventType = ev.user.code;
                if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) {
                    int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nScene )
                    {
                    case SCENE_3_Highscores:
                        //
                        // SCENE::HELP
                        //
                        if ( nState == (int)SceneHighscores::STATE::FADE_OUT )
                        {
                            LoadAndRunScene( SCENE_0_Intro );
                            SetSceneState( SCENE_0_Intro, (int)SceneSplashScreen::STATE::START_NOMUSIC );
                            SetState( (int)STATE::SPLASH_SCREEN );
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        },
        {
            //
            // STATE::HELP
            //
            (int)STATE::HELP,
            [&](SDL_Event& ev){
                int nEventType = ev.user.code;
                if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) {
                    int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nScene )
                    {
                    case SCENE_4_Help:
                        //
                        // SCENE::HELP
                        //
                        if ( nState == (int)SceneHelp::STATE::FADE_OUT )
                        {
                            LoadAndRunScene( SCENE_0_Intro );
                            SetSceneState( SCENE_0_Intro, (int)SceneSplashScreen::STATE::START_NOMUSIC );
                            SetState( (int)STATE::SPLASH_SCREEN );
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        },
        {
            //
            // STATE::GAME
            //
            (int)STATE::GAME,
            [&](SDL_Event& ev){
                int nEventType = ev.user.code;
                if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) {
                    int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nScene )
                    {
                    case SCENE_1_Game:
                        //
                        // SCENE::GAME
                        //
                        if ( nState == (int)SceneLevel::STATE::FADE_OUT )
                        {
                            LoadAndRunScene( SCENE_2_GameOver );
                            SetState( (int)STATE::GAME_OVER );
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        },
        {
            //
            // STATE::GAME_OVER
            //
            (int)STATE::GAME_OVER,
            [&](SDL_Event& ev){
                int nEventType = ev.user.code;
                if ( nEventType == DemoEngine::EVENTTYPE::SCENE_EVENT ) {
                    int nState = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data1));
                    int nScene = static_cast<int>(reinterpret_cast<uintptr_t>(ev.user.data2));
                    switch ( nScene )
                    {
                    case SCENE_2_GameOver:
                        //
                        // SCENE::GAME_OVER
                        //
                        if ( nState == (int)SceneGameOver::STATE::FADE_OUT )
                        {
                            #ifdef DEBUG_SCENE1
                            cout << "Restarting Scene 1 because DEBUG_SCENE1 defined." << endl;
                            StopScene( SCENE_1_Game );
                            LoadAndRunScene( SCENE_1_Game );
                            SetState( (int)STATE::GAME );
                            #else
                            LoadAndRunScene( SCENE_0_Intro );
                            SetState( (int)STATE::SPLASH_SCREEN );
                            #endif
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    };

    ///////////////////////////////////////////////////
    //
    // Post Render
    //
    ///////////////////////////////////////////////////
    m_Handlers["PostRender"] = {
        {
            //
            // STATE::SPLASH_SCREEN
            //
            (int)CGame::STATE::ANY_STATE,
            [&](SDL_Event& ev){
                DISCARD_UNUNSED_PARAMETER( ev );

                auto& renderer = CSingleton<CRenderer>::Instance();
                int x = m_iScreenW + m_noteImgWidth - ((int)(GetRealTime()*60) % (m_iScreenW + m_noteImgWidth*2));
                renderer->Render( TextFactory::Instance()->Get( RESOURCE::TEXT_BETA_BUILD_NOTE ), x, m_iScreenH-12 );
            }
        }
    };

    ///////////////////////////////////////////////////
    //
    // OnKeyDown
    //
    ///////////////////////////////////////////////////
    m_Handlers["OnKeyDown"] = {
        {
            //
            // STATE::TESTS
            //
            (int)CGame::STATE::ANY_STATE,
            [&](SDL_Event& ev){
                switch ( ev.key.keysym.sym ) {
                    #ifdef DEBUG
                    case SDLK_1:
                        cout << "Setting Game speed to 0.1" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.1f;
                        break;
                    case SDLK_2:
                        cout << "Setting Game speed to 0.3" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.3f;
                        break;
                    case SDLK_3:
                        cout << "Setting Game speed to 0.5" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.5f;
                        break;
                    case SDLK_4:
                        cout << "Setting Game speed to 0.7" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)0.7f;
                        break;
                    case SDLK_5:
                        cout << "Setting Game speed to 1.0" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.0f;
                        break;
                    case SDLK_6:
                        cout << "Setting Game speed to 1.3" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.3f;
                        break;
                    case SDLK_7:
                        cout << "Setting Game speed to 1.5" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.5f;
                        break;
                    case SDLK_8:
                        cout << "Setting Game speed to 1.7" << endl;
                        CSingleton<CProperties>::Instance()->Property( "Game", "Speed" ) = (float)1.7f;
                        break;
                    #endif
                    case SDLK_F1:
                        cout << "Setting FPS to 10" << endl;
                        SDL_setFramerate( &m_fpsManager, 10 );
                        break;
                    case SDLK_F2:
                        cout << "Setting FPS to 20" << endl;
                        SDL_setFramerate( &m_fpsManager, 20 );
                        break;
                    case SDLK_F3:
                        cout << "Setting FPS to 30" << endl;
                        SDL_setFramerate( &m_fpsManager, 30 );
                        break;
                    case SDLK_F4:
                        cout << "Setting FPS to 40" << endl;
                        SDL_setFramerate( &m_fpsManager, 40 );
                        break;
                    case SDLK_F5:
                        cout << "Setting FPS to 50" << endl;
                        SDL_setFramerate( &m_fpsManager, 50 );
                        break;
                    case SDLK_F6:
                        cout << "Setting FPS to 60" << endl;
                        SDL_setFramerate( &m_fpsManager, 60 );
                        break;
                    case SDLK_F7:
                        cout << "Setting FPS to 120" << endl;
                        SDL_setFramerate( &m_fpsManager, 120 );
                        break;
                    default:
                        break;
                }
            }
        }
    };

}
void AAmethystCharacter::OnStopRunning()
{
	SetRunning(false, false);
}
Example #11
0
/** \fn HDHRStreamHandler::run(void)
 *  \brief Reads HDHomeRun socket for tables & data
 */
void HDHRStreamHandler::run(void)
{
    threadRegister("HDHRStreamHandler");
    /* Create TS socket. */
    if (!hdhomerun_device_stream_start(_hdhomerun_device))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "Starting recording (set target failed). Aborting.");
        _error = true;
	threadDeregister();
        return;
    }
    hdhomerun_device_stream_flush(_hdhomerun_device);

    SetRunning(true, false, false);

    /* Calculate buffer size */
    uint buffersize = gCoreContext->GetNumSetting(
        "HDRingbufferSize", 50 * TSPacket::kSize) * 1024;
    buffersize /= VIDEO_DATA_PACKET_SIZE;
    buffersize *= VIDEO_DATA_PACKET_SIZE;
    buffersize = max(49 * TSPacket::kSize * 128, buffersize);

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): begin");

    int remainder = 0;
    while (_running_desired && !_error)
    {
        UpdateFiltersFromStreamData();
        UpdateFilters();

        size_t read_size = 64 * 1024; // read about 64KB
        read_size /= VIDEO_DATA_PACKET_SIZE;
        read_size *= VIDEO_DATA_PACKET_SIZE;

        size_t data_length;
        unsigned char *data_buffer = hdhomerun_device_stream_recv(
            _hdhomerun_device, read_size, &data_length);

        if (!data_buffer)
        {
            usleep(5000);
            continue;
        }

        // Assume data_length is a multiple of 188 (packet size)

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData(data_buffer, data_length);

        _listener_lock.unlock();
        if (remainder != 0)
        {
            LOG(VB_RECORD, LOG_INFO, LOC +
                QString("RunTS(): data_length = %1 remainder = %2")
                    .arg(data_length).arg(remainder));
        }
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "shutdown");

    RemoveAllPIDFilters();

    hdhomerun_device_stream_stop(_hdhomerun_device);
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "end");

    SetRunning(false, false, false);
    threadDeregister();
}
void V4L2encStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_RECORD, LOG_INFO, LOC + "run() -- begin");

    if (!IsOpen())
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            "Starting stream handler, but v4l2 is not open!");
        if (!Open())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("run() -- Failed to open %1: ")
                .arg(_device) + ENO);
            _error = true;
            return;
        }
    }

#if 0
    // VBI
    if (m_vbi_fd >= 0)
        m_vbi_thread = new VBIThread(this);
#endif

    bool      good_data = false;
    bool      gap = false;
    QDateTime gap_start;

    int len, remainder = 0;

    QByteArray buffer;
    char* pkt_buf = new char[PACKET_SIZE + 1];

    SetRunning(true, true, false);

    while (_running_desired && !_error)
    {
        // Get V4L2 data
        if (m_streaming_cnt.load() == 0)
        {
            LOG(VB_RECORD, LOG_INFO, LOC + "Waiting for stream start.");
            QMutexLocker locker(&_start_stop_lock);
            _running_state_changed.wait(&_start_stop_lock, 5000);
            continue;
        }

        // Check for errors

        if (!m_drb)
            break;

        len = m_drb->Read(reinterpret_cast<unsigned char *>(pkt_buf),
                          PACKET_SIZE);
        if (m_drb->IsErrored())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "run() -- Device error detected");

            if (good_data)
            {
                if (gap)
                {
                    /* Already processing a gap, which means
                     * restarting the encoding didn't work! */
                    m_failing = true;
                }
                else
                    gap = true;
            }

            RestartEncoding();
        }
        else if (m_drb->IsEOF())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "run() -- Device EOF detected");
            _error = true;
        }
        else
        {
#if 0 // For this to work, the data needs to be propagated back up to
      // the 'recorder', but there could be multiple rcorders...

            // If we have seen good data, but now have a gap, note it
            if (good_data)
            {
                if (gap)
                {
                    QMutexLocker locker(&statisticsLock);
                    QDateTime gap_end(MythDate::current());

                    for (Irec = m_rec_gaps.begin();
                         Irec != m_rec_caps.end(); ++Irec)
                    {
                        (*Irec).push_back(RecordingGap
                                          (gap_start, gap_end));
                    }
                    LOG(VB_RECORD, LOG_DEBUG,
                        LOC + QString("Inserted gap %1 dur %2")
                        .arg(recordingGaps.back().toString())
                        .arg(gap_start.secsTo(gap_end)));
                    gap = false;
                }
                else
                    gap_start = MythDate::current();
            }
            else
                good_data = true;
#else
            good_data = true;
#endif
        }

        if (len < 0)
        {
            if (errno != EAGAIN)
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("run() -- error reading from: %1")
                    .arg(_device) + ENO);
            continue;
        }

        buffer.append(pkt_buf, len);
        len = buffer.size();

        if (len < static_cast<int>(TSPacket::kSize))
            continue;

        if (!_listener_lock.tryLock())
            continue;

        if (_stream_data_list.empty())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("run() -- _stream_data_list is empty, %1 buffered")
                .arg(buffer.size()));
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData
                        (reinterpret_cast<const uint8_t *>
                         (buffer.constData()), len);

        _listener_lock.unlock();

        if (remainder > 0 && (len > remainder)) // leftover bytes
            buffer.remove(0, len - remainder);
        else
            buffer.clear();
    }

    QString tmp(_error);
    LOG(VB_GENERAL, LOG_WARNING, LOC +
        QString("_running_desired(%1)  _error(%2)")
                .arg(_running_desired).arg(tmp));

    LOG(VB_RECORD, LOG_INFO, LOC + "run() -- finishing up");
    StopEncoding();

    delete[] pkt_buf;

    SetRunning(false, true, false);
    RunEpilog();

    LOG(VB_RECORD, LOG_INFO, LOC + "run() -- end");
}
Example #13
0
void
COpenGLDemo::OnQuit( SDL_QuitEvent & ev )
{
  SetRunning(false);
}
Example #14
0
void CTimer::Stop()
{
	SetRunning(false);
	DispatchStateMessage();
}
Example #15
0
void ANimModCharacter::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);

	if (bWantsToRunToggled && !IsRunning())
	{
		SetRunning(false, false);
	}
	ANimModPlayerController* MyPC = Cast<ANimModPlayerController>(Controller);
	if (MyPC)
	{
		if (MyPC->HasHealthRegen())
		{
			if (this->Health < this->GetMaxHealth())
			{
				this->Health += 5 * DeltaSeconds;
				if (Health > this->GetMaxHealth())
				{
					Health = this->GetMaxHealth();
				}
			}
		}

		if (!bWantsToFire)
		{
			if (PreviousViewPunchStep != FVector2D::ZeroVector /*&& CurrentViewPunchLERPCount < 10*/)
			{
				FVector2D nextViewPunchStep = FMath::Vector2DInterpConstantTo(PreviousViewPunchStep, FVector2D::ZeroVector, DeltaSeconds, 5.0f);
				FVector2D deltaStep = (PreviousViewPunchStep - nextViewPunchStep);
				AddViewPunch(-deltaStep);
				PreviousViewPunchStep = nextViewPunchStep;
			}
		}
		
		if (MyPC->GetPlayerTeamNumber() == ENimModTeam::ASSASSINS)
		{
			//FName parameterName = TEXT("NimMod_Opacity");
			//for (auto material : GetPawnMesh()->GetMaterials())
			//{
			//	if (material)
			//	{
			//		float TestValue; //not used but needed for GetScalarParameterValue call
			//		if (material->GetScalarParameterValue(parameterName, TestValue))
			//		{
			//			UMaterialInstanceDynamic* DynamicMaterial = Cast<UMaterialInstanceDynamic>(material);
			//			if (!DynamicMaterial) //Is it already a UMaterialInstanceDynamic (ie we used it last tick)
			//			{
			//				continue;
			//			}
			//			DynamicMaterial->SetScalarParameterValue(parameterName, 0.25);
			//			break;
			//		}
			//	}
			//}
		}
	}

	if (LowHealthSound && GEngine->UseSound())
	{
		if ((this->Health > 0 && this->Health < this->GetMaxHealth() * LowHealthPercentage) && (!LowHealthWarningPlayer || !LowHealthWarningPlayer->IsPlaying()))
		{
			LowHealthWarningPlayer = UGameplayStatics::PlaySoundAttached(LowHealthSound, GetRootComponent(),
				NAME_None, FVector(ForceInit), EAttachLocation::KeepRelativeOffset, true);
			LowHealthWarningPlayer->SetVolumeMultiplier(0.0f);
		}
		else if ((this->Health > this->GetMaxHealth() * LowHealthPercentage || this->Health < 0) && LowHealthWarningPlayer && LowHealthWarningPlayer->IsPlaying())
		{
			LowHealthWarningPlayer->Stop();
		}
		if (LowHealthWarningPlayer && LowHealthWarningPlayer->IsPlaying())
		{
			const float MinVolume = 0.3f;
			const float VolumeMultiplier = (1.0f - (this->Health / (this->GetMaxHealth() * LowHealthPercentage)));
			LowHealthWarningPlayer->SetVolumeMultiplier(MinVolume + (1.0f - MinVolume) * VolumeMultiplier);
		}
	}
}
Example #16
0
void IPTVStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, LOC + "run()");

    SetRunning(true, false, false);

    // TODO Error handling..

    // Setup
    CetonRTSP *rtsp = NULL;
    IPTVTuningData tuning = m_tuning;
    if (m_tuning.GetURL(0).scheme().toLower() == "rtsp")
    {
        rtsp = new CetonRTSP(m_tuning.GetURL(0));

        // Check RTSP capabilities
        QStringList options;
        if (!(rtsp->GetOptions(options)     && options.contains("OPTIONS")  &&
              options.contains("DESCRIBE")  && options.contains("SETUP")    &&
              options.contains("PLAY")      && options.contains("TEARDOWN")))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP interface did not support the necessary options");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        if (!rtsp->Describe())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP Describe command failed");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        tuning = IPTVTuningData(
            QString("rtp://%[email protected]%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            IPTVTuningData::kNone,
            QString("rtp://%[email protected]%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            "", 0);
    }

    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        QUrl url = tuning.GetURL(i);
        if (url.port() < 0)
            continue;

        m_sockets[i] = new QUdpSocket();
        m_read_helpers[i] = new IPTVStreamHandlerReadHelper(
            this, m_sockets[i], i);

        // we need to open the descriptor ourselves so we
        // can set some socket options
        int fd = socket(AF_INET, SOCK_DGRAM, 0); // create IPv4 socket
        if (fd < 0)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "Unable to create socket " + ENO);
            continue;
        }
        int buf_size = 2 * 1024 * max(tuning.GetBitrate(i)/1000, 500U);
        if (!tuning.GetBitrate(i))
            buf_size = 2 * 1024 * 1024;
        int ok = setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
                            (char *)&buf_size, sizeof(buf_size));
        if (ok)
        {
            LOG(VB_GENERAL, LOG_INFO, LOC +
                QString("Increasing buffer size to %1 failed")
                .arg(buf_size) + ENO);
        }
        /*
          int broadcast = 1;
          ok = setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
          (char *)&broadcast, sizeof(broadcast));
          if (ok)
          {
          LOG(VB_GENERAL, LOG_INFO, LOC +
          QString("Enabling broadcast failed") + ENO);
          }
        */
        m_sockets[i]->setSocketDescriptor(
            fd, QAbstractSocket::UnconnectedState, QIODevice::ReadOnly);

        m_sockets[i]->bind(QHostAddress::Any, url.port());

        QHostAddress dest_addr(tuning.GetURL(i).host());

        if (dest_addr != QHostAddress::Any)
        {
            //m_sockets[i]->joinMulticastGroup(dest_addr); // needs Qt 4.8
            LOG(VB_GENERAL, LOG_INFO, LOC + QString("Joining %1")
                .arg(dest_addr.toString()));
            struct ip_mreq imr;
            memset(&imr, 0, sizeof(struct ip_mreq));
            imr.imr_multiaddr.s_addr = inet_addr(
                dest_addr.toString().toLatin1().constData());
            imr.imr_interface.s_addr = htonl(INADDR_ANY);
            if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
				(const char *)&imr, sizeof(imr)) < 0)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    "setsockopt - IP_ADD_MEMBERSHIP " + ENO);
            }
        }

        if (!url.userInfo().isEmpty())
            m_sender[i] = QHostAddress(url.userInfo());
    }
    if (m_use_rtp_streaming)
        m_buffer = new RTPPacketBuffer(tuning.GetBitrate(0));
    else
        m_buffer = new UDPPacketBuffer(tuning.GetBitrate(0));
    m_write_helper = new IPTVStreamHandlerWriteHelper(this);
    m_write_helper->Start();

    bool error = false;
    if (rtsp)
    {
        // Start Streaming
        if (!rtsp->Setup(m_sockets[0]->localPort(),
                         m_sockets[1]->localPort()) ||
            !rtsp->Play())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (RTP initialization failed). Aborting.");
            error = true;
        }
    }

    if (!error)
    {
        // Enter event loop
        exec();
    }

    // Clean up
    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        if (m_sockets[i])
        {
            delete m_sockets[i];
            m_sockets[i] = NULL;
            delete m_read_helpers[i];
            m_read_helpers[i] = NULL;
        }
    }
    delete m_buffer;
    m_buffer = NULL;
    delete m_write_helper;
    m_write_helper = NULL;

    if (rtsp)
    {
        rtsp->Teardown();
        delete rtsp;
    }

    SetRunning(false, false, false);
    RunEpilog();
}
Example #17
0
void ANimModCharacter::ServerSetRunning_Implementation(bool bNewRunning, bool bToggle)
{
	SetRunning(bNewRunning, bToggle);
}
uint32 FBuildPatchFileConstructor::Run()
{
	SetRunning( true );
	SetInited( true );
	const bool bIsFileData = BuildManifest->IsFileDataManifest();

	// Save the list of completed files
	TArray< FString > ConstructedFiles;

	// Check for resume data
	FResumeData ResumeData( StagingDirectory, BuildManifest );

	// Start resume progress at zero or one
	BuildProgress->SetStateProgress( EBuildPatchProgress::Resuming, ResumeData.bHasResumeData ? 0.0f : 1.0f );

	// While we have files to construct, run
	FString FileToConstruct;
	while( GetFileToConstruct( FileToConstruct ) && !FBuildPatchInstallError::HasFatalError() )
	{
		// Check resume status, currently we are only supporting sequential resume, so once we start downloading, we can't resume any more.
		// this only comes up if the resume data has been changed externally.
		ResumeData.CheckFile( FileToConstruct );
		const bool bFilePreviouslyComplete = !bIsDownloadStarted && ResumeData.FilesCompleted.Contains( FileToConstruct );
		const bool bFilePreviouslyStarted = !bIsDownloadStarted && ResumeData.FilesStarted.Contains( FileToConstruct );

		// Construct or skip the file
		bool bFileSuccess;
		if( bFilePreviouslyComplete )
		{
			bFileSuccess = true;
			CountBytesProcessed( BuildManifest->GetFileSize( FileToConstruct ) );
			// Inform the chunk cache of the chunk skip
			if( !bIsFileData )
			{
				FBuildPatchChunkCache::Get().SkipFile( FileToConstruct );
			}
		}
		else
		{
			bFileSuccess = ConstructFileFromChunks( FileToConstruct, bFilePreviouslyStarted );
			// Add to resume data if successful or failure was not file construction fail
			if( bFileSuccess || FBuildPatchInstallError::GetErrorState() != EBuildPatchInstallError::FileConstructionFail )
			{
				ResumeData.FilesStarted.AddUnique( FileToConstruct );
			}
		}

		// If the file succeeded, add to lists
		if( bFileSuccess )
		{
			ConstructedFiles.Add( FileToConstruct );
		}
		else
		{
			GWarn->Logf( TEXT( "BuildPatchServices: ERROR: Failed to construct file %s" ), *FPaths::GetCleanFilename( FileToConstruct ) );
			FBuildPatchInstallError::SetFatalError( EBuildPatchInstallError::FileConstructionFail );
		}

		// Pause
		BuildProgress->WaitWhilePaused();
	}

	// Save resume data
	ResumeData.SaveOut();
	BuildProgress->SetStateProgress(EBuildPatchProgress::Resuming, 1.0f);

	// Set constructed files
	ThreadLock.Lock();
	FilesConstructed.Empty();
	FilesConstructed.Append( ConstructedFiles );
	ThreadLock.Unlock();

	SetRunning( false );
	return 0;
}
Example #19
0
void ASIStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_RECORD, LOG_INFO, LOC + "run(): begin");

    if (!Open())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Failed to open device %1 : %2")
                .arg(_device).arg(strerror(errno)));
        _error = true;
        return;
    }

    DeviceReadBuffer *drb = new DeviceReadBuffer(this, true, false);
    bool ok = drb->Setup(_device, _fd, _packet_size, _buf_size);
    if (!ok)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate DRB buffer");
        delete drb;
        drb = NULL;
        Close();
        _error = true;
        RunEpilog();
        return;
    }

    uint buffer_size = _packet_size * 15000;
    unsigned char *buffer = new unsigned char[buffer_size];
    if (!buffer)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate buffer");
        delete drb;
        drb = NULL;
        Close();
        _error = true;
        RunEpilog();
        return;
    }
    memset(buffer, 0, buffer_size);

    SetRunning(true, true, false);

    drb->Start();

    {
        QMutexLocker locker(&_start_stop_lock);
        _drb = drb;
    }

    int remainder = 0;
    while (_running_desired && !_error)
    {
        UpdateFiltersFromStreamData();

        ssize_t len = 0;

        len = drb->Read(
            &(buffer[remainder]), buffer_size - remainder);

        if (!_running_desired)
            break;

        // Check for DRB errors
        if (drb->IsErrored())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Device error detected");
            _error = true;
        }

        if (drb->IsEOF())
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Device EOF detected");
            _error = true;
        }

        if ((0 == len) || (-1 == len))
        {
            usleep(100);
            continue;
        }

        len += remainder;

        if (len < 10) // 10 bytes = 4 bytes TS header + 6 bytes PES header
        {
            remainder = len;
            continue;
        }

        if (!_listener_lock.tryLock())
        {
            remainder = len;
            continue;
        }

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData(buffer, len);

        if (_mpts != NULL)
            _mpts->Write(buffer, len - remainder);

        _listener_lock.unlock();

        if (remainder > 0 && (len > remainder)) // leftover bytes
            memmove(buffer, &(buffer[len - remainder]), remainder);
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "run(): " + "shutdown");

    RemoveAllPIDFilters();

    {
        QMutexLocker locker(&_start_stop_lock);
        _drb = NULL;
    }

    if (drb->IsRunning())
        drb->Stop();

    delete drb;
    delete[] buffer;
    Close();

    LOG(VB_RECORD, LOG_INFO, LOC + "run(): " + "end");

    SetRunning(false, true, false);
    RunEpilog();
}
uint32 FBuildPatchInstaller::Run()
{
    // Make sure this function can never be parallelized
    static FCriticalSection SingletonFunctionLockCS;
    FScopeLock SingletonFunctionLock(&SingletonFunctionLockCS);
    FBuildPatchInstallError::Reset();

    SetRunning(true);
    SetInited(true);
    SetDownloadSpeed(-1);
    UpdateDownloadProgressInfo(true);

    // Register the current manifest with the installation info, to make sure we pull from it
    if (CurrentBuildManifest.IsValid())
    {
        InstallationInfo.RegisterAppInstallation(CurrentBuildManifest.ToSharedRef(), InstallDirectory);
    }

    // Keep track of files that failed verify
    TArray<FString> CorruptFiles;

    // Init prereqs progress value
    const bool bInstallPrereqs = !CurrentBuildManifest.IsValid() && !NewBuildManifest->GetPrereqPath().IsEmpty();

    // Get the start time
    double StartTime = FPlatformTime::Seconds();
    double CleanUpTime = 0;

    // Keep retrying the install while it is not canceled, or caused by download error
    bool bProcessSuccess = false;
    bool bCanRetry = true;
    int32 InstallRetries = 5;
    while (!bProcessSuccess && bCanRetry)
    {
        // Run the install
        bool bInstallSuccess = RunInstallation(CorruptFiles);
        BuildProgress.SetStateProgress(EBuildPatchProgress::PrerequisitesInstall, bInstallPrereqs ? 0.0f : 1.0f);
        if (bInstallSuccess)
        {
            BuildProgress.SetStateProgress(EBuildPatchProgress::Downloading, 1.0f);
            BuildProgress.SetStateProgress(EBuildPatchProgress::Installing, 1.0f);
        }

        // Backup local changes then move generated files
        bInstallSuccess = bInstallSuccess && RunBackupAndMove();

        // Run Verification
        CorruptFiles.Empty();
        BuildProgress.SetStateProgress(EBuildPatchProgress::Initializing, 1.0f);
        bProcessSuccess = bInstallSuccess && RunVerification(CorruptFiles);

        // Clean staging if INSTALL success
        if (bInstallSuccess)
        {
            GLog->Logf(TEXT("BuildPatchServices: Deleting staging area"));
            CleanUpTime = FPlatformTime::Seconds();
            IFileManager::Get().DeleteDirectory(*StagingDirectory, false, true);
            CleanUpTime = FPlatformTime::Seconds() - CleanUpTime;
        }
        BuildProgress.SetStateProgress(EBuildPatchProgress::CleanUp, 1.0f);

        // Set if we can retry
        --InstallRetries;
        bCanRetry = InstallRetries > 0 && !FBuildPatchInstallError::IsInstallationCancelled() && !FBuildPatchInstallError::IsNoRetryError();

        // If successful or we will retry, remove the moved files marker
        if (bProcessSuccess || bCanRetry)
        {
            GLog->Logf(TEXT("BuildPatchServices: Reset MM"));
            IFileManager::Get().Delete(*PreviousMoveMarker, false, true);
        }
    }

    if (bProcessSuccess)
    {
        // Run the prerequisites installer if this is our first install and the manifest has prerequisites info
        if (bInstallPrereqs)
        {
            // @TODO: We also want to trigger prereq install if this is an update and the prereq installer differs in the update
            bProcessSuccess &= RunPrereqInstaller();
        }
    }

    // Set final stat values and log out results
    {
        FScopeLock Lock(&ThreadLock);
        bSuccess = bProcessSuccess;
        BuildStats.ProcessSuccess = bProcessSuccess;
        BuildStats.ProcessExecuteTime = (FPlatformTime::Seconds() - StartTime) - BuildStats.ProcessPausedTime;
        BuildStats.FailureReason = FBuildPatchInstallError::GetErrorString();
        BuildStats.FailureReasonText = FBuildPatchInstallError::GetErrorText();
        BuildStats.CleanUpTime = CleanUpTime;

        // Log stats
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: AppName: %s"), *BuildStats.AppName);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: AppInstalledVersion: %s"), *BuildStats.AppInstalledVersion);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: AppPatchVersion: %s"), *BuildStats.AppPatchVersion);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: CloudDirectory: %s"), *BuildStats.CloudDirectory);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumFilesInBuild: %u"), BuildStats.NumFilesInBuild);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumFilesOutdated: %u"), BuildStats.NumFilesOutdated);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumFilesToRemove: %u"), BuildStats.NumFilesToRemove);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumChunksRequired: %u"), BuildStats.NumChunksRequired);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: ChunksQueuedForDownload: %u"), BuildStats.ChunksQueuedForDownload);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: ChunksLocallyAvailable: %u"), BuildStats.ChunksLocallyAvailable);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumChunksDownloaded: %u"), BuildStats.NumChunksDownloaded);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumChunksRecycled: %u"), BuildStats.NumChunksRecycled);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumChunksCacheBooted: %u"), BuildStats.NumChunksCacheBooted);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumDriveCacheChunkLoads: %u"), BuildStats.NumDriveCacheChunkLoads);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumRecycleFailures: %u"), BuildStats.NumRecycleFailures);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: NumDriveCacheLoadFailures: %u"), BuildStats.NumDriveCacheLoadFailures);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: TotalDownloadedData: %lld"), BuildStats.TotalDownloadedData);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: AverageDownloadSpeed: %.3f MB/sec"), BuildStats.AverageDownloadSpeed / 1024.0 / 1024.0);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: TheoreticalDownloadTime: %s"), *FPlatformTime::PrettyTime(BuildStats.TheoreticalDownloadTime));
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: VerifyTime: %s"), *FPlatformTime::PrettyTime(BuildStats.VerifyTime));
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: CleanUpTime: %s"), *FPlatformTime::PrettyTime(BuildStats.CleanUpTime));
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: ProcessExecuteTime: %s"), *FPlatformTime::PrettyTime(BuildStats.ProcessExecuteTime));
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: ProcessPausedTime: %.1f sec"), BuildStats.ProcessPausedTime);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: ProcessSuccess: %s"), BuildStats.ProcessSuccess ? TEXT("TRUE") : TEXT("FALSE"));
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: FailureReason: %s"), *BuildStats.FailureReason);
        GLog->Logf(TEXT("BuildPatchServices: Build Stat: FailureReasonText: %s"), *BuildStats.FailureReasonText.BuildSourceString());
    }

    // Mark that we are done
    SetRunning(false);

    return bSuccess ? 0 : 1;
}
Example #21
0
LandsharkPaintball::~LandsharkPaintball()
{
  SetRunning( false );
  m_ThreadGroup.join_all();
  close(m_SocketFileDescriptor);
}
Example #22
0
void CTimer::Start(int start)
{
    m_iStartTick = start;
    SetRunning(true);
    DispatchStateMessage();
}
Example #23
0
/** \fn HDHRStreamHandler::RunTS(void)
 *  \brief Uses TS filtering devices to read a DVB device for tables & data
 *
 *  This supports all types of MPEG based stream data, but is extreemely
 *  slow with DVB over USB 1.0 devices which for efficiency reasons buffer
 *  a stream until a full block transfer buffer full of the requested
 *  tables is available. This takes a very long time when you are just
 *  waiting for a PAT or PMT table, and the buffer is hundreds of packets
 *  in size.
 */
void HDHRStreamHandler::RunTS(void)
{
    int remainder = 0;

    /* Calculate buffer size */
    uint buffersize = gCoreContext->GetNumSetting(
        "HDRingbufferSize", 50 * TSPacket::SIZE) * 1024;
    buffersize /= VIDEO_DATA_PACKET_SIZE;
    buffersize *= VIDEO_DATA_PACKET_SIZE;

    // Buffer should be at least about 1MB..
    buffersize = max(49 * TSPacket::SIZE * 128, buffersize);

    /* Create TS socket. */
    if (!hdhomerun_device_stream_start(_hdhomerun_device))
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR +
                "Starting recording (set target failed). Aborting.");
        return;
    }
    hdhomerun_device_stream_flush(_hdhomerun_device);

    bool _error = false;

    VERBOSE(VB_RECORD, LOC + "RunTS(): begin");

    while (IsRunning() && !_error)
    {
        UpdateFiltersFromStreamData();

        size_t read_size = 64 * 1024; // read about 64KB
        read_size /= VIDEO_DATA_PACKET_SIZE;
        read_size *= VIDEO_DATA_PACKET_SIZE;

        size_t data_length;
        unsigned char *data_buffer = hdhomerun_device_stream_recv(
            _hdhomerun_device, read_size, &data_length);

        if (!data_buffer)
        {
            usleep(5000);
            continue;
        }

        // Assume data_length is a multiple of 188 (packet size)

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        for (uint i = 0; i < _stream_data_list.size(); i++)
        {
            remainder = _stream_data_list[i]->ProcessData(
                data_buffer, data_length);
        }

        _listener_lock.unlock();
        if (remainder != 0)
        {
            VERBOSE(VB_RECORD, LOC +
                    QString("RunTS(): data_length = %1 remainder = %2")
                    .arg(data_length).arg(remainder));
        }
    }
    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "shutdown");

    RemoveAllPIDFilters();

    hdhomerun_device_stream_stop(_hdhomerun_device);
    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "end");

    SetRunning(false);
}
Example #24
0
void HLSStreamHandler::run(void)
{
    RunProlog();

    QString url = m_tuning.GetURL(0).toString();
    int err_cnt = 0;
    int nil_cnt = 0;
    int open_sleep = 500000;

    LOG(VB_GENERAL, LOG_INFO, LOC + "run() -- begin");

    SetRunning(true, false, false);

    if (!m_hls)
        return;
    m_hls->Throttle(false);

    int remainder = 0;
    while (_running_desired)
    {
        if (!m_hls->IsOpen(url))
        {
            if (!m_hls->Open(url, m_tuning.GetBitrate(0)))
            {
                if (m_hls->FatalError())
                    break;
                usleep(open_sleep);
                if (open_sleep < 20000000)
                    open_sleep += 500000;
                continue;
            }
            open_sleep = 500000;
            m_hls->Throttle(m_throttle);
            m_throttle = false;
        }

        int size = m_hls->Read(&m_readbuffer[remainder],
                               BUFFER_SIZE - remainder);

        size += remainder;

        if (size < 0)
        {
            // error
            if (++err_cnt > 10)
            {
                LOG(VB_RECORD, LOG_ERR, LOC + "HLSReader failed");
                Stop();
                break;
            }
            continue;
        }
        err_cnt = 0;

        if (size == 0)
        {
            if (nil_cnt < 4)
                ++nil_cnt;
            usleep(250000 * nil_cnt - 1);  // range .25 to 1 second, minus 1
            continue;
        }
        nil_cnt = 0;

        if (m_readbuffer[0] != 0x47)
        {
            LOG(VB_RECORD, LOG_INFO, LOC +
                QString("Packet not starting with SYNC Byte (got 0x%1)")
                .arg((char)m_readbuffer[0], 2, QLatin1Char('0')));
            continue;
        }

        {
            QMutexLocker locker(&_listener_lock);
            HLSStreamHandler::StreamDataList::const_iterator sit;
            sit = _stream_data_list.begin();
            for (; sit != _stream_data_list.end(); ++sit)
                remainder = sit.key()->ProcessData(m_readbuffer, size);
        }

        if (remainder > 0)
        {
            if (size > remainder) // unprocessed bytes
                memmove(m_readbuffer, &(m_readbuffer[size - remainder]),
                        remainder);

            LOG(VB_RECORD, LOG_INFO, LOC +
                QString("data_length = %1 remainder = %2")
                .arg(size).arg(remainder));
        }

        if (m_hls->IsThrottled())
            usleep(999999);
        else if (size < BUFFER_SIZE)
        {
            LOG(VB_RECORD, LOG_DEBUG, LOC +
                QString("Requested %1 bytes, got %2 bytes.")
                .arg(BUFFER_SIZE).arg(size));
            usleep(10000); // hundredth of a second.
        }
        else
            usleep(1000);
    }

    m_hls->Throttle(false);

    SetRunning(false, false, false);
    RunEpilog();

    LOG(VB_GENERAL, LOG_INFO, LOC + "run() -- done");
}
Example #25
0
void CetonStreamHandler::run(void)
{
    RunProlog();
    bool _error = false;

    QFile file(_device_path);
    CetonRTP rtp(_ip_address, _tuner);

    if (_using_rtp)
    {
        if (!(rtp.Init() && rtp.StartStreaming()))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (RTP initialization failed). Aborting.");
            _error = true;
        }
    }
    else
    {
        if (!file.open(QIODevice::ReadOnly))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (file open failed). Aborting.");
            _error = true;
        }

        int flags = fcntl(file.handle(), F_GETFL, 0);
        if (flags == -1) flags = 0;
        fcntl(file.handle(), F_SETFL, flags | O_NONBLOCK);
    }

    if (_error)
    {
        RunEpilog();
        return;
    }

    SetRunning(true, false, false);

    int buffer_size = (64 * 1024); // read about 64KB
    buffer_size /= TSPacket::kSize;
    buffer_size *= TSPacket::kSize;
    char *buffer = new char[buffer_size];

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): begin");

    _read_timer.start();

    int remainder = 0;
    while (_running_desired && !_error)
    {
        int bytes_read;
        if (_using_rtp)
            bytes_read = rtp.Read(buffer, buffer_size);
        else
            bytes_read = file.read(buffer, buffer_size);

        if (bytes_read <= 0)
        {
            if (_read_timer.elapsed() >= 5000)
            {
                LOG(VB_RECORD, LOG_WARNING, LOC +
                    "No data received for 5 seconds...checking tuning");
                if (!VerifyTuning())
                    RepeatTuning();
                _read_timer.start();
            }

            usleep(5000);
            continue;
        }

        _read_timer.start();

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData(
                reinterpret_cast<unsigned char*>(buffer), bytes_read);

        _listener_lock.unlock();
        if (remainder != 0)
        {
            LOG(VB_RECORD, LOG_INFO, LOC +
                QString("RunTS(): bytes_read = %1 remainder = %2")
                    .arg(bytes_read).arg(remainder));
        }
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "shutdown");

    if (_using_rtp)
        rtp.StopStreaming();
    else
        file.close();

    delete[] buffer;

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "end");

    SetRunning(false, false, false);
    RunEpilog();
}
Example #26
0
/** \fn DVBStreamHandler::RunTS(void)
 *  \brief Uses TS filtering devices to read a DVB device for tables & data
 *
 *  This supports all types of MPEG based stream data, but is extreemely
 *  slow with DVB over USB 1.0 devices which for efficiency reasons buffer
 *  a stream until a full block transfer buffer full of the requested
 *  tables is available. This takes a very long time when you are just
 *  waiting for a PAT or PMT table, and the buffer is hundreds of packets
 *  in size.
 */
void DVBStreamHandler::RunTS(void)
{
    QByteArray dvr_dev_path = _dvr_dev_path.toAscii();
    int dvr_fd;
    for (int tries = 1; ; ++tries)
    {
        dvr_fd = open(dvr_dev_path.constData(), O_RDONLY | O_NONBLOCK);
        if (dvr_fd >= 0)
            break;

        LOG(VB_GENERAL, LOG_WARNING, LOC +
            QString("Opening DVR device %1 failed : %2")
                .arg(_dvr_dev_path).arg(strerror(errno)));

        if (tries >= 20 || (errno != EBUSY && errno != EAGAIN))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Failed to open DVR device %1 : %2")
                    .arg(_dvr_dev_path).arg(strerror(errno)));
            _error = true;
            return;
        }
        usleep(50000);
    }

    int remainder = 0;
    int buffer_size = TSPacket::kSize * 15000;
    unsigned char *buffer = new unsigned char[buffer_size];
    if (!buffer)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate memory");
        close(dvr_fd);
        _error = true;
        return;
    }
    memset(buffer, 0, buffer_size);

    DeviceReadBuffer *drb = NULL;
    if (_needs_buffering)
    {
        drb = new DeviceReadBuffer(this, true, false);
        if (!drb->Setup(_device, dvr_fd))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate DRB buffer");
            delete drb;
            delete[] buffer;
            close(dvr_fd);
            _error = true;
            return;
        }

        drb->Start();
    }

    {
        // SetRunning() + set _drb
        QMutexLocker locker(&_start_stop_lock);
        _running = true;
        _using_buffering = _needs_buffering;
        _using_section_reader = false;
        _drb = drb;
    }

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): begin");

    fd_set fd_select_set;
    FD_ZERO(        &fd_select_set);
    FD_SET (dvr_fd, &fd_select_set);
    while (_running_desired && !_error)
    {
        RetuneMonitor();
        UpdateFiltersFromStreamData();

        ssize_t len = 0;

        if (drb)
        {
            len = drb->Read(
                &(buffer[remainder]), buffer_size - remainder);

            // Check for DRB errors
            if (drb->IsErrored())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Device error detected");
                _error = true;
            }

            if (drb->IsEOF() && _running_desired)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Device EOF detected");
                _error = true;
            }
        }
        else
        {
            // timeout gets reset by select, so we need to create new one
            struct timeval timeout = { 0, 50 /* ms */ * 1000 /* -> usec */ };
            int ret = select(dvr_fd+1, &fd_select_set, NULL, NULL, &timeout);
            if (ret == -1 && errno != EINTR)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "select() failed" + ENO);
            }
            else
            {
                len = read(dvr_fd, &(buffer[remainder]),
                           buffer_size - remainder);
            }
        }

        if ((0 == len) || (-1 == len))
        {
            usleep(100);
            continue;
        }

        len += remainder;

        if (len < 10) // 10 bytes = 4 bytes TS header + 6 bytes PES header
        {
            remainder = len;
            continue;
        }

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        StreamDataList::const_iterator sit = _stream_data_list.begin();
        for (; sit != _stream_data_list.end(); ++sit)
            remainder = sit.key()->ProcessData(buffer, len);

        _listener_lock.unlock();

        if (remainder > 0 && (len > remainder)) // leftover bytes
            memmove(buffer, &(buffer[len - remainder]), remainder);
    }
    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "shutdown");

    RemoveAllPIDFilters();

    {
        QMutexLocker locker(&_start_stop_lock);
        _drb = NULL;
    }

    if (drb)
    {
        if (drb->IsRunning())
            drb->Stop();
        delete drb;
    }

    close(dvr_fd);
    delete[] buffer;

    LOG(VB_RECORD, LOG_INFO, LOC + "RunTS(): " + "end");

    SetRunning(false, _needs_buffering, false);
}
Example #27
0
/** \fn DVBStreamHandler::RunTS(void)
 *  \brief Uses TS filtering devices to read a DVB device for tables & data
 *
 *  This supports all types of MPEG based stream data, but is extreemely
 *  slow with DVB over USB 1.0 devices which for efficiency reasons buffer
 *  a stream until a full block transfer buffer full of the requested
 *  tables is available. This takes a very long time when you are just
 *  waiting for a PAT or PMT table, and the buffer is hundreds of packets
 *  in size.
 */
void DVBStreamHandler::RunTS(void)
{
    if (_needs_buffering)
        _device_read_buffer = new DeviceReadBuffer(this);

    int remainder = 0;
    int buffer_size = TSPacket::SIZE * 15000;
    unsigned char *buffer = new unsigned char[buffer_size];
    if (!buffer)
        return;
    memset(buffer, 0, buffer_size);

    QByteArray dvr_dev_path = _dvr_dev_path.toAscii();
    int dvr_fd;
    for (int tries = 1; ; ++tries)
    {
        dvr_fd = open(dvr_dev_path.constData(), O_RDONLY | O_NONBLOCK);
        if (dvr_fd >= 0)
            break;
        VERBOSE(VB_IMPORTANT, LOC_WARN +
                QString("Opening DVR device %1 failed : %2")
                .arg(_dvr_dev_path).arg(strerror(errno)));
        if (tries >= 20 || (errno != EBUSY && errno != EAGAIN))
        {
            VERBOSE(VB_IMPORTANT, LOC +
                    QString("Failed to open DVR device %1 : %2")
                    .arg(_dvr_dev_path).arg(strerror(errno)));
            delete[] buffer;
            return;
        }
        usleep(50000);
    }

    bool _error = false;
    if (_device_read_buffer)
    {
        bool ok = _device_read_buffer->Setup(_dvb_dev, dvr_fd);

        if (!ok)
        {
            VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to allocate DRB buffer");
            _error = true;
            delete[] buffer;
            return;
        }

        _device_read_buffer->Start();
    }

    VERBOSE(VB_RECORD, LOC + "RunTS(): begin");

    fd_set fd_select_set;
    FD_ZERO(        &fd_select_set);
    FD_SET (dvr_fd, &fd_select_set);
    while (IsRunning() && !_error)
    {
        RetuneMonitor();
        UpdateFiltersFromStreamData();

        ssize_t len = 0;

        if (_device_read_buffer)
        {
            len = _device_read_buffer->Read(
                &(buffer[remainder]), buffer_size - remainder);

            // Check for DRB errors
            if (_device_read_buffer->IsErrored())
            {
                VERBOSE(VB_IMPORTANT, LOC_ERR + "Device error detected");
                _error = true;
            }

            if (_device_read_buffer->IsEOF())
            {
                VERBOSE(VB_IMPORTANT, LOC_ERR + "Device EOF detected");
                _error = true;
            }
        }
        else
        {
            // timeout gets reset by select, so we need to create new one
            struct timeval timeout = { 0, 50 /* ms */ * 1000 /* -> usec */ };
            int ret = select(dvr_fd+1, &fd_select_set, NULL, NULL, &timeout);
            if (ret == -1 && errno != EINTR)
            {
                VERBOSE(VB_IMPORTANT, LOC_ERR + "select() failed" + ENO);
            }
            else
            {
                len = read(dvr_fd, &(buffer[remainder]),
                           buffer_size - remainder);
            }
        }

        if ((0 == len) || (-1 == len))
        {
            usleep(100);
            continue;
        }

        len += remainder;

        if (len < 10) // 10 bytes = 4 bytes TS header + 6 bytes PES header
        {
            remainder = len;
            continue;
        }

        _listener_lock.lock();

        if (_stream_data_list.empty())
        {
            _listener_lock.unlock();
            continue;
        }

        for (uint i = 0; i < _stream_data_list.size(); i++)
        {
            remainder = _stream_data_list[i]->ProcessData(buffer, len);
        }

        _listener_lock.unlock();

        if (remainder > 0 && (len > remainder)) // leftover bytes
            memmove(buffer, &(buffer[len - remainder]), remainder);
    }
    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "shutdown");

    RemoveAllPIDFilters();

    if (_device_read_buffer)
    {
        if (_device_read_buffer->IsRunning())
            _device_read_buffer->Stop();

        delete _device_read_buffer;
        _device_read_buffer = NULL;
    }

    close(dvr_fd);
    delete[] buffer;

    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "end");

    SetRunning(false);
}
Example #28
0
void ANimModCharacter::OnStopRunning()
{
	SetRunning(false, false);
}
Example #29
0
/** 
 * @brief When timeout the Timer call this function.
 * 
 * @param timer The Navigate timer,watch the document load.
 * 
 * @return 
 */
NS_IMETHODIMP nsBrowserListener::Notify(nsITimer  *timer)
{
     LOG<<"timmer start:"<<running<<"count"<<timeCount<<"isScroll"<<isScrolled<<"\n";
     LOG<<"doc flag:"<<docStop<<" win flag"<<WinStop<<"\n";
     int breTime=(int)(interTime*(float)1000);
     if(running==NOT_RUN)
     {
	  if(brwStop)
	  {
	       LOG<<"stop browser set!\n";
	       timer->Cancel();
	       exit(1);
	  }else
	  {
	       if(docStop&&WinStop)
	       {
		    LOG<<"doc  fetched!\n";
		    if(scroolWait>0&&!isScrolled)
		    {
			 ScrollWin();
			 SetRunning(RUNNING);
			 isScrolled=true;
			 breTime=scroolWait*1000;
		    }else
		    {
			 //Init event stat.
			 SetEventWait(false);
			      
			 nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(mBro);
			 if(!browError)
			 {
			      //redirect the browser to the target
			      ReDirect(nav);
			      if(!isred)
			      {
				   Excute(nav);			      
			      }
			 }
			 //if the evenWait has set, do not change the web site.
			 if(evenWait||isred)
			 {
			      SetRunning(RUNNING);
			      breTime=1000;
			 }else
			 {
			      nsCString tmpUrl;
			      GetUrl(tmpUrl);
			      LOG<<tmpUrl.get()<<"\n";
			      
			      if(tmpUrl.Length()>0)
			      {
				   //init running stat and scrool stat.
				   SetRunning(RUNNING);
				   isScrolled=false;
				   //navigate the web site.
				   WebNav(nav,tmpUrl);
			      }else
			      {
				   StopBrows();
			      }
			 }
		    }    
	       }else
	       {
		    LOG<<"waite count set!\n";
		    if(timeCount>3)
		    {
			 docStop=true;
			 WinStop=true;
			 timeCount=0;
		    }else
		    {
			 timeCount++;
		    }
	       }
	  }
     }else
     {
	  LOG<<"set not run!\n";
	  timeCount=0;
	  SetRunning(NOT_RUN);
	  breTime=6000;
     }
     timeOut->Cancel();

     LOG<<"timmer stop:"<<running<<"inter time:"<<breTime<<"\n";
     timeOut->InitWithCallback(this, breTime, 0);


     return NS_OK;
}
Example #30
0
void IPTVStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, LOC + "run()");

    SetRunning(true, false, false);

    // TODO Error handling..

    // Setup
    CetonRTSP *rtsp = NULL;
    IPTVTuningData tuning = m_tuning;
    if (m_tuning.GetURL(0).scheme().toLower() == "rtsp")
    {
        rtsp = new CetonRTSP(m_tuning.GetURL(0));

        // Check RTSP capabilities
        QStringList options;
        if (!(rtsp->GetOptions(options)     && options.contains("OPTIONS")  &&
              options.contains("DESCRIBE")  && options.contains("SETUP")    &&
              options.contains("PLAY")      && options.contains("TEARDOWN")))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP interface did not support the necessary options");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        if (!rtsp->Describe())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP Describe command failed");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        tuning = IPTVTuningData(
            QString("rtp://%[email protected]%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            IPTVTuningData::kNone,
            QString("rtp://%[email protected]%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            "", 0);
    }

    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        QUrl url = tuning.GetURL(i);
        if (url.port() < 0)
            continue;

        m_sockets[i] = new QTcpSocket();
		m_sockets[i]->setSocketOption(QAbstractSocket::LowDelayOption, 1);
        m_read_helpers[i] = new IPTVStreamHandlerReadHelper(
            this, m_sockets[i], i);

        if (!url.userInfo().isEmpty())
            m_sender[i] = QHostAddress(url.userInfo());

        m_sockets[i]->connectToHost(url.host().toAscii(), 3000);
 if (m_sockets[i]->waitForConnected(1000))
   {
 m_sockets[i]->write("GET " + url.path().toAscii() + " HTTP/1.0\r\n\r\n\r\n\r\n");
                           m_sockets[i]->waitForBytesWritten(500);
                
}
else
{
  qDebug("not Connected!");
    m_sockets[i]->connectToHost(url.host().toAscii(), 3000);
m_sockets[i]->write("GET " + url.path().toAscii() + " HTTP/1.0\r\n\r\n\r\n\r\n");
                           m_sockets[i]->waitForBytesWritten(500);
}
                          
						   
						 
    }
    //if (m_use_rtp_streaming)
      //  m_buffer = new RTPPacketBuffer(tuning.GetBitrate(0));
    //else
        m_buffer = new UDPPacketBuffer(tuning.GetBitrate(0));
    m_write_helper = new IPTVStreamHandlerWriteHelper(this);
    m_write_helper->Start();

    bool error = false;
    /*if (rtsp)
    {
        // Start Streaming
        if (!rtsp->Setup(m_sockets[0]->localPort(),
                         m_sockets[1]->localPort()) ||
            !rtsp->Play())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (RTP initialization failed). Aborting.");
            error = true;
        }
    }
*/
    if (!error)
    {
        // Enter event loop
        exec();
    }

    // Clean up
    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        if (m_sockets[i])
        {
            delete m_sockets[i];
            m_sockets[i] = NULL;
            delete m_read_helpers[i];
            m_read_helpers[i] = NULL;
        }
    }
    delete m_buffer;
    m_buffer = NULL;
    delete m_write_helper;
    m_write_helper = NULL;

    if (rtsp)
    {
        rtsp->Teardown();
        delete rtsp;
    }

    SetRunning(false, false, false);
    RunEpilog();
}