Beispiel #1
0
  bool refersTo    ( const Symbol & sym ) const
  {
    const_iterator item = refs.lower_bound( sym );
    const_iterator last = refs.upper_bound( sym );

    return item != last;
  }
Beispiel #2
0
  bool isReferredTo( const Symbol & sym ) const
  {
    const_iterator item = sfer.lower_bound( sym );
    const_iterator last = sfer.upper_bound( sym );

    return item != last;
  }
Beispiel #3
0
  void remove( const Symbol & sym )
  {
    refs.erase( sym );
    sfer.erase( sym );

    removeSymbol( sym );
  }
Beispiel #4
0
void H264UserDataTest::TestZeroRawSEI()
{
    printf("H264UserDataTest::TestZeroRawSEI()\n");
    fflush(stdout);

    XIRef<XMemory> data = new XMemory;

    for(uint8_t i = 1; i < 77; ++i)
        data->Append<uint8_t>(0);

    XRef<SEIPayload> payload = new SEIPayload(data);
    CPPUNIT_ASSERT(payload->GetData().Get() == data.Get());
    CPPUNIT_ASSERT(payload->GetUUID() == XUuid("7e0858c4-38fe-48ea-852d-dace39badb30"));

    H264UserData before(payload);
    const std::vector<XRef<SEIPayload> >& beforePayloads = before.GetPayloads();
    CPPUNIT_ASSERT(beforePayloads.size() == 1);
    CPPUNIT_ASSERT(beforePayloads.front() == payload);
    XIRef<XMemory> sei = before.GenSEI();

    H264UserData after(sei->begin(), sei->GetDataSize());
    const std::vector<XRef<SEIPayload> >& afterPayloads = before.GetPayloads();
    CPPUNIT_ASSERT(afterPayloads.size() == 1);
    CPPUNIT_ASSERT(afterPayloads.front().Get() == payload.Get());
}
Beispiel #5
0
void XStatisticsTest::TestMaxSamples()
{
    XRef<XStatistics<Average,double> > avg = new XStatistics<Average,double>(MAX_SAMPLES);
    UT_ASSERT( avg.IsValid() == true );
    for (size_t ii=0; ii<g_testLen; ++ii)
        avg->AddSample(g_test[ii]);
    double result = 0.0;
    UT_ASSERT_NO_THROW( avg->GetResult(result) );

    // "Hand-calculate" the average
    double answer = 0.0;
    for (size_t ii=g_testLen-MAX_SAMPLES; ii<g_testLen; ++ii)
        answer += g_test[ii];
    answer /= MAX_SAMPLES;

    UT_ASSERT( answer == result );

    int count = -1;
    UT_ASSERT_NO_THROW( count = avg->GetNumSamples() );
    UT_ASSERT( count == MAX_SAMPLES );
    UT_ASSERT_NO_THROW( count = avg->GetMaxSamples() );
    UT_ASSERT( count == MAX_SAMPLES );

    UT_ASSERT_NO_THROW( avg->SetMaxSamples( MAX_SAMPLES + 1 ) );
    UT_ASSERT( count = avg->GetMaxSamples() );
    UT_ASSERT( count == MAX_SAMPLES + 1 );
    for (size_t ii=0; ii<g_testLen; ++ii)
        avg->AddSample(g_test[ii]);
    UT_ASSERT_NO_THROW( count = avg->GetNumSamples() );
    UT_ASSERT( count == MAX_SAMPLES + 1 );
}
Beispiel #6
0
void H264UserDataTest::TestUUID()
{
    printf("H264UserDataTest::TestUUID()\n");
    fflush(stdout);

    XRef<SEIPayload> payload = new SEIPayload(XIRef<XMemory>(new XMemory), XUuid("00000000-1111-2222-3333-444444444444"));
    CPPUNIT_ASSERT(payload->GetData()->empty());
    CPPUNIT_ASSERT(payload->GetUUID() == XUuid("00000000-1111-2222-3333-444444444444"));
}
Beispiel #7
0
  void removeSymbol( const Symbol & sym, XRef & it)
  {
    iterator item = it.begin();
    iterator last = it.end();

    while (item != last)
    {
      iterator thisOne = item++;

      if ((*thisOne).second == sym)
      {
	it.erase( thisOne );
      }
    }
  }
Beispiel #8
0
void set_media_box(PDFDoc * doc, int page, PDFRectangle * rect)
{
	XRef *xref = doc->getXRef();
	//int num = xref->getNumObjects();
	Catalog *catalog = doc->getCatalog();
	Ref *ref = catalog->getPageRef(page);

	XRefEntry *entry = xref->getEntry(ref->num);
	Object obj;
	xref->fetch(ref->num, ref->gen, &obj);
	Object *newArray =
	    mk_box_array(rect->x1, rect->y1, rect->x2, rect->y2);
	obj.dictSet((char *) "MediaBox", newArray);
	entry->obj = obj;
	entry->updated = gTrue;
}
Beispiel #9
0
void XStatisticsTest::TestAverage()
{
    XRef<XStatistics<Average,double> > avg = new XStatistics<Average,double>;
    UT_ASSERT( avg.IsValid() == true );
    for (size_t ii=0; ii<g_testLen; ++ii)
        avg->AddSample(g_test[ii]);
    double result = 0.0;
    UT_ASSERT_NO_THROW( avg->GetResult(result) );

    // "Hand-calculate" the average
    double answer = 0.0;
    for (size_t ii=0; ii<g_testLen; ++ii)
        answer += g_test[ii];
    answer /= g_testLen;

    UT_ASSERT( answer == result );
}
Beispiel #10
0
void CmnOAPIServer::run()
{
	m_port = 9080;
        XSocket socket;

        socket.Bind(m_port);
        socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		CmnOAPIServerSession *session = new CmnOAPIServerSession(m_pFactory, 
			clientSocket);
		session->start();
#if 0

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			<html>\
			<head ><title>OpenCVR</title></head>\
			<body>\
			<h1>Wellcome OpenCVR //TODO</h1><br>\
			</body>\
			</html>";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}
		
		clientSocket->Shutdown(SOCKET_SHUT_FLAGS);
		clientSocket->Close();
#endif
	}
}
Beispiel #11
0
void XStatisticsTest::TestMedian()
{
    XRef<XStatistics<Median,double> > med = new XStatistics<Median,double>;
    UT_ASSERT( med.IsValid() == true );
    for (size_t ii=0; ii<g_testLen; ++ii)
        med->AddSample(g_test[ii]);
    double result = 0.0;
    UT_ASSERT_NO_THROW( med->GetResult(result) );

    // "Hand-calculate" the median
    vector<double> sorted(g_testLen);
    for (size_t ii=0; ii<g_testLen; ++ii)
        sorted[ii] = g_test[ii];
    sort(sorted.begin(), sorted.end());
    double answer = sorted[g_testLen/2];

    UT_ASSERT( answer == result );
}
Beispiel #12
0
void H264UserDataTest::TestEmptySEI()
{
    printf("H264UserDataTest::TestEmptySEI()\n");
    fflush(stdout);

    XRef<SEIPayload> payload = new SEIPayload(XIRef<XMemory>(new XMemory));
    CPPUNIT_ASSERT(payload->GetData()->empty());
    CPPUNIT_ASSERT(payload->GetUUID() == XUuid("7e0858c4-38fe-48ea-852d-dace39badb30"));

    H264UserData before(payload);
    const std::vector<XRef<SEIPayload> >& beforePayloads = before.GetPayloads();
    CPPUNIT_ASSERT(beforePayloads.size() == 1);
    CPPUNIT_ASSERT(beforePayloads.front() == payload);
    XIRef<XMemory> sei = before.GenSEI();

    H264UserData after(sei->begin(), sei->GetDataSize());
    const std::vector<XRef<SEIPayload> >& afterPayloads = before.GetPayloads();
    CPPUNIT_ASSERT(afterPayloads.size() == 1);
    CPPUNIT_ASSERT(afterPayloads.front().Get() == payload.Get());
}
Beispiel #13
0
void CmnOAPISSLServer::run()
{
	m_port = 9554;
	XSSLSocket socket;
	socket.UsePEMCertificateFile( "C:\\videodb\\ServerCRT1.crt" );
	socket.UsePEMRSAPrivateKeyFile( "C:\\videodb\\PrivateKey1.key" );

	socket.Bind(m_port);
	socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			<html>\
			<head ><title>OpenCVR</title></head>\
			<body>\
			<h1>Wellcome OpenCVR //TODO</h1><br>\
			</body>\
			</html>";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}
		
		clientSocket->Close();
	}
}
Beispiel #14
0
int main(int argc, char *argv[])
{
	XRef<XSocket> pSocket = new XSocket;
	
	try
    {
		XSDK::XString host = "127.0.0.1";
		pSocket->Connect(host, 9080);
		
		oapi::DeviceList list;
		OAPIClient pClient(pSocket);
		
		pClient.DeviceListRequest(list);
    }
	catch( XSDK::XException& ex )
	{
		
	}
	
	x_sleep(10000);
}
Beispiel #15
0
void XStatisticsTest::TestSampleTimeout()
{
    // Add samples, wait half the expiration time, add more samples,
    // wait a little over half the expiration time, make sure half
    // the sample have been pruned.
    XRef<XStatistics<Average,double> > avg = new XStatistics<Average,double>(g_testLen*10, XDuration(XSDK::SECONDS, MAX_DURATION_SEC));
    UT_ASSERT( avg.IsValid() == true );
    for (size_t ii=0; ii<g_testLen; ++ii)
        avg->AddSample(g_test[ii]);

    x_sleep(MAX_DURATION_SEC / 2);

    for (size_t ii=0; ii<g_testLen; ++ii)
        avg->AddSample(g_test[ii]);

    x_sleep( (MAX_DURATION_SEC / 2) + (MAX_DURATION_SEC / 4) );

    double result = 0.0;
    UT_ASSERT_NO_THROW( avg->GetResult(result) );

    int count = -1;
    UT_ASSERT_NO_THROW( count = avg->GetNumSamples() );
    UT_ASSERT( count == (int)g_testLen );

    // "Hand-calculate" the average
    double answer = 0.0;
    for (size_t ii=0; ii<g_testLen; ++ii)
        answer += g_test[ii];
    answer /= g_testLen;

    UT_ASSERT( answer == result );
}
Beispiel #16
0
void TranscodeExport::_FinishInit( XRef<H264Encoder>& encoder,
                                   XRef<AVMuxer>& muxer,
                                   H264Decoder& decoder,
                                   const XString& tempFileName,
                                   bool outputToFile,
                                   int traversalNum,
                                   int traversalDen )
{
    // Now that we have decoded the first frame, we can finish initializing everything...

    // First, we should finish initializing our Decoder by setting an output resolution.
    uint16_t width = 0;
    uint16_t height = 0;

    AspectCorrectDimensions( decoder.GetInputWidth(), decoder.GetInputHeight(),
                             _requestedWidth, _requestedHeight,
                             width, height );

    decoder.SetOutputWidth( width );
    decoder.SetOutputHeight( height );

    // Configure and create our encoder...
    int timeBaseNum = 0;
    int timeBaseDen = 0;
    AVKit::DToQ( (1 / _frameRate), timeBaseNum, timeBaseDen );

    CodecOptions options = GetCRFH264EncoderOptions( 26, width, height, 15, timeBaseNum, timeBaseDen );

    encoder = new H264Encoder( options, false );

    // Create our muxer...
    muxer = new AVMuxer( encoder->GetOptions(),
                         tempFileName,
                         (outputToFile) ? AVMuxer::OUTPUT_LOCATION_FILE : AVMuxer::OUTPUT_LOCATION_BUFFER );

    // Finally, provide the muxer with our encoders extra data so we create valid conainers.
    muxer->SetExtraData( encoder->GetExtraData() );
}
Beispiel #17
0
void ClientSideResponse::_CleanSocket(XRef<XStreamIO> socket, char** writer)
{
    if ( socket.IsEmpty() )
        X_STHROW(WebbyException, ("StreamIO is null"));

    if(!socket->Valid())
        X_STHROW(WebbyException, ("Invalid Socket"));

    char tempBuffer[1];

    // Clear junk off the socket
    while(true)
    {
        if(!_ReceiveData(socket, tempBuffer, 1))
            X_STHROW(WebbyException, ("Failed to read data from socket->"));

        if(!XString::IsSpace(tempBuffer[0]))
        {
            **writer = tempBuffer[0];
            ++*writer;
            break;
        }
    }
}
Beispiel #18
0
void AVMuxerTest::TestRecontainerize()
{
    struct CodecOptions options;

    options.gop_size = 15;
    options.bit_rate = 1424400; // size of gop * 8 == bit_rate
    options.width = 1280;
    options.height = 720;
    options.time_base_num = 1;
    options.time_base_den = 30;

    XRef<AVMuxer> c = new AVMuxer( options,
                                   "bar.mp4",
                                   AVMuxer::OUTPUT_LOCATION_FILE );

    for( int i = 0; i < NUM_FRAMES_IN_GOP; i++ )
    {
        int index = i % NUM_FRAMES_IN_GOP;
        XIRef<Packet> pkt = new Packet( gop[index].frame, gop[index].frameSize, false );
        c->WriteVideoPacket( pkt, ((i % 15) == 0) ? true : false );
    }

    c->FinalizeFile();
}
Beispiel #19
0
int _main(int argc, char* argv[], stringstream * preLog)
{
  int fromPage = 1;
  int toPage = 0;
  char * usageString = "\npdfToText: Wrong arguments. Usage: pdfToText(.exe) [input pdf file] [otput txt file] [optional args]\n\
                       Optional arguments are: -pfrom [page number], -pto [page number], -logenabled\n";

  if(argc < 3 || argc > 8) //program inputFile oputputFile [optional]
	{
		cerr << "\npdfToText: Wrong number of arguments.\n";
		cout << usageString;
		return 1;
	}
		
	char * inputFilePath = argv[1];
  //Open the PDF source file:
  *preLog << "\nOpening source file " << inputFilePath;
  cerr << "Input file: " << inputFilePath << endl;
	ifstream filei (inputFilePath, ios::binary);
	if (!filei.is_open() || !filei.good())
	{
		cerr << "\npdfToText: Could not open input file";
    cout << "\nCould not open input file.";
		return 2; //files couldnt be opened
	}
	filei.clear();

	char * outputFilePath = argv[2];
	//Discard existing output:
	*preLog << "\nOpening output file " << outputFilePath;
  FILE * fileo = fopen( outputFilePath, "wb");
	if (fileo == null)
	{
		cerr << "\npdfToText: Could not open output file";
    cout << "\nCould not open output file";
		return 2; //files couldnt be opened
	}

  //Process optional arguments
  for(int argindex = 3; argindex < argc; argindex++)
  {
    if(stricmp(argv[argindex], "-pfrom") == 0)
    {
      if(argindex+1 < argc)
      {
        argindex++;
        long int pfrom = strtol(argv[argindex], null, 10);
        if(pfrom > 0 && pfrom < INT_MAX)
        {
          fromPage = (int) pfrom;
          continue;
        }
      }
    }
    if(stricmp(argv[argindex], "-pto") == 0)
    {
      if(argindex+1 < argc)
      {
        argindex++;
        long int pto = strtol(argv[argindex], null, 10);
        if(pto > 0 && pto < INT_MAX)
        {
          toPage = (int) pto;
          continue;
        }
      }
    }
    if(stricmp(argv[argindex], "-logenabled") == 0)
    {
      logEnabled = true;
      continue;
    }
    cerr << "\npdfToText: Wrong arguments.\n";
    cout << usageString;
    return 1;
  }

  if(logEnabled)
  {
    clog<<preLog->str();
  }

	conv_desc = iconv_open ("WCHAR_T", "UTF-16BE");
	if (conv_desc == (iconv_t)-1)
	{
		/* Initialization failure. */
		cerr << "\npdfToText: Iconv init failed.\n";
		return 5;
	}
	//-----------------------------------------------
	//---- Read reference table and find objects ----
  if(logEnabled)
		clog<< "\n\n-=| Finding refference table and its objects |=-\n";

	objectMap = new map < pair<int,int>, IndirectObject*>;
	map <pair<int,int>, IndirectObject*>::iterator objectMapIterator;

	XRef * refTable = new XRef(filei);
  XRef * firstRefTable = refTable;
  if(logEnabled)
    clog<<"\n\nProcessing refference table...";
  while(refTable != null && refTable->getXRef() != null)
	{
		XRefSubsection * sections = refTable->getXRef();
		int i,j;
		for(i=0;i<refTable->sectionCount;i++)
		{
			for(j=0;j<XRefSubsection(sections[i]).count;j++)
			{
				int objectNum = XRefSubsection(sections[i]).firstObjectNumber + j;
				IndirectObject * po = new IndirectObject(
					XRefSubsection(sections[i]).table[j], objectNum, filei);
        (*objectMap)[make_pair(po->objectNumber, po->generationNumber)] = po;
				/*if(logEnabled)
				{
					if(po->objectState == IN_USE_OBJECT)
						clog<<"\n"<<po->objectNumber<<" "<<po->objectState<<" "<<po->byteOffset<<" ("<<po->generationNumber<<")";
					else
						clog<<"\n"<<po->objectNumber<<" "<<po->objectState<<" "<<po->nextFreeObject<<" ("<<po->generationNumber<<")";
				}*/
			}
		}
		refTable = refTable->getNextXRef();
	}

  if(logEnabled)
    clog<<"\nFound " << objectMap->size() << " indirect objects.";

  if(objectMap->size() <= 0)
  {
    cerr << "\npdfToText: No objects found in reference table.\n";
    return 4;
  }
	
	//----------------------
	//---- Load objects ----
	if(logEnabled)
		clog<< "\n\n-=| Loading Objects |=-\n";
  
  int loadedCount = 0;

	for ( objectMapIterator = objectMap->begin(); objectMapIterator != objectMap->end();
		objectMapIterator++)
  {
    if((*objectMapIterator).second->load())
      loadedCount++;
  }

  if(logEnabled)
    clog<<"\nLoaded " << loadedCount << " in use indirect objects.";

  //------------------------
  //---- Read Page tree ----
  if(logEnabled)
		clog<< "\n\n-=| Reading Page tree |=-\n";
  if(firstRefTable == null || firstRefTable->getXRef() == null || firstRefTable->trailerDictionary == null || firstRefTable->trailerDictionary->getObject("/Root") == null)
  {
    cerr<<"\npdfToText: Couldn't find Document Catalog in PDF file.\n";
    return 3;
  }
  IndirectObject * indirectObject = (IndirectObject*) firstRefTable->trailerDictionary->getObject("/Root");
  DictionaryObject * documentCatalogDictionary = (DictionaryObject*) indirectObject->getFirstObject();
  if(documentCatalogDictionary == null || documentCatalogDictionary->objectType != PdfObject::TYPE_DICTIONARY)
  {
    cerr<<"\npdfToText: Problem with reading Document Catalog in PDF file.\n";
    return 3;
  }
  if(logEnabled)
    clog<<"\nDocument catalog found in object "<<indirectObject->objectNumber<<" "<<indirectObject->generationNumber<<" R.";
  if(documentCatalogDictionary->getObject("/Pages") == null)
  {
    cerr<<"\npdfToText: Couldn't find page tree in Document Catalog in PDF file.\n";
    return 3;
  }
  indirectObject = (IndirectObject*) documentCatalogDictionary->getObject("/Pages");
  DictionaryObject * pageTreeRootDictionary = (DictionaryObject*) indirectObject->getFirstObject();
  if(pageTreeRootDictionary == null || pageTreeRootDictionary->objectType != PdfObject::TYPE_DICTIONARY)
  {
    cerr<<"\npdfToText: Problem with reading Page Tree root node dictionary in PDF file.\n";
    return 3;
  }
  if(logEnabled)
    clog<<"\nPage tree root node dictionary found in object "<<indirectObject->objectNumber<<" "<<indirectObject->generationNumber<<" R.";
  if(logEnabled)
    clog<<"\nConstructing page tree ...";
  PageTreeNode * pageTreeRoot = new PageTreeNode(pageTreeRootDictionary);
  list<PageTreeNode*> pageList;
  list<PageTreeNode*>::iterator pageListIterator;
  pageTreeRoot->createPageList(&pageList);
  
  //skip specified pages
  if(toPage == 0)
    toPage = pageList.size();
  if((toPage - fromPage + 1) > 0 && (toPage - fromPage + 1) <= pageList.size())
  {
    int ii;
    int endCut = pageList.size() - toPage;
    for(ii = 0; ii<endCut; ii++)
      pageList.pop_back();
    for(ii = 1; ii<fromPage; ii++)
      pageList.pop_front();
  }
  else
  {
    cerr << "\npdfToText: Wrong page range specified in arguments.\n";
    return 1;
  }

  if(logEnabled)
    clog<<"\nPage tree construction finished. \nFound " << pageList.size() << " pages.";

	//-------------------------
	//---- Process objects ----

  if(logEnabled)
		clog<< "\n\n-=| Processing Pages Content Streams |=-\n";

  if(pageList.size() > 0)
  {
    for(pageListIterator = pageList.begin(); pageListIterator != pageList.end(); pageListIterator++)
    {
      (*pageListIterator)->processPage();
    }
  }
  else
  {
    cerr<<"\nNo pages found in a page tree. Nothing to extract.\n";
    return 3;
  }
  
  //-------------------------------
	//---- Get text from objects ----
	if(logEnabled)
		clog<< "\n\n-=| Getting text from Content Streams |=-\n";
	
  for(pageListIterator = pageList.begin(); pageListIterator != pageList.end(); pageListIterator++)
  {
    (*pageListIterator)->getText(fileo);
  }
  fclose(fileo);
	return 0;
}
Beispiel #20
0
void TranscodeExport::Create( XIRef<XMemory> output )
{
    XString tempFileName = _GetTMPName( _fileName );

    // If their is only 1 export in progress (us), but the temp file exists then it means we were interrupted
    // (either a power issue, or a segfault) and we should delete the temporary.
    if( _exportsInProgress == 1 )
    {
        if( XPath::Exists(tempFileName) )
            unlink(tempFileName.c_str());
    }

    if( XPath::Exists(tempFileName) )
        X_THROW(("Export in progress exception: %s", tempFileName.c_str()));

    bool outputToFile = (output.IsEmpty()) ? true : false;
    H264Decoder decoder( GetFastH264DecoderOptions() );
    XRef<YUV420PToARGB24> yuvToARGB = new YUV420PToARGB24;
    XRef<ARGB24ToYUV420P> argbToYUV = new ARGB24ToYUV420P;
    XRef<H264Transcoder> transcoder;
    XRef<H264Encoder> encoder;
    XRef<AVMuxer> muxer;
    XRef<ExportOverlay> ov;
    bool wroteToContainer = false;

    auto lastProgressTime = steady_clock::now();

    // We are going to count how many decoding or encoding exceptions we get... If it
    // ever exceeds some large threshold, we bail on this export.
    int64_t codingExceptions = 0;

    XString recorderURI;
    while( _recorderURLS.GetNextURL( recorderURI ) )
    {
        auto now = steady_clock::now();
        if( wroteToContainer && duration_cast<seconds>(now-lastProgressTime).count() > 2 )
        {
            _progress( _recorderURLS.PercentComplete() );
            lastProgressTime = now;
        }
        
        try
        {
            XIRef<XMemory> responseBuffer = FRAME_STORE_CLIENT::FetchMedia( _config->GetRecorderIP(),
                                                                            _config->GetRecorderPort(),
                                                                            recorderURI );

            ResultParser resultParser;

            resultParser.Parse( responseBuffer );

            FRAME_STORE_CLIENT::ResultStatistics stats = resultParser.GetStatistics();

            // If we are not provided with a bit rate or a frame rate, we use the sources values.
            if( _bitRate == 0 )
                _bitRate = stats.averageBitRate;
            
            if( _maxRate == 0 )
                _maxRate = 2 * stats.averageBitRate;

            if( _bufSize == 0 )
                _bufSize = 2 * stats.averageBitRate;

            if( _frameRate == 0.0 )
                _frameRate = stats.frameRate;

            // Fix for ffmpeg's inability to make files with fps < 6.0. Don't believe me? Try these 2 commands and play
            // output in vlc:
            //
            //   # generate a test movie of the game of life in life.mp4
            //   ffmpeg -f lavfi -i life -frames:v 1000 life.mp4
            //   # transcode and drop framerate of life.mp4 to 1 fps. output.mp4 won't play in vlc and will have a weird
            //   # pause at the beginning for other players.
            //   ffmpeg -i life.mp4 -vf fps=fps=1/1 -vcodec h264 output.mp4
            //
            if( _frameRate < 6.0 )
                _frameRate = 6.0;

            int outputTimeBaseNum = 0;
            int outputTimeBaseDen = 0;
            int inputTimeBaseNum = 0;
            int inputTimeBaseDen = 0;

            AVKit::DToQ( (1/stats.frameRate), inputTimeBaseNum, inputTimeBaseDen );
            AVKit::DToQ( (1/_frameRate), outputTimeBaseNum, outputTimeBaseDen );

            if( transcoder.IsEmpty() )
            {
                transcoder = new H264Transcoder( inputTimeBaseNum, inputTimeBaseDen,
                                                 outputTimeBaseNum, outputTimeBaseDen,
                                                 _speed,
                                                 // if our input is key only, enable decode skipping...
                                                 _recorderURLS.KeyFrameOnly() );
            }

            double secondsPer = AVKit::QToD(inputTimeBaseNum, inputTimeBaseDen) / (AVKit::QToD(inputTimeBaseNum, inputTimeBaseDen) / (AVKit::QToD(outputTimeBaseNum, outputTimeBaseDen) * _speed));
            int traversalNum = 0;
            int traversalDen = 0;

            AVKit::DToQ( secondsPer, traversalNum, traversalDen );

            while( !resultParser.EndOfFile() )
            {
                try
                {
                    if( transcoder->Decode( resultParser, decoder ) )
                    {
                        if( encoder.IsEmpty() )
                            _FinishInit( encoder, muxer, decoder, tempFileName, outputToFile, traversalNum, traversalDen );

                        if( ov.IsEmpty() )
                            ov = new ExportOverlay( _msg,
                                                    _withTime,
                                                    _hAlign,
                                                    _vAlign,
                                                    decoder.GetOutputWidth(),
                                                    decoder.GetOutputHeight(),
                                                    traversalNum,
                                                    traversalDen );

                        yuvToARGB->Transform( decoder.Get(), decoder.GetOutputWidth(), decoder.GetOutputHeight() );

                        XIRef<Packet> rgb = yuvToARGB->Get();

                        XIRef<Packet> withOverlay = ov->Process( rgb, resultParser.GetFrameTS() );

                        argbToYUV->Transform( withOverlay, decoder.GetOutputWidth(), decoder.GetOutputHeight() );

                        transcoder->EncodeYUV420PAndMux( *encoder, *muxer, argbToYUV->Get() );
                        wroteToContainer = true;
                    }
                }
                catch(XException& ex)
                {
                    X_LOG_NOTICE("Coding exception: %s",ex.what());
                    
                    ++codingExceptions;

                    // If we have had a LOT of decoding or encoding exceptions, just give up.
                    if( codingExceptions > 100000 )
                        throw ex;
                }
            }
        }
        catch( XException& ex )
        {
            X_LOG_NOTICE("Exception thrown while processing export. Continuing: %s",ex.what());
        }
    }

	if( wroteToContainer )
        _progress( 1.0 );
    else X_STHROW( HTTP404Exception, ("No video was found during entire export."));

    if( outputToFile )
    {
        muxer->FinalizeFile();
        rename( tempFileName.c_str(), _fileName.c_str() );
    }
    else muxer->FinalizeBuffer( output );
}
Beispiel #21
0
bool ClientSideResponse::_ReceiveData(XRef<XStreamIO> socket, void* data, size_t dataLen)
{
    const ssize_t bytesSent = socket->Recv(data, dataLen);

    return socket->Valid() && bytesSent == (ssize_t)dataLen;
}
Beispiel #22
0
 void Clear(void)
 {
   refs.clear();
   sfer.clear();
 }
Beispiel #23
0
void TestOptionalContent::checkIsVisible()
{
    GooString *fileName = new GooString(TESTDATADIR "/unittestcases/vis_policy_test.pdf");
    globalParams = new GlobalParams();
    PDFDoc *doc = new PDFDoc( fileName );
    QVERIFY( doc );

    OCGs *ocgs = doc->getOptContentConfig();
    QVERIFY( ocgs );

    XRef *xref = doc->getXRef();

    Object obj;

    // In this test, both Ref(21,0) and Ref(2,0) are set to On

    // AnyOn, one element array:
    // 22 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOn>>endobj
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QVERIFY( ocgs->optContentIsVisible( &obj ) );
    obj.free();

    // Same again, looking for any leaks or dubious free()'s
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QVERIFY( ocgs->optContentIsVisible( &obj ) );
    obj.free();

    // AnyOff, one element array:
    // 29 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOff>>endobj
    xref->fetch( 29, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOn, one element array:
    // 36 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOn>>endobj
    xref->fetch( 36, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();


    // AllOff, one element array:
    // 43 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOff>>endobj
    xref->fetch( 43, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AnyOn, multi-element array:
    // 50 0 obj<</Type/OCMD/OCGs[21 0 R 28 0 R]/P/AnyOn>>endobj
    xref->fetch( 50, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOff, multi-element array:
    // 57 0 obj<</Type/OCMD/P/AnyOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 57, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOn, multi-element array:
    // 64 0 obj<</Type/OCMD/P/AllOn/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 64, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOff, multi-element array:
    // 71 0 obj<</Type/OCMD/P/AllOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 71, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    delete doc;
    delete globalParams;
}
Beispiel #24
0
 void addPair( const Symbol & sym, const Symbol & ref )
 {
   refs.insert( value_type( sym, ref ) );
   sfer.insert( value_type( ref, sym ) );
 }
Beispiel #25
0
void AVMuxerTest::TestBuffer()
{
    XRef<H264Decoder> d = new H264Decoder( GetFastH264DecoderOptions() );
    d->SetOutputWidth( 640 );
    d->SetOutputHeight( 360 );
    XRef<H264Encoder> e = new H264Encoder( GetFastH264EncoderOptions( 250000, 640, 360, 15, 1, 15 ) );
    XRef<AVMuxer> c = new AVMuxer( e->GetOptions(),
                                   "foo.mp4",
                                   AVMuxer::OUTPUT_LOCATION_BUFFER );

    c->SetExtraData( e->GetExtraData() );

    for( int i = 0; i < NUM_FRAMES_IN_GOP; i++ )
    {
        int index = i % NUM_FRAMES_IN_GOP;

        XIRef<Packet> pkt = new Packet( gop[index].frame, gop[index].frameSize, false );
        d->Decode( pkt );
        e->EncodeYUV420P( d->Get() );
        c->WriteVideoPacket( e->Get(), ((i % 15) == 0) ? true : false );
    }

    XIRef<XMemory> buffer = new XMemory;
    c->FinalizeBuffer( buffer );
}
Beispiel #26
0
void AVMuxerTest::TSLeak()
{
	// avformat_write_trailer() isn't called on every file for .ts files. This caused
	// a leak. The solution is to call it in dtor after file/buffer is done.

    XRef<H264Decoder> d = new H264Decoder( GetFastH264DecoderOptions() );
    d->SetOutputWidth( 640 );
    d->SetOutputHeight( 360 );
    XRef<H264Encoder> e = new H264Encoder( GetHLSH264EncoderOptions( 250000, 640, 360, 15, 1, 15 ) );
    XRef<AVMuxer> c = new AVMuxer( e->GetOptions(),
                                   "foo.ts",
                                   AVMuxer::OUTPUT_LOCATION_BUFFER );

    c->SetExtraData( e->GetExtraData() );

    for( int i = 0; i < NUM_FRAMES_IN_GOP; i++ )
    {
        int index = i % NUM_FRAMES_IN_GOP;

        XIRef<Packet> pkt = new Packet( gop[index].frame, gop[index].frameSize, false );
        d->Decode( pkt );
        e->EncodeYUV420P( d->Get() );
        c->WriteVideoPacket( e->Get(), ((i % 15) == 0) ? true : false );
    }

    XIRef<XMemory> buffer = new XMemory;
    c->FinalizeBuffer(buffer);
}
Beispiel #27
0
void TestOptionalContent::checkVisibilitySetting()
{
    globalParams = new GlobalParams();
    GooString *fileName = new GooString(TESTDATADIR "/unittestcases/vis_policy_test.pdf");
    PDFDoc *doc = new PDFDoc( fileName );
    QVERIFY( doc );

    OCGs *ocgs = doc->getOptContentConfig();
    QVERIFY( ocgs );

    XRef *xref = doc->getXRef();

    Object obj;

    // In this test, both Ref(21,0) and Ref(28,0) start On,
    // based on the file settings
    Object ref21obj;
    ref21obj.initRef( 21, 0 );
    Ref ref21 = ref21obj.getRef();
    OptionalContentGroup *ocgA = ocgs->findOcgByRef( ref21 );
    QVERIFY( ocgA );

    QVERIFY( (ocgA->getName()->cmp("A")) == 0 );
    QCOMPARE( ocgA->getState(), OptionalContentGroup::On );

    Object ref28obj;
    ref28obj.initRef( 28, 0 );
    Ref ref28 = ref28obj.getRef();
    OptionalContentGroup *ocgB = ocgs->findOcgByRef( ref28 );
    QVERIFY( ocgB );

    QVERIFY( (ocgB->getName()->cmp("B")) == 0 );
    QCOMPARE( ocgB->getState(), OptionalContentGroup::On );

    // turn one Off
    ocgA->setState( OptionalContentGroup::Off );

    // AnyOn, one element array:
    // 22 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOn>>endobj
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // Same again, looking for any leaks or dubious free()'s
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AnyOff, one element array:
    // 29 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOff>>endobj
    xref->fetch( 29, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOn, one element array:
    // 36 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOn>>endobj
    xref->fetch( 36, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOff, one element array:
    // 43 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOff>>endobj
    xref->fetch( 43, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AnyOn, multi-element array:
    // 50 0 obj<</Type/OCMD/OCGs[21 0 R 28 0 R]/P/AnyOn>>endobj
    xref->fetch( 50, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOff, multi-element array:
    // 57 0 obj<</Type/OCMD/P/AnyOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 57, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOn, multi-element array:
    // 64 0 obj<</Type/OCMD/P/AllOn/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 64, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOff, multi-element array:
    // 71 0 obj<</Type/OCMD/P/AllOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 71, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();


    // Turn the other one off as well (i.e. both are Off)
    ocgB->setState(OptionalContentGroup::Off);

    // AnyOn, one element array:
    // 22 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOn>>endobj
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // Same again, looking for any leaks or dubious free()'s
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AnyOff, one element array:
    // 29 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOff>>endobj
    xref->fetch( 29, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOn, one element array:
    // 36 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOn>>endobj
    xref->fetch( 36, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOff, one element array:
    // 43 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOff>>endobj
    xref->fetch( 43, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOn, multi-element array:
    // 50 0 obj<</Type/OCMD/OCGs[21 0 R 28 0 R]/P/AnyOn>>endobj
    xref->fetch( 50, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AnyOff, multi-element array:
    // 57 0 obj<</Type/OCMD/P/AnyOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 57, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOn, multi-element array:
    // 64 0 obj<</Type/OCMD/P/AllOn/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 64, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOff, multi-element array:
    // 71 0 obj<</Type/OCMD/P/AllOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 71, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();


    // Turn the first one on again (21 is On, 28 is Off)
    ocgA->setState(OptionalContentGroup::On);

    // AnyOn, one element array:
    // 22 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOn>>endobj
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // Same again, looking for any leaks or dubious free()'s
    xref->fetch( 22, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOff, one element array:
    // 29 0 obj<</Type/OCMD/OCGs[21 0 R]/P/AnyOff>>endobj
    xref->fetch( 29, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOn, one element array:
    // 36 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOn>>endobj
    xref->fetch( 36, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOff, one element array:
    // 43 0 obj<</Type/OCMD/OCGs[28 0 R]/P/AllOff>>endobj
    xref->fetch( 43, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOn, multi-element array:
    // 50 0 obj<</Type/OCMD/OCGs[21 0 R 28 0 R]/P/AnyOn>>endobj
    xref->fetch( 50, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AnyOff, multi-element array:
    // 57 0 obj<</Type/OCMD/P/AnyOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 57, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), true );
    obj.free();

    // AllOn, multi-element array:
    // 64 0 obj<</Type/OCMD/P/AllOn/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 64, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    // AllOff, multi-element array:
    // 71 0 obj<</Type/OCMD/P/AllOff/OCGs[21 0 R 28 0 R]>>endobj
    xref->fetch( 71, 0, &obj );
    QVERIFY( obj.isDict() );
    QCOMPARE( ocgs->optContentIsVisible( &obj ), false );
    obj.free();

    delete doc;
    delete globalParams;
}