CameraFrameTest() : CameraStreamFixture(STREAM_PARAMETERS) {
        TEST_EXTENSION_FORKING_CONSTRUCTOR;

        if (!HasFatalFailure()) {
            CreateStream();
        }
    }
Beispiel #2
0
void sensor_server() {
    struct SensorService service;    
    sensorservice_initialize(&service);

    RegisterAs("SensorServer");

    // Create the thing sending us sensor messages.
    Create(HIGH, sensor_notifier);

    tid_t stream = CreateStream("SensorServerStream");

    int tid;
    SensorServerMessage msg, rply;
    for(;;) {
        Receive(&tid, (char *) &msg, sizeof(msg));

        switch(msg.type) {
            case SENSOR_EVENT_REQUEST:
                rply.type = SENSOR_EVENT_RESPONSE;
                Reply(tid, (char *) &rply, sizeof(rply));

                sensorservice_process_data(&service, msg.data);

                publish(&service, stream);
                break;
            default:
                ulog("Invalid SensorServer Request");
        }
    }

    Exit();
}
Beispiel #3
0
long CStream::GetNextStream(short nKeyNum)
{
	long nResult = -1;
	if (!IsStreamRunning())
	{
		m_nFunc = DBA_GET_NEXT_STREAM;
		nResult = CreateStream(nKeyNum);
	}
	return nResult;
}
Beispiel #4
0
//+----------------------------------------------------------------------------+
//|bool Initialize(AudioEngine* engine, const rString &path, SoundType type)
//\----------------------------------------------------------------------------+
bool SoundSDL::Initialize(AudioEngine* engine, const rString &path, SoundType type)
{
	AudioEngineSDL* audioEngine = reinterpret_cast<AudioEngineSDL*>(engine);
	const SDL_AudioSpec* sysSpec = audioEngine->GetSystemSpec();
	m_AudioEngine = audioEngine;
	m_Type = type;
	m_Name = path;
	m_ChunkSize = sysSpec->size;

	m_AudioCVT = pNew(SDL_AudioCVT);
	m_BufferData = tNew(AudioBuffer);
	m_AudioFile = nullptr;

	///Check which file format the requested audiofile are
	///Only wav and ogg are supported

	///Is wave file
	if(path.find(".wav", 0) != std::string::npos)
	{ 
		m_AudioFile = pNew(WavFileReader);
	}
	///Is ogg file
	else if(path.find(".ogg", 0) != std::string::npos)
	{ 
		m_AudioFile = pNew(OggFileReader);
	}
	///Not supported format
	else
	{
		fprintf(stderr, "SoundSDL. Trying to load unsupported file format %s \n", path.c_str());
		return false;
	}

	m_AudioFile->Initialize();

	///Read as sample, read everything into buffer
	if(type == SoundType::SAMPLE)
	{
		CreateSample(path, m_BufferData, sysSpec);
	}
	///Read as stream, prepare for buffer streaming
	else if(type == SoundType::STREAM)
	{
		CreateStream(path, m_BufferData, sysSpec);
	}
	else
	{
		///This should not happend..
		fprintf(stderr, "SoundSDL. Unexpected error loading %s while setting sound type \n", path.c_str());
		return false;
	}

	return true;
}
// Simple segment reading.
TEST(TestBufferedInputStream, SimpleReadSegments) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  char buf2[kBufSize];
  uint32_t count;
  ASSERT_EQ(NS_OK, bis->ReadSegments(NS_CopySegmentToBuffer, buf2, sizeof(buf2), &count));
  ASSERT_EQ(count, buf.Length());
  ASSERT_TRUE(nsCString(buf.get(), kBufSize).Equals(nsCString(buf2, count)));
}
Beispiel #6
0
bool PAPlayer::QueueNextFile(const CFileItem &file, bool checkCrossFading)
{
  if (IsPaused())
    Pause();

  if (file.m_strPath == m_currentFile->m_strPath &&
      file.m_lStartOffset > 0 &&
      file.m_lStartOffset == m_currentFile->m_lEndOffset)
  { // continuing on a .cue sheet item - return true to say we'll handle the transistion
    *m_nextFile = file;
    return true;
  }

  // check if we can handle this file at all
  int decoder = 1 - m_currentDecoder;
  int64_t seekOffset = (file.m_lStartOffset * 1000) / 75;
  if (!m_decoder[decoder].Create(file, seekOffset, m_crossFading))
  {
    m_bQueueFailed = true;
    return false;
  }

  // ok, we're good to go on queuing this one up
  CLog::Log(LOGINFO, "PAPlayer: Queuing next file %s", file.m_strPath.c_str());

  m_bQueueFailed = false;
  if (checkCrossFading)
  {
    UpdateCrossFadingTime(file);
  }

  unsigned int channels, samplerate, bitspersample;
  m_decoder[decoder].GetDataFormat(&channels, &samplerate, &bitspersample);

  // check the number of channels isn't changing (else we can't do crossfading)
  if (m_crossFading && m_decoder[m_currentDecoder].GetChannels() == channels)
  { // crossfading - need to create a new stream
    if (!CreateStream(1 - m_currentStream, channels, samplerate, bitspersample))
    {
      m_decoder[decoder].Destroy();
      CLog::Log(LOGERROR, "PAPlayer::Unable to create audio stream");
    }
  }
  else
  { // no crossfading if nr of channels is not the same
    m_crossFading = 0;
  }

  *m_nextFile = file;

  return true;
}
//---------------------------------------------------------------------------
void File_DtvccTransport::Streams_Finish()
{
    Clear(Stream_Text);

    if (ServiceDescriptors)
    {
        if (ServiceDescriptors->ServiceDescriptors608.find(0)!=ServiceDescriptors->ServiceDescriptors608.end())
            CreateStream(0);
        if (ServiceDescriptors->ServiceDescriptors608.find(1)!=ServiceDescriptors->ServiceDescriptors608.end())
            CreateStream(1);
        if (!ServiceDescriptors->ServiceDescriptors708.empty())
            CreateStream(2);
    }

    //Per stream
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsAccepted] /*&& Streams[Pos]->Parser->Status[IsUpdated]*/)
        {
            Finish(Streams[Pos]->Parser);
            Streams_Update_PerStream(Pos);
        }
}
Beispiel #8
0
  void AudioFMOD::Add(Resources::SoundCue::Ptr soundCue)
  {
    Trace("'" + soundCue->getName() + "'");
    soundCue->getSound().Type = ::Audio::Sound::Type::File;
    auto& soundAddress = soundCue->getSound().Handle.Sound.File;
    auto& soundFile = soundCue->getAssetPath();
    //auto& soundAddress = soundCue->getSound().Address;

    // You pick which to use depending on file size here.
    // For now, we will be using stream.
    CreateStream(soundFile, &soundAddress);
    //CreateSound(soundFile, &soundAddress);
  }
Beispiel #9
0
    int DiskThread::Main() {
        dmsg(3,("Disk thread running\n"));
        while (true) {
            pthread_testcancel(); // mandatory for OSX
            IsIdle = true; // will be set to false if a stream got filled

            // if there are ghost streams, delete them
            for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient
                Stream::Handle hGhostStream;
                GhostQueue->pop(&hGhostStream);
                bool found = false;
                for (int i = 0; i < this->Streams; i++) {
                    if (pStreams[i]->GetHandle() == hGhostStream) {
                        pStreams[i]->Kill();
                        found = true;
                        break;
                    }
                }
                if (!found) GhostQueue->push(&hGhostStream); // put ghost stream handle back to the queue
            }

            // if there are creation commands, create new streams
            while (Stream::UnusedStreams > 0 && CreationQueue->read_space() > 0) {
                create_command_t command;
                CreationQueue->pop(&command);
                CreateStream(command);
            }

            // if there are deletion commands, delete those streams
            while (Stream::UnusedStreams < Stream::TotalStreams && DeletionQueue->read_space() > 0) {
                delete_command_t command;
                DeletionQueue->pop(&command);
                DeleteStream(command);
            }

            RefillStreams(); // refill the most empty streams

            // if nothing was done during this iteration (eg no streambuffer
            // filled with data) then sleep for 50ms
            if (IsIdle) usleep(30000);

            int streamsInUsage = 0;
            for (int i = Streams - 1; i >= 0; i--) {
                if (pStreams[i]->GetState() != Stream::state_unused) streamsInUsage++;
            }
            ActiveStreamCount = streamsInUsage;
            if (streamsInUsage > ActiveStreamCountMax) ActiveStreamCountMax = streamsInUsage;
        }

        return EXIT_FAILURE;
    }
// AsyncWait - sync
TEST(TestBufferedInputStream, AsyncWait_sync) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  RefPtr<testing::InputStreamCallback> cb =
    new testing::InputStreamCallback();

  ASSERT_EQ(NS_OK, bis->AsyncWait(cb, 0, 0, nullptr));

  // Immediatelly called
  ASSERT_TRUE(cb->Called());
}
Beispiel #11
0
bool tdnMesh::Create( const CreateData &data )
{
	if ( CreateVertex( data.numVertexes, data.vertexSize, data.vertexArray ) == false )
		return false;
	if ( data.numIndexes != 0 && data.indexArray != nullptr )
		if ( CreateIndexes( data.numIndexes, data.indexArray ) == false )
			return false;
	if ( data.streamSize != 0 && data.streamArray != nullptr && data.numStream != 0 )
		if ( CreateStream( data.numStream, data.streamSize, data.streamArray ) == false )
			return false;
	if ( CreateDeclaration( data.vertexSize, data.decl ) == false )
		return false;
	numFaces = data.numIndexes / 3;
	return true;
}
// Simple reading.
TEST(TestBufferedInputStream, SimpleRead) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  uint64_t length;
  ASSERT_EQ(NS_OK, bis->Available(&length));
  ASSERT_EQ((uint64_t)kBufSize, length);

  char buf2[kBufSize];
  uint32_t count;
  ASSERT_EQ(NS_OK, bis->Read(buf2, sizeof(buf2), &count));
  ASSERT_EQ(count, buf.Length());
  ASSERT_TRUE(nsCString(buf.get(), kBufSize).Equals(nsCString(buf2, count)));
}
Beispiel #13
0
static bool_t create_client(ext2fs_st            *st, 
			    Client_st            *c,
			    IDCServerBinding_clp  binding)
{
    int          i;
    USD_QoS      qos;

    c->fs=st;
    CL_INIT(c->cl, &fs_ms, c);
    c->binding=binding;

    /* Default QoS? Hmm. */
    c->qos.p = MILLISECS(200);
    c->qos.s = MILLISECS(10);
    c->qos.l = MILLISECS(5);
    c->qos.x = True;

    qos.p = c->qos.p;
    qos.s = c->qos.s;
    qos.x = c->qos.x;

    for (i=0; i<MAX_CLIENT_HANDLES; i++) {
	c->handles[i].used=False;
    }

    /* Create a stream for the client. This involves calling the USD domain;
       must be careful we don't deadlock. */
    if(USDCtl$CreateStream(st->disk.usdctl,
			   (USD_ClientID)(word_t)c,
			   &(c->usd_stream),
			   &(c->usd))
       != USDCtl_Error_None)
    {
	return False;
    }
    if(USDCtl$AdjustQoS(st->disk.usdctl,
			c->usd_stream,
			&qos)
       != USDCtl_Error_None)
    {
	(void)USDCtl$DestroyStream(st->disk.usdctl,
				   c->usd_stream);
	return False;
    }

    return True;
}
Beispiel #14
0
int XSocketMgr::ProcessNewSocket(XListenNode* pListen, time_t nTimeNow)
{
	int			nCount      = 0;
    int         nRetCode    = 0;
    sockaddr_in remoteAddr;

    while (!pListen->bUsrClose)
    {
        SOCKET         nSocket     = INVALID_SOCKET;
        int            nAddrLen    = sizeof(sockaddr_in);
        XStreamNode*   pNode       = NULL;

        memset(&remoteAddr, 0, sizeof(sockaddr_in));
        
        nSocket = accept(pListen->nSocket, (sockaddr*)&remoteAddr, &nAddrLen);
        if (nSocket == INVALID_SOCKET)
            break;

		nCount++;

        nRetCode = SetSocketNoneBlock(nSocket);
        if (!nRetCode)
        {
            closesocket(nSocket);
            continue;
        }

        pNode = CreateStream(
            nSocket, inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port), nTimeNow, pListen->uMaxRecvPackSize
        );
        if (pNode == NULL)
        {
            closesocket(nSocket);
            continue;
        }

		pNode->nSendRetryCount = pListen->nSendRetryCount;
		pNode->nSendRetrySleep = pListen->nSendRetrySleep;

        if (pListen->pCallback)
        {
            (*pListen->pCallback)(pListen, pListen->pvUsrData, pNode);
        }
    }

	return nCount;
}
TInt CMccControllerStub::ControllerStreamCtrCalled( TMMCActionType aAction,
                                                    TUint32 aSessionID,
                                                    TUint32 aLinkID,
                                                    TUint32 aStreamID,
                                                    TUint32 aEndpointID,
                                                    TUint32 aPaused,
                                                    TUint32 aEnableRTCP )
                                           
    {
    TAction action;
    action.iAction = aAction;
    action.iSessionID = aSessionID;
    action.iLinkID = aLinkID;
    action.iStreamID = aStreamID;
    action.iEndpointID = aEndpointID;
    action.iLinkType = KMceNotAssigned;
    action.iStreamType = KMceNotAssigned;
    action.iPaused = aPaused;
    action.iEnableRTCP = aEnableRTCP;
    action.iKey = KMceNotAssigned;
    action.iParamSet = KMceNotAssigned;
    
    iActions[ iActionPtr++ ] = action;

    iActionPtr = iActionPtr < KMce_MM_MaxArray-1 ? iActionPtr : 0;

    if ( aAction == EMccCreateStream )
        {
        TLink link;
        link.iSessionID = aSessionID;
        link.iLinkID = aLinkID;
        CreateStream( link );
        
        }
    else if ( aAction == EMccDeleteStream )
        {
        TLink link;
        link.iSessionID = aSessionID;
        link.iLinkID = aLinkID;
        TLink& l = GetLink( link );
        l.iStreams--;
        }
        
    
    return iLeaveError;
    
    }
// AsyncWait - async
TEST(TestBufferedInputStream, AsyncWait_async) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  RefPtr<testing::InputStreamCallback> cb =
    new testing::InputStreamCallback();
  nsCOMPtr<nsIThread> thread = do_GetCurrentThread();

  ASSERT_EQ(NS_OK, bis->AsyncWait(cb, 0, 0, thread));

  ASSERT_FALSE(cb->Called());

  // Eventually it is called.
  MOZ_ALWAYS_TRUE(mozilla::SpinEventLoopUntil([&]() { return cb->Called(); }));
  ASSERT_TRUE(cb->Called());
}
// AsyncWait - sync - closureOnly
TEST(TestBufferedInputStream, AsyncWait_sync_closureOnly) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  RefPtr<testing::InputStreamCallback> cb =
    new testing::InputStreamCallback();

  ASSERT_EQ(NS_OK, bis->AsyncWait(cb, nsIAsyncInputStream::WAIT_CLOSURE_ONLY,
                                  0, nullptr));
  ASSERT_FALSE(cb->Called());

  bis->CloseWithStatus(NS_ERROR_FAILURE);

  // Immediatelly called
  ASSERT_TRUE(cb->Called());
}
Beispiel #18
0
	///////////////////////////////////////////////////////////////////////////////
	//                                                                           //
	// File I/O                                                                  //
	//                                                                           //
	///////////////////////////////////////////////////////////////////////////////
	aalError Sample::Load(const char * _name)
	{
		Stream * stream = CreateStream(_name);

		if (!stream) return AAL_ERROR_FILEIO;

		stream->GetFormat(format);
		stream->GetLength(length);
		DeleteStream(stream);

		aalVoid * ptr = realloc(name, strlen(_name) + 1);

		if (!ptr) return AAL_ERROR_MEMORY;

		name = (char *)ptr;
		strcpy(name, _name);

		return AAL_OK;
	}
Beispiel #19
0
nsresult
LockedFile::CreateParallelStream(nsISupports** aStream)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  nsIFileStorage* fileStorage = mFileHandle->mFileStorage;
  if (fileStorage->IsStorageInvalidated()) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  nsCOMPtr<nsISupports> stream =
    mFileHandle->CreateStream(mFileHandle->mFile, mMode == READ_ONLY);
  NS_ENSURE_TRUE(stream, NS_ERROR_FAILURE);

  mParallelStreams.AppendElement(stream);

  stream.forget(aStream);
  return NS_OK;
}
// AsyncWait - async
TEST(TestBufferedInputStream, AsyncWait_async_closureOnly) {
  const size_t kBufSize = 10;

  nsCString buf;
  RefPtr<nsBufferedInputStream> bis = CreateStream(kBufSize, buf);

  RefPtr<testing::InputStreamCallback> cb =
    new testing::InputStreamCallback();
  nsCOMPtr<nsIThread> thread = do_GetCurrentThread();

  ASSERT_EQ(NS_OK, bis->AsyncWait(cb, nsIAsyncInputStream::WAIT_CLOSURE_ONLY,
                                  0, thread));

  ASSERT_FALSE(cb->Called());
  bis->CloseWithStatus(NS_ERROR_FAILURE);
  ASSERT_FALSE(cb->Called());

  // Eventually it is called.
  MOZ_ALWAYS_TRUE(mozilla::SpinEventLoopUntil([&]() { return cb->Called(); }));
  ASSERT_TRUE(cb->Called());
}
Beispiel #21
0
XnStatus XnDeviceBase::CreateStreamsFromFile(const XnChar* csINIFilePath, const XnChar* csSectionName)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// go through numbers until no stream is found
	XnUInt32 nStreamIndex = 0;
	XnChar csKeyName[XN_INI_MAX_LEN];

	for (;;)
	{
		sprintf(csKeyName, "Stream%u_Type", nStreamIndex);

		XnChar csStreamType[XN_INI_MAX_LEN];
		XnChar csStreamName[XN_INI_MAX_LEN];

		nRetVal = xnOSReadStringFromINI(csINIFilePath, csSectionName, csKeyName, csStreamType, XN_INI_MAX_LEN);
		if (nRetVal != XN_STATUS_OK) // no more streams
		{
			break;
		}

		// check if the stream has a name
		sprintf(csKeyName, "Stream%u_Name", nStreamIndex);
		nRetVal = xnOSReadStringFromINI(csINIFilePath, csSectionName, csKeyName, csStreamName, XN_INI_MAX_LEN);
		if (nRetVal != XN_STATUS_OK)
		{
			// use its type as a name
			strcpy(csStreamName, csStreamType);
		}

		nRetVal = CreateStream(csStreamType, csStreamName);
		XN_IS_STATUS_OK(nRetVal);

		nStreamIndex++;
	}

	return (XN_STATUS_OK);
}
TEST_P(CameraStreamTest, CreateStream) {

    TEST_EXTENSION_FORKING_INIT;

    /** Make sure the format requested is supported. PASS this test if it's not
      * not supported.
      *
      * TODO: would be nice of not running this test in the first place
      *       somehow.
      */
    {
        camera_metadata_ro_entry availableFormats =
            GetStaticEntry(ANDROID_SCALER_AVAILABLE_FORMATS);

        bool hasFormat = false;
        for (size_t i = 0; i < availableFormats.count; ++i) {
            if (availableFormats.data.i32[i] == GetParam().mFormat) {
                hasFormat = true;
                break;
            }
        }

        if (!hasFormat) {
            const ::testing::TestInfo* const test_info =
                ::testing::UnitTest::GetInstance()->current_test_info();
            std::cerr << "Skipping test "
                      << test_info->test_case_name() << "."
                      << test_info->name()
                      << " because the format was not available: "
                      << GetParam() << std::endl;
            return;
        }
    }

    ASSERT_NO_FATAL_FAILURE(CreateStream());
    ASSERT_NO_FATAL_FAILURE(DeleteStream());
}
Beispiel #23
0
	void Picture::SaveBitmapToFile(const std::wstring & path, IWICBitmap* bitmap)
	{
		auto wicFactory = PublicResource::GetGraphicsResource().WicImagingFactory.p;
		CComPtr<IWICStream> stream;
		CComPtr<IWICBitmapEncoder> encoder;
		CComPtr<IWICBitmapFrameEncode> frameEncoder;
		CComPtr<ID2D1Bitmap> newBitmap;
		WICPixelFormatGUID format = GUID_WICPixelFormat32bppPBGRA;
		wicFactory->CreateStream(&stream);
		UINT width, height;
		bitmap->GetSize(&width, &height);
		stream->InitializeFromFilename(path.data(), GENERIC_WRITE);
		HRESULT hr = wicFactory->CreateEncoder(Picture::PictureTypeParser(path),
			nullptr,
			&encoder);
		hr = encoder->Initialize(stream, WICBitmapEncoderNoCache);
		hr = encoder->CreateNewFrame(&frameEncoder, nullptr);
		hr = frameEncoder->Initialize(nullptr);
		hr = frameEncoder->SetSize(width, height);
		hr = frameEncoder->SetPixelFormat(&format);
		hr = frameEncoder->WriteSource(bitmap,nullptr);
		hr = frameEncoder->Commit();
		hr = encoder->Commit();
	}
Beispiel #24
0
bool PAPlayer::OpenFile(const CFileItem& file, const CPlayerOptions &options)
{
  if (m_currentlyCrossFading) CloseFileInternal(false); //user seems to be in a hurry

  m_crossFading = g_guiSettings.GetInt("musicplayer.crossfade");
  //WASAPI doesn't support multiple streams, no crossfading for cdda, cd-reading goes mad and no crossfading for last.fm doesn't like two connections
  if (file.IsCDDA() || file.IsLastFM() || g_guiSettings.GetString("audiooutput.audiodevice").find("wasapi:") != CStdString::npos) m_crossFading = 0;
  if (m_crossFading && IsPlaying())
  {
    //do a short crossfade on trackskip
    //set to max 2 seconds for these prev/next transitions
    if (m_crossFading > 2) m_crossFading = 2;
    //queue for crossfading
    bool result = QueueNextFile(file, false);
    if (result)
    {
      //crossfading value may be update by QueueNextFile when nr of channels changed
      if (!m_crossFading) // swap to next track
        m_decoder[m_currentDecoder].SetStatus(STATUS_ENDED);
      else //force to fade to next track immediately
        m_forceFadeToNext = true;
    }
    return result;
  }

  // normal opening of file, nothing playing or crossfading not enabled
  // however no need to return to gui audio device
  CloseFileInternal(false);

  // always open the file using the current decoder
  m_currentDecoder = 0;

  if (!m_decoder[m_currentDecoder].Create(file, (__int64)(options.starttime * 1000), m_crossFading))
    return false;

  m_iSpeed = 1;
  m_bPaused = false;
  m_bStopPlaying = false;
  m_bytesSentOut = 0;

  CLog::Log(LOGINFO, "PAPlayer: Playing %s", file.m_strPath.c_str());

  m_timeOffset = (__int64)(options.starttime * 1000);

  unsigned int channel, sampleRate, bitsPerSample;
  m_decoder[m_currentDecoder].GetDataFormat(&channel, &sampleRate, &bitsPerSample);

  if (!CreateStream(m_currentStream, channel, sampleRate, bitsPerSample))
  {
    m_decoder[m_currentDecoder].Destroy();
    CLog::Log(LOGERROR, "PAPlayer::Unable to create audio stream");
  }

  *m_currentFile = file;

  if (ThreadHandle() == NULL)
    Create();

  m_startEvent.Set();

  m_bIsPlaying = true;
  m_cachingNextFile = false;
  m_currentlyCrossFading = false;
  m_forceFadeToNext = false;
  m_bQueueFailed = false;

  m_decoder[m_currentDecoder].Start();  // start playback

  return true;
}
Beispiel #25
0
/*
 * Compose stage file events into a stage stream.  Streams
 * represent optimal i/o requests for media.  A stream is
 * added to work queue.
 */
void
Compose(void)
{
	FileInfo_t **sortList;
	StreamInfo_t *stream;
	FileInfo_t *file;
	char *currentVsn;
	int i;
	int copy;
	int retry;
	boolean_t added;

	if (composeList.entries == 0) {
		return;
	}

	sortList = makeSortList();
	separateVsns(sortList);

	currentVsn = NULL;
	stream = NULL;

	for (i = 0; i < composeList.entries; i++) {

		file = GetFile(composeList.data[i]);

		copy = file->copy;

		/*
		 * If first VSN (currentVsn == NULL) or different VSN or
		 * disk cache already open, ie. multivolume, create a new
		 * stream.  Add new stream to the work queue.
		 */
		if (currentVsn == NULL ||
		    (strcmp(file->ar[copy].section.vsn, currentVsn) != 0) ||
		    GET_FLAG(file->flags, FI_DCACHE)) {

			retry = 3;
			stream = NULL;

			while (stream == NULL && retry-- > 0) {
				stream = CreateStream(file);
				if (stream == NULL) {
					SetErrno = 0;	/* set for trace */
					Trace(TR_ERR, "Create stream failed");
					sleep(5);
				}
			}
			if (stream == NULL) {
				FatalSyscallError(EXIT_FATAL, HERE,
				    "Compose create stream", currentVsn);
			}

			AddWork(stream);

			if (GET_FLAG(file->flags, FI_DCACHE_CLOSE) == 0) {
				currentVsn = file->ar[copy].section.vsn;
			}
		}

		/*
		 * Add stage request to the stream.
		 */
		added = AddStream(stream, composeList.data[i],
		    ADD_STREAM_NOSORT);
		if (added == B_FALSE) {
			SetErrno = 0;	/* set for trace */
			Trace(TR_ERR,
			    "Compose add stream '%s.%d' 0x%x failed",
			    stream->vsn, stream->seqnum, (int)stream);
			SET_FLAG(stream->flags, SR_full);
		}

		/* Stream is full, create a new one. */
		if (GET_FLAG(stream->flags, SR_full)) {
			currentVsn = NULL;
		}
	}

	/*
	 * We should have added all requests to the work queue
	 * so free the composition list.
	 */
	composeList.entries = 0;
}
//---------------------------------------------------------------------------
void File_DtvccTransport::Read_Buffer_Continue()
{
    //Parsing
    Element_Begin1(Format==Format_DVD?"DVD Captions":"DTVCC Transport");
    int8u  cc_count;
    bool   process_cc_data_flag, additional_data_flag;
    BS_Begin();
    if (Format==Format_DVD)
    {
        //Modified DTVCC Transport from DVD
        Skip_SB(                                                "field 1 then field 2");
        Get_S1 (7, cc_count,                                    "cc_count");
        process_cc_data_flag=true;
        additional_data_flag=false;
    }
    else
    {
        //Normal DTVCC Transport
        bool process_em_data_flag;
        Get_SB (process_em_data_flag,                           "process_em_data_flag");
        Get_SB (process_cc_data_flag,                           "process_cc_data_flag");
        Get_SB (additional_data_flag,                           "additional_data_flag");
        Get_S1 (5, cc_count,                                    "cc_count");
        Skip_S1(8,                                              process_em_data_flag?"em_data":"reserved"); //Emergency message
    }
    BS_End();
    if (process_cc_data_flag)
    {
        for (int8u Pos=0; Pos<cc_count; Pos++)
        {
            if (Element_Offset+3>Element_Size)
                break; //Found one stream with bad cc_count, we discard cc_count without flagging the stream as untrusted for the moment

            Element_Begin1("cc");
            int8u cc_type;
            bool  cc_valid;
            BS_Begin();
            Mark_1();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            if (Format==Format_DVD)
            {
                //Modified DTVCC Transport from DVD
                Mark_1();
                Mark_1();
                Get_S1 (1, cc_type,                             "cc_type"); Param_Info1(DtvccTransport_cc_type(cc_type));
                cc_valid=true;
            }
            else
            {
                //Normal DTVCC Transport
                Get_SB (   cc_valid,                            "cc_valid");
                Get_S1 (2, cc_type,                             "cc_type"); Param_Info1(DtvccTransport_cc_type(cc_type));
            }
            BS_End();

            #if MEDIAINFO_ADVANCED
                if (cc_type>=2 && !Streams[2] && Config->File_Eia708_DisplayEmptyStream_Get())
                    CreateStream(2);
            #endif //MEDIAINFO_ADVANCED

            if (cc_valid)
            {
                Element_Begin1("cc_data");
                    //Calculating the parser position
                    int8u Parser_Pos=cc_type==3?2:cc_type; //cc_type 2 and 3 are for the same text

                    //Stream creation
                    if (Streams[Parser_Pos]==NULL)
                        CreateStream(Parser_Pos);

                    //Parsing
                    #if MEDIAINFO_DEMUX
                        Element_Code=Parser_Pos;
                        Demux(Buffer+(size_t)(Buffer_Offset+Element_Offset), 2, ContentType_MainStream);
                    #endif //MEDIAINFO_DEMUX
                    if (!Streams[Parser_Pos]->Parser->Status[IsFinished])
                    {
                        //Parsing
                        if (Streams[Parser_Pos]->Parser->PTS_DTS_Needed)
                        {
                            Streams[Parser_Pos]->Parser->FrameInfo.PCR=FrameInfo.PCR;
                            Streams[Parser_Pos]->Parser->FrameInfo.PTS=FrameInfo.PTS;
                            Streams[Parser_Pos]->Parser->FrameInfo.DTS=FrameInfo.DTS;
                        }
                        if (Parser_Pos==2)
                        {
                            #if defined(MEDIAINFO_EIA708_YES)
                                ((File_Eia708*)Streams[2]->Parser)->cc_type=cc_type;
                                if (AspectRatio)
                                    ((File_Eia708*)Streams[2]->Parser)->AspectRatio=AspectRatio;
                            #endif
                            if (cc_type==3)
                            {
                                ((File_Eia708*)Streams[2]->Parser)->cc_type=4; //Magic value saying that the buffer must be kept (this is only a point of synchro from the undelying layer)
                                Open_Buffer_Continue(Streams[Parser_Pos]->Parser, Buffer+(size_t)(Buffer_Offset+Element_Offset), 0);
                                ((File_Eia708*)Streams[2]->Parser)->cc_type=3;
                            }
                        }
                        else
                        {
                        }
                        #if defined(MEDIAINFO_EIA608_YES) || defined(MEDIAINFO_EIA708_YES)
                            Streams[Parser_Pos]->Parser->ServiceDescriptors=ServiceDescriptors;
                        #endif
                        Open_Buffer_Continue(Streams[Parser_Pos]->Parser, Buffer+(size_t)(Buffer_Offset+Element_Offset), 2);
                        Element_Show();
                        Element_Offset+=2;
                    }
                    else
                        Skip_XX(2,                                  "Data");
                Element_End0();
            }
            else
                Skip_XX(2,                                          "Junk");
            Element_End0();
        }

        FILLING_BEGIN();
            if (!Status[IsAccepted])
                Accept("DTVCC Transport");
        FILLING_END();
    }
    else
        Skip_XX(cc_count*2,                                         "Junk");

    if (Format==Format_A53_4_GA94_03)
    {
        //Normal DTVCC Transport
        BS_Begin();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        Mark_1_NoTrustError();
        BS_End();

        if (additional_data_flag)
        {
            Skip_XX(Element_Size-Element_Offset,                "additional_user_data");
        }

        while (Element_Offset<Element_Size)
        {
            Skip_B1(                                                "Zero"); //TODO: test Zero
        }
    }

    Element_End0();
}
Beispiel #27
0
//---------------------------------------------------------------------------
void File_Cdp::ccsvcinfo_section()
{
    //Parsing
    int8u svc_count;
    Element_Begin1("ccsvcinfo_section");
    Skip_B1(                                                    "ccsvcinfo_id");
    BS_Begin();
    Skip_SB(                                                    "reserved");
    Skip_SB(                                                    "svc_info_start");
    Skip_SB(                                                    "svc_info_change");
    Skip_SB(                                                    "svc_info_complete");
    Get_S1 (4, svc_count,                                       "svc_count");
    BS_End();
    for (int8u Pos=0; Pos<svc_count; Pos++)
    {
        Element_Begin1("svc");
        bool  csn_size;
        BS_Begin();
        Skip_SB(                                                "reserved");
        Get_SB (   csn_size,                                    "csn_size");
        if (csn_size)
        {
            Skip_SB(                                            "reserved");
            Skip_S1(5,                                          "caption_service_number");
        }
        else
            Skip_S1(6,                                          "caption_service_number");
        BS_End();

        //svc_data_byte - caption_service_descriptor
        Element_Begin1("service");
        string language;
        int8u caption_service_number=0;
        bool digital_cc, line21_field=false;
        Get_String(3, language,                                 "language");
        BS_Begin();
        Get_SB (digital_cc,                                     "digital_cc");
        Skip_SB(                                                "reserved");
        if (digital_cc) //line21
            Get_S1 (6, caption_service_number,                  "caption_service_number");
        else
        {
            Skip_S1(5,                                          "reserved");
            Get_SB (   line21_field,                            "line21_field");

            //Coherency test
            if (line21_field && svc_count==1)
                line21_field=false; // Wrong info in the descriptor?
        }
        Skip_SB(                                                "easy_reader");
        Skip_SB(                                                "wide_aspect_ratio");
        Skip_S2(14,                                             "reserved");
        BS_End();
        Element_End0();
        Element_End0();

        FILLING_BEGIN();
            #if defined(MEDIAINFO_EIA608_YES) || defined(MEDIAINFO_EIA708_YES)
                if (digital_cc)
                {
                    #if defined(MEDIAINFO_EIA708_YES)
                        ServiceDescriptors->ServiceDescriptors708[caption_service_number].language=language;
                    #endif
                }
                else
                {
                    #if defined(MEDIAINFO_EIA708_YES)
                        ServiceDescriptors->ServiceDescriptors608[line21_field?1:0].language=language;
                    #endif
                }
            #endif

            //Stream creation
            int8u Parser_Pos;
            if (digital_cc) //line21
                Parser_Pos = 2;
            else
                Parser_Pos= (line21_field ? 1 : 0); //cc_type 2 and 3 are for the same text
            if (Streams[Parser_Pos]==NULL)
                CreateStream(Parser_Pos);
        FILLING_END();
    }
    Element_End0();
}
Beispiel #28
0
bool PAPlayer::ProcessPAP()
{
  /*
   * Here's what we should be doing in each player loop:
   *
   * 1.  Run DoWork() on our audio device to actually output audio.
   *
   * 2.  Pass our current buffer to the audio device to see if it wants anything,
   *     and if so, reduce our buffer size accordingly.
   *
   * 3.  Check whether we have space in our buffer for more data, and if so,
   *     read some more in.
   *
   * 4.  Check for end of file and return false if we reach it.
   *
   * 5.  Perform any seeking and ffwd/rewding as necessary.
   *
   * 6.  If we don't do anything in 2...5, we can take a breather and break out for sleeping.
   */
  while (true)
  {
    if (m_bStop) return false;

    // Check for .cue sheet item end
    if (m_currentFile->m_lEndOffset && GetTime() >= GetTotalTime64())
    {
      CLog::Log(LOGINFO, "PAPlayer: Passed end of track in a .cue sheet item");
      m_decoder[m_currentDecoder].SetStatus(STATUS_ENDED);
    }

    // check whether we need to send off our callbacks etc.
    int status = m_decoder[m_currentDecoder].GetStatus();
    if (status == STATUS_NO_FILE)
      return false;

    UpdateCacheLevel();

    // check whether we should queue the next file up
    if ((GetTotalTime64() > 0) && GetTotalTime64() - GetTime() < TIME_TO_CACHE_NEXT_FILE + m_crossFading * 1000L && !m_cachingNextFile)
    { // request the next file from our application
      m_callback.OnQueueNextItem();
      m_cachingNextFile = true;
    }

    if (m_crossFading && m_decoder[0].GetChannels() == m_decoder[1].GetChannels())
    {
      if (((GetTotalTime64() - GetTime() < m_crossFading * 1000L) || (m_forceFadeToNext)) && !m_currentlyCrossFading)
      { // request the next file from our application
        if (m_decoder[1 - m_currentDecoder].GetStatus() == STATUS_QUEUED && m_pAudioDecoder[1 - m_currentStream])
        {
          m_currentlyCrossFading = true;
          if (m_forceFadeToNext)
          {
            m_forceFadeToNext = false;
            m_crossFadeLength = m_crossFading * 1000L;
          }
          else
          {
            m_crossFadeLength = GetTotalTime64() - GetTime();
          }
          m_currentDecoder = 1 - m_currentDecoder;
          m_decoder[m_currentDecoder].Start();
          m_currentStream = 1 - m_currentStream;
          CLog::Log(LOGDEBUG, "Starting Crossfade - resuming stream %i", m_currentStream);

          m_pAudioDecoder[m_currentStream]->Resume();

          m_callback.OnPlayBackStarted();
          m_timeOffset = m_nextFile->m_lStartOffset * 1000 / 75;
          m_bytesSentOut = 0;
          *m_currentFile = *m_nextFile;
          m_nextFile->Reset();
          m_cachingNextFile = false;
        }
      }
    }

    // Check for EOF and queue the next track if applicable
    if (m_decoder[m_currentDecoder].GetStatus() == STATUS_ENDED)
    { // time to swap tracks
      if (m_nextFile->m_strPath != m_currentFile->m_strPath ||
          !m_nextFile->m_lStartOffset ||
          m_nextFile->m_lStartOffset != m_currentFile->m_lEndOffset)
      { // don't have a .cue sheet item
        int nextstatus = m_decoder[1 - m_currentDecoder].GetStatus();
        if (nextstatus == STATUS_QUEUED || nextstatus == STATUS_QUEUING || nextstatus == STATUS_PLAYING)
        { // swap streams
          CLog::Log(LOGDEBUG, "PAPlayer: Swapping tracks %i to %i", m_currentDecoder, 1-m_currentDecoder);
          if (!m_crossFading || m_decoder[0].GetChannels() != m_decoder[1].GetChannels())
          { // playing gapless (we use only the 1 output stream in this case)
            int prefixAmount = m_decoder[m_currentDecoder].GetDataSize();
            CLog::Log(LOGDEBUG, "PAPlayer::Prefixing %i samples of old data to new track for gapless playback", prefixAmount);
            m_decoder[1 - m_currentDecoder].PrefixData(m_decoder[m_currentDecoder].GetData(prefixAmount), prefixAmount);
            // check if we need to change the resampler (due to format change)
            unsigned int channels, samplerate, bitspersample;
            m_decoder[m_currentDecoder].GetDataFormat(&channels, &samplerate, &bitspersample);
            unsigned int channels2, samplerate2, bitspersample2;
            m_decoder[1 - m_currentDecoder].GetDataFormat(&channels2, &samplerate2, &bitspersample2);
            // change of channels - reinitialize our speaker configuration
            if (channels != channels2 || (g_advancedSettings.m_musicResample == 0 && (samplerate != samplerate2 || bitspersample != bitspersample2)))
            {
              CLog::Log(LOGINFO, "PAPlayer: Stream properties have changed, restarting stream");
              FreeStream(m_currentStream);
              if (!CreateStream(m_currentStream, channels2, samplerate2, bitspersample2))
              {
                CLog::Log(LOGERROR, "PAPlayer: Error creating stream!");
                return false;
              }
              m_pAudioDecoder[m_currentStream]->Resume();
            }
            else if (samplerate != samplerate2 || bitspersample != bitspersample2)
            {
              CLog::Log(LOGINFO, "PAPlayer: Restarting resampler due to a change in data format");
              m_resampler[m_currentStream].DeInitialize();
              if (!m_resampler[m_currentStream].InitConverter(samplerate2, bitspersample2, channels2, g_advancedSettings.m_musicResample, 16, PACKET_SIZE))
              {
                CLog::Log(LOGERROR, "PAPlayer: Error initializing resampler!");
                return false;
              }
            }
            CLog::Log(LOGINFO, "PAPlayer: Starting new track");

            m_decoder[m_currentDecoder].Destroy();
            m_decoder[1 - m_currentDecoder].Start();
            m_callback.OnPlayBackStarted();
            m_timeOffset = m_nextFile->m_lStartOffset * 1000 / 75;
            m_bytesSentOut = 0;
            *m_currentFile = *m_nextFile;
            m_nextFile->Reset();
            m_cachingNextFile = false;
            m_currentDecoder = 1 - m_currentDecoder;
          }
          else
          { // cross fading - shouldn't ever get here - if we do, return false
            if (!m_currentlyCrossFading)
            {
              CLog::Log(LOGERROR, "End of file Reached before crossfading kicked in!");
              return false;
            }
            else
            {
              CLog::Log(LOGINFO, "End of file reached before crossfading finished!");
              return false;
            }
          }
        }
        else
        {
          if (GetTotalTime64() <= 0 && !m_bQueueFailed)
          { //we did not know the duration so didn't queue the next song, try queueing it now
            if (!m_cachingNextFile)
            {// request the next file from our application
              m_callback.OnQueueNextItem();
              m_cachingNextFile = true;
            }
          }
          else
          {
            // no track queued - return and get another one once we are finished
            // with the current stream
            WaitForStream();
            return false;
          }
        }
      }
      else
      {
        // set the next track playing (.cue sheet)
        m_decoder[m_currentDecoder].SetStatus(STATUS_PLAYING);
        m_callback.OnPlayBackStarted();
        m_timeOffset = m_nextFile->m_lStartOffset * 1000 / 75;
        m_bytesSentOut = 0;
        *m_currentFile = *m_nextFile;
        m_nextFile->Reset();
        m_cachingNextFile = false;
      }
    }

    // handle seeking and ffwd/rewding.
    HandleSeeking();
    if (!HandleFFwdRewd())
    {
      // need to skip to the next track - let's see if we already have another one
      m_decoder[m_currentDecoder].SetStatus(STATUS_ENDED);
      continue; // loop around to start the next track
    }

    if (!m_bPaused)
    {

      // Let our decoding stream(s) do their thing
      int retVal = m_decoder[m_currentDecoder].ReadSamples(PACKET_SIZE);
      if (retVal == RET_ERROR)
      {
        m_decoder[m_currentDecoder].Destroy();
        return false;
      }

      int retVal2 = m_decoder[1 - m_currentDecoder].ReadSamples(PACKET_SIZE);
      if (retVal2 == RET_ERROR)
      {
        m_decoder[1 - m_currentDecoder].Destroy();
      }

      // if we're cross-fading, then we do this for both streams, otherwise
      // we do it just for the one stream.
      if (m_currentlyCrossFading)
      {
        if (GetTime() >= m_crossFadeLength)  // finished
        {
          CLog::Log(LOGDEBUG, "Finished Crossfading");
          m_currentlyCrossFading = false;
          SetStreamVolume(m_currentStream, g_settings.m_nVolumeLevel);
          FreeStream(1 - m_currentStream);
          m_decoder[1 - m_currentDecoder].Destroy();
        }
        else
        {
          float fraction = (float)(m_crossFadeLength - GetTime()) / (float)m_crossFadeLength - 0.5f;
          // make sure we can take valid logs.
          if (fraction > 0.499f) fraction = 0.499f;
          if (fraction < -0.499f) fraction = -0.499f;
          float volumeCurrent = 2000.0f * log10(0.5f - fraction);
          float volumeNext = 2000.0f * log10(0.5f + fraction);
          SetStreamVolume(m_currentStream, g_settings.m_nVolumeLevel + (int)volumeCurrent);
          SetStreamVolume(1 - m_currentStream, g_settings.m_nVolumeLevel + (int)volumeNext);
          if (AddPacketsToStream(1 - m_currentStream, m_decoder[1 - m_currentDecoder]))
            retVal2 = RET_SUCCESS;
        }
      }

      // add packets as necessary
      if (AddPacketsToStream(m_currentStream, m_decoder[m_currentDecoder]))
        retVal = RET_SUCCESS;

      if (retVal == RET_SLEEP && retVal2 == RET_SLEEP)
      {
        float maximumSleepTime = m_pAudioDecoder[m_currentStream]->GetCacheTime();
        
        if (m_pAudioDecoder[1 - m_currentStream])
          maximumSleepTime = std::min(maximumSleepTime, m_pAudioDecoder[1 - m_currentStream]->GetCacheTime());

        int sleep = std::max((int)((maximumSleepTime / 2.0f) * 1000.0f), 1);

        Sleep(std::min(sleep, 15));
      }
    }
    else
      Sleep(100);
  }
  return true;
}
Beispiel #29
0
    int DiskThread::Main() {
        dmsg(3,("Disk thread running\n"));
        while (true) {
            #if !defined(WIN32)
            pthread_testcancel(); // mandatory for OSX
            #endif
            IsIdle = true; // will be set to false if a stream got filled

            // if there are ghost streams, delete them
            for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient
                delete_command_t ghostStream;
                GhostQueue->pop(&ghostStream);
                bool found = false;
                for (int i = 0; i < this->Streams; i++) {
                    if (pStreams[i]->GetHandle() == ghostStream.hStream) {
                        pStreams[i]->Kill();
                        found = true;
                        // if original sender requested a notification, let him know now
                        if (ghostStream.bNotify)
                            DeletionNotificationQueue.push(&ghostStream.hStream);
                        break;
                    }
                }
                if (!found) GhostQueue->push(&ghostStream); // put ghost stream handle back to the queue
            }

            // if there are creation commands, create new streams
            while (Stream::UnusedStreams > 0 && CreationQueue->read_space() > 0) {
                create_command_t command;
                CreationQueue->pop(&command);
                CreateStream(command);
            }

            // if there are deletion commands, delete those streams
            while (Stream::UnusedStreams < Stream::TotalStreams && DeletionQueue->read_space() > 0) {
                delete_command_t command;
                DeletionQueue->pop(&command);
                DeleteStream(command);
            }

            // release DimensionRegions that belong to instruments
            // that are no longer loaded
            while (DeleteDimregQueue->read_space() > 0) {
                ::gig::DimensionRegion* dimreg;
                DeleteDimregQueue->pop(&dimreg);
                pInstruments->HandBackDimReg(dimreg);
            }

            RefillStreams(); // refill the most empty streams

            // if nothing was done during this iteration (eg no streambuffer
            // filled with data) then sleep for 30ms
            if (IsIdle) usleep(30000);

            int streamsInUsage = 0;
            for (int i = Streams - 1; i >= 0; i--) {
                if (pStreams[i]->GetState() != Stream::state_unused) streamsInUsage++;
            }
            ActiveStreamCount = streamsInUsage;
            if (streamsInUsage > ActiveStreamCountMax) ActiveStreamCountMax = streamsInUsage;
        }

        return EXIT_FAILURE;
    }