bool grab_pa_syms(std::string pulse_dso_name)
{
	if (sSymsGrabbed)
	{
		// already have grabbed good syms
		return true;
	}

	bool sym_error = false;
	bool rtn = false;
	apr_status_t rv;
	apr_dso_handle_t *sSymPADSOHandle = NULL;

#define LL_PA_SYM(REQUIRED, PASYM, RTN, ...) do{rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll##PASYM, sSymPADSOHandle, #PASYM); if (rv != APR_SUCCESS) {INFOMSG("Failed to grab symbol: %s", #PASYM); if (REQUIRED) sym_error = true;} else DEBUGMSG("grabbed symbol: %s from %p", #PASYM, (void*)ll##PASYM);}while(0)

	//attempt to load the shared library
	apr_pool_create(&sSymPADSOMemoryPool, NULL);
  
	if ( APR_SUCCESS == (rv = apr_dso_load(&sSymPADSOHandle,
					       pulse_dso_name.c_str(),
					       sSymPADSOMemoryPool) ))
	{
		INFOMSG("Found DSO: %s", pulse_dso_name.c_str());

#include "linux_volume_catcher_pa_syms.inc"
#include "linux_volume_catcher_paglib_syms.inc"
      
		if ( sSymPADSOHandle )
		{
			sSymPADSOHandleG = sSymPADSOHandle;
			sSymPADSOHandle = NULL;
		}
      
		rtn = !sym_error;
	}
	else
	{
		INFOMSG("Couldn't load DSO: %s", pulse_dso_name.c_str());
		rtn = false; // failure
	}

	if (sym_error)
	{
		WARNMSG("Failed to find necessary symbols in PulseAudio libraries.");
	}
#undef LL_PA_SYM

	sSymsGrabbed = rtn;
	return rtn;
}
bool grab_dbus_syms(std::string dbus_dso_name)
{
	if (sSymsGrabbed)
	{
		// already have grabbed good syms
		return TRUE;
	}

	bool sym_error = false;
	bool rtn = false;
	apr_status_t rv;
	apr_dso_handle_t *sSymDBUSDSOHandle = NULL;

#define LL_DBUS_SYM(REQUIRED, DBUSSYM, RTN, ...) do{rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll##DBUSSYM, sSymDBUSDSOHandle, #DBUSSYM); if (rv != APR_SUCCESS) {INFOMSG("Failed to grab symbol: %s", #DBUSSYM); if (REQUIRED) sym_error = true;} else DEBUGMSG("grabbed symbol: %s from %p", #DBUSSYM, (void*)ll##DBUSSYM);}while(0)

	//attempt to load the shared library
	apr_pool_create(&sSymDBUSDSOMemoryPool, NULL);
  
	if ( APR_SUCCESS == (rv = apr_dso_load(&sSymDBUSDSOHandle,
					       dbus_dso_name.c_str(),
					       sSymDBUSDSOMemoryPool) ))
	{
		INFOMSG("Found DSO: %s", dbus_dso_name.c_str());

#include "llappviewerlinux_api_dbus_syms_raw.inc"
      
		if ( sSymDBUSDSOHandle )
		{
			sSymDBUSDSOHandleG = sSymDBUSDSOHandle;
			sSymDBUSDSOHandle = NULL;
		}
      
		rtn = !sym_error;
	}
	else
	{
		INFOMSG("Couldn't load DSO: %s", dbus_dso_name.c_str());
		rtn = false; // failure
	}

	if (sym_error)
	{
		WARNMSG("Failed to find necessary symbols in DBUS-GLIB libraries.");
	}
#undef LL_DBUS_SYM

	sSymsGrabbed = rtn;
	return rtn;
}
Esempio n. 3
0
static void
logToAllLevels(
    void               *v_name)
{
#define ST_ND_TH(c) \
    ((((c) % 10) == 1) ? "st" : ((((c) % 10) == 2) ? "nd" : "th"))

    int c;
    char *name = (char *)v_name;

    pthread_mutex_lock(&count_mutex);
    c = ++global_count;
    pthread_mutex_unlock(&count_mutex);

    if (test_emerg) {
        EMERGMSG("Writing a EMERGMSG for the %d%s time [%s]",
                 c, ST_ND_TH(c), name);
    }
    ALERTMSG("Writing a ALERTMSG for the %d%s time [%s]",
             c, ST_ND_TH(c), name);
    CRITMSG("Writing a CRITMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    ERRMSG("Writing a ERRMSG for the %d%s time [%s]",
           c, ST_ND_TH(c), name);
    WARNINGMSG("Writing a WARNINGMSG for the %d%s time [%s]",
               c, ST_ND_TH(c), name);
    NOTICEMSG("Writing a NOTICEMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    INFOMSG("Writing a INFOMSG for the %d%s time [%s]",
            c, ST_ND_TH(c), name);
    DEBUGMSG("Writing a DEBUGMSG for the %d%s time [%s]",
             c, ST_ND_TH(c), name);
}
Esempio n. 4
0
CameraView::~CameraView()
{
        
	DEBUGMSG(("starting to stop cameraView..."));
	if(isCameraConnected)
	{
		// Stop processing thread
		if(processingThread->isRunning())
			stopProcessingThread();
		// Stop capture thread
		if(captureThread->isRunning())
			stopCaptureThread();
		
		// Remove from shared buffer
		sharedImageBuffer->remove(id);
		
		
		// Disconnect camera
		if(captureThread->disconnectCamera()){
			// INFOMSG(("[ %d ]Camera successfully disconnected.",id));
		}else{
			// INFOMSG(( "[ %d ] WARNING: Camera already disconnected.",id));
		}
	}
	while(captureThread->isRunning())
	{
	        usleep(2000);
	        INFOMSG(("."));
	}
	// Delete UI
	delete ui;
}
Esempio n. 5
0
void CameraView::connectStream()
{
	
	// Create processing thread
	processingThread = new ProcessingThread(sharedImageBuffer, tabId,id);
	
	// Setup signal/slot connections
	connect(processingThread, SIGNAL(newFrame(QImage)), this, SLOT(updateFrame(QImage)));
	connect(processingThread, SIGNAL(updateStatisticsInGUI(struct ThreadStatisticsData)), this, SLOT(updateProcessingThreadStats(struct ThreadStatisticsData)));
	connect(captureThread, SIGNAL(updateStatisticsInGUI(struct ThreadStatisticsData)), this, SLOT(updateCaptureThreadStats(struct ThreadStatisticsData)));
	connect(this, SIGNAL(setROI(QRect)), processingThread, SLOT(setROI(QRect)));
	// Only enable ROI setting/resetting if frame processing is enabled
	connect(ui->frameLabel, SIGNAL(newMouseData(struct MouseData)), this, SLOT(newMouseData(struct MouseData)));
	
	// Set initial data in processing thread
	// emit setROI(QRect(0, 0, captureThread->getInputSourceWidth(), captureThread->getInputSourceHeight()));
	
	// Start capturing frames from camera
	captureThread->start((QThread::Priority)QThread::NormalPriority);
	// Start processing captured frames (if enabled)
	
	processingThread->start((QThread::Priority)QThread::TimeCriticalPriority);
	
	// Setup imageBufferBar with minimum and maximum values
	ui->imageBufferBar->setMinimum(0);
	ui->imageBufferBar->setMaximum(sharedImageBuffer->maxSize());
	// Enable/disable appropriate GUI items
	//ui->imageProcessingMenu->setEnabled(enableFrameProcessing);
	//ui->imageProcessingSettingsAction->setEnabled(enableFrameProcessing);
	// Enable "Clear Image Buffer" push button
	ui->clearImageBufferButton->setEnabled(true);
	// Set text in labels
	// ui->deviceNumberLabel->setNum(tabId);
	ui->cameraResolutionLabel->setText(
	        QString::number(captureThread->getInputSourceWidth())+
	        QString("x")+
	        QString::number(captureThread->getInputSourceHeight())+
	        QString(" (")+
	        QString::number(ui->frameLabel->width())+
	        QString("x")+
	        QString::number(ui->frameLabel->height())+
	        QString(")")
	        );
	// Set internal flag and return
	isCameraConnected=true;
	// Set frame label text
	
	
	loadLinesSettings();
	
	if(captureThread->getInputSourceWidth() > ui->frameLabel->width())
	{
	        processingThread->resizeToFitWindow = true;
	        INFOMSG(("resizing to fit window"));
	}
}
void ViewerWindowBase::UpdateGeometryViolations(void) const
{
    const ViewerBase::AlignmentList& alignments = viewer->GetCurrentAlignments();
    ViewerBase::AlignmentList::const_iterator a, ae = alignments.end();
    int nViolations = 0;
    for (a=alignments.begin(); a!=ae; ++a)
        nViolations += (*a)->ShowGeometryViolations(GeometryViolationsShown());
    if (GeometryViolationsShown())
        INFOMSG("Found " << nViolations << " geometry violation"
            << ((nViolations == 1) ? "" : "s") << " in this window");
}
Esempio n. 7
0
void CWallTool::OnCloak ()
{
for (BOOL bSide = FALSE; bSide <= m_bBothSides; bSide++)
	if (m_pWall [bSide]) {
		UpdateData (TRUE);
		theApp.SetModified (TRUE);
		m_defWall.cloak_value =
		m_pWall [bSide]->cloak_value = (INT8) (m_nCloak * 31.0 / 100.0) % 32;
		}
	else
		INFOMSG ("wall not found");
}
Esempio n. 8
0
bool clsYarp::connectPort(char *portIn,char *portOut, char *protocol)
{
	portIsOK = yarp::os::Network::connect(portIn,portOut,protocol);
	
	if(!portIsOK)
	{
	        WARNMSG(("failed to connect %s to %s with %s",portIn,portOut,protocol));
	        return false;
	}
	INFOMSG(("connected %s to %s with %s",portIn,portOut,protocol));
	return true;
}
Esempio n. 9
0
static void *
thread_c(
    void        UNUSED(*dummy))
{
    skDQErr_t err;

    meet();

    INFOMSG("**** Test 1 ****");
    err = skDequePushFront(da, (void*)xa);
    XASSERT(err == SKDQ_SUCCESS);
    starta();
    meet();

    INFOMSG("**** Test 2 ****");
    starta();
    SLEEP(1);
    err = skDequePushFront(da, (void*)xa);
    XASSERT(err == SKDQ_SUCCESS);
    meet();

    INFOMSG("**** Test 3 ****");
    starta();
    SLEEP(1);
    startb();
    SLEEP(1);
    err = skDequePushFront(da, (void*)xa);
    XASSERT(err == SKDQ_SUCCESS);
    err = skDequePushFront(da, (void*)xb);
    XASSERT(err == SKDQ_SUCCESS);
    meet();
    XASSERT(resulta == 1 && resultb == 1);

    /* End */
    starta();
    startb();

    return NULL;
}
Esempio n. 10
0
/*
 *  status = readerStart(flow_processor);
 *
 *    Invoked by input_mode_type->start_fn();
 */
static int
readerStart(
    flow_proc_t UNUSED(*fproc))
{
    /* Create the polldir object for directory polling */
    INFOMSG(("Creating " INPUT_MODE_TYPE_NAME " directory poller for '%s'"),
            incoming_directory);

    polldir = skPollDirCreate(incoming_directory, polling_interval);
    if (NULL == polldir) {
        CRITMSG("Could not initiate polling for %s", incoming_directory);
        return 1;
    }

    return 0;
}
Esempio n. 11
0
/*
 *  readerPrintStats(flow_processor);
 *
 *    Invoked by input_mode_type->print_stats_fn();
 */
static void
readerPrintStats(
    flow_proc_t        *fproc)
{
    skPDUSource_t *pdu_src = (skPDUSource_t*)fproc->flow_src;

    if (pdu_src) {
        skPDUSourceLogStatsAndClear(pdu_src);
    }
    if (fproc->rec_count_bad) {
        INFOMSG(("'%s': Records categorized %" PRIu64 ", dropped %" PRIu64),
                skpcProbeGetFileSource(fproc->probe),
                (fproc->rec_count_total - fproc->rec_count_bad),
                fproc->rec_count_bad);
    }
}
Esempio n. 12
0
/*
 *  readerGetNextValidFile(&fc_src);
 *
 *    Pull the next file name off of the valid-queue and create a
 *    flowsource object to read the flowcap records in it.  Fills
 *    'fproc' with the new flowcap-source object and probe.
 *
 *    Return 0 on success.  Return -1 if getting the file name fails.
 *    If unable to open the file or file not of correct form, return
 *    -2 unless the --error-dir is set, in which case move the file
 *    there and try the next file.
 */
static int
readerGetNextValidFile(
    flow_proc_t        *fproc)
{
    skstream_t *fcfile = NULL;
    skpc_probe_t *probe = NULL;
    skPollDirErr_t pderr;
    char *filename;
    char path[PATH_MAX];
    int rv;

    do {
        /* Get next file from the directory poller */
        pderr = skPollDirGetNextFile(polldir, path, &filename);
        if (pderr != PDERR_NONE) {
            if (pderr == PDERR_STOPPED) {
                return -1;
            }
            CRITMSG("Fatal polldir error ocurred: %s",
                    ((pderr == PDERR_SYSTEM)
                     ? strerror(errno)
                     : skPollDirStrError(pderr)));
            skAbort();
        }

        INFOMSG((INPUT_MODE_TYPE_NAME " processing %s"), filename);

        /* open the file to create a source of records */
        rv = flowcapSourceCreateFromFile(path, &fcfile, &probe);
        if (rv) {
            rv = errorDirectoryInsertFile(path);
            if (rv != 0) {
                /* either no --error-dir (rv == 1) or problem moving
                 * the file (rv == -1).  either way, return an error
                 * code to the caller. */
                return -2;
            }
        }
    } while (fcfile == NULL);

    fproc->flow_src = fcfile;
    fproc->probe = probe;

    return 0;
}
MediaPluginGStreamer010::MediaPluginGStreamer010(
	LLPluginInstance::sendMessageFunction send_message_function,
	LLPluginInstance* plugin_instance) :
	MediaPluginBase(send_message_function, plugin_instance),
	mBusWatchID ( 0 ),
	mCurrentRowbytes ( 4 ),
	mTextureFormatPrimary ( GL_RGBA ),
	mTextureFormatType ( GL_UNSIGNED_INT_8_8_8_8_REV ),
	mSeekWanted(false),
	mSeekDestination(0.0),
	mPump ( NULL ),
	mPlaybin ( NULL ),
	mVideoSink ( NULL ),
	mCommand ( COMMAND_NONE )
{
	std::ostringstream str;
	INFOMSG("MediaPluginGStreamer010 constructor - my PID=%u", U32(LL_GETPID()));
}
Esempio n. 14
0
void CTextureTool::OnReplace () 
{
UpdateData (TRUE);
if (!(m_bUse1st || m_bUse2nd))
	return;
if (!GetMine ())
	return;

	INT16			segnum,
					sidenum;
	CDSegment	*seg = m_mine->Segments ();
	CDSide		*side;
	bool			bChange = false,
					bAll = !m_mine->GotMarkedSides ();

if (bAll && (QueryMsg ("Replace textures in entire mine?") != IDYES))
	return;
bool bUndo = theApp.SetModified (TRUE);
theApp.LockUndo ();
if (bAll)
	INFOMSG (" Replacing textures in entire mine.");
for (segnum = 0; segnum < m_mine->SegCount (); segnum++, seg++)
	for (sidenum = 0, side = seg->sides; sidenum < 6; sidenum++, side++)
		if (bAll || m_mine->SideIsMarked (segnum, sidenum)) {
			if (m_bUse1st && (side->nBaseTex != last_texture1))
				continue;
			if (m_bUse2nd && ((side->nOvlTex & 0x3FFF) != last_texture2))
				continue;
			if ((seg->children [sidenum] >= 0) && (side->nWall == NO_WALL))
				 continue;
			if (m_mine->SetTexture (segnum, sidenum, m_bUse1st ? save_texture1 : -1, m_bUse2nd ? save_texture2 : -1))
				bChange = true;
//			int i;
//			for (i = 0; i < 4; i++)
//				side->uvls [i].l = save_uvls [i].l;
			}
if (bChange)
	theApp.UnlockUndo ();
else
	theApp.ResetModified (bUndo);
Refresh ();
theApp.MineView ()->Refresh ();
}
MediaPluginGStreamer010::MediaPluginGStreamer010(
	LLPluginInstance::sendMessageFunction host_send_func,
	void *host_user_data ) :
	MediaPluginBase(host_send_func, host_user_data),
	mBusWatchID ( 0 ),
	mCurrentRowbytes ( 4 ),
	mTextureFormatPrimary ( GL_RGBA ),
	mTextureFormatType ( GL_UNSIGNED_INT_8_8_8_8_REV ),
	mSeekWanted(false),
	mSeekDestination(0.0),
	mPump ( NULL ),
	mPlaybin ( NULL ),
	mVisualizer ( NULL ),
	mVideoSink ( NULL ),
	mCommand ( COMMAND_NONE )
{
	std::ostringstream str;
	INFOMSG("MediaPluginGStreamer010 constructor - my PID=%u", U32(getpid()));
}
Esempio n. 16
0
void CTextureTool::OnPasteMarked () 
{
UpdateData (TRUE);
if (!(m_bUse1st || m_bUse2nd))
	return;
if (!GetMine ())
	return;

	INT16			segnum,
					sidenum;
	CDSegment	*seg = m_mine->Segments ();
	CDSide		*side;
	bool			bChange = false,
					bAll = !m_mine->GotMarkedSides ();

if (bAll && (QueryMsg ("Paste texture to entire mine?") != IDYES))
	return;
bool bUndo = theApp.SetModified (TRUE);
theApp.LockUndo ();
if (bAll)
	INFOMSG (" Pasting texture in entire mine.");
for (segnum = 0; segnum < m_mine->SegCount (); segnum++, seg++) {
	for (sidenum = 0, side = seg->sides; sidenum < 6; sidenum++, side++) {
		if (bAll || m_mine->SideIsMarked (segnum, sidenum)) {
			if (seg->children [sidenum] == -1) {
				bChange = true;
				m_mine->SetTexture (segnum, sidenum, m_bUse1st ? save_texture1 : -1, m_bUse2nd ? save_texture2 : -1);
				int i;
				for (i = 0; i < 4; i++)
					side->uvls [i].l = save_uvls [i].l;
				}
			}
		}
	}
if (bChange)
	theApp.UnlockUndo ();
else
	theApp.ResetModified (bUndo);
Refresh ();
theApp.MineView ()->Refresh ();
}
Esempio n. 17
0
bool clsTracking2D::resolutionChanged()
{
        if(
                cameraResolutions["roiX"] != paramsInt["roiX"] ||
                cameraResolutions["roiY"] != paramsInt["roiY"] ||
                cameraResolutions["roiW"] != paramsInt["roiW"] ||
                cameraResolutions["roiH"] != paramsInt["roiH"] ||
                cameraResolutions["width"]  != rawImage.cols  ||
                cameraResolutions["height"] != rawImage.rows)
        {
                INFOMSG(("Resolution/ROI changed from: cam:%dx%d ROI:%dx%d[%dx%d] to cam:%dx%d ROI:%dx%d[%dx%d]",
                        cameraResolutions["width"] ,cameraResolutions["height"],
                        cameraResolutions["roiX"],cameraResolutions["roiY"],cameraResolutions["roiW"],cameraResolutions["roiH"], 
                        rawImage.cols,rawImage.rows,
                        paramsInt["roiX"],paramsInt["roiY"],paramsInt["roiW"],paramsInt["roiH"]
                        ));

                return true;
        }
        return false;
}
Esempio n. 18
0
void CameraView::setVideoResolution(int width,int height)
{
        if(isVideo)
        {
                INFOMSG(("setting new resolution %dx%d",width,height));
                // captureThread->pVideoCapture.setImageSize(width,height);
                captureThread->setVideoResolution(width,height);
                clearImageBuffer();
                // delete processingThread;
                
                // sharedImageBuffer->clear(tabId);
                // if(processingThread->isRunning())
                // stopProcessingThread();
		
		// while(!processingThread->isRunning())
		// {
		// usleep(500);
		// }
                // processingThread = new ProcessingThread(sharedImageBuffer, tabId,id,pSharedParticles);
                // processingThread->resetTracking();
        }
}
Esempio n. 19
0
void clsTracking2D::calcBgSegmentation(Mat img, IplImage *foreground)
{
        // cap >> img;
        
        //
        
        // return;
        if( img.empty() )
        {
                INFOMSG(("Img is empty()"));
                return;
        }
        
        if( fgimg.empty() )
                fgimg.create(img.size(), img.type());
        
        //update the model
        bg_model(img, fgmask, updateBgModel ? -1 : 0);
        
        fgimg = Scalar::all(0);
        img.copyTo(fgimg, fgmask);
        
        Mat bgimg;
        bg_model.getBackgroundImage(bgimg);
        
        // imshow("image", img);
        // imshow("foreground mask", fgmask);
        // imshow("foreground image", fgimg);
        // imshow("bg image", bgimg);
        
        // if(foregroung != null)
        // {
        //         cvReleaseImage(&foreground);
        // }
        // foreground=cvCloneImage(&(IplImage)fgmask);
        
        
}
Esempio n. 20
0
void clsTracking2D::initializeProcessing()
{
        if(allocatedInitFrames)
        {
        //         cvReleaseImage(&rawImageI);
                cvReleaseImage(&paintedFrame);
                cvReleaseImage(&foregroundImage);
                cvReleaseImage(&debugFrame);
                
                INFOMSG(("released memory.. general"));
        }
        
        cameraResolutions["width"] = rawImage.cols;
        cameraResolutions["height"] = rawImage.rows;
        cameraResolutions["roiX"] = paramsInt["roiX"];
        cameraResolutions["roiY"] = paramsInt["roiY"];
        cameraResolutions["roiW"] = paramsInt["roiW"];
        cameraResolutions["roiH"] = paramsInt["roiH"];
        
        // INFOMSG(("loading ROI(%dx%d[%dx%d]) rawImage(%d,%d)",cameraResolutions["roiX"], cameraResolutions["roiY"], cameraResolutions["roiW"],  cameraResolutions["roiH"],rawImage.cols,rawImage.rows));
        
        
        
        // INFOMSG(("loaded ROI(%dx%d[%dx%d]) rawImage(%d,%d)",cameraResolutions["roiX"], cameraResolutions["roiY"], cameraResolutions["roiW"],  cameraResolutions["roiH"],rawImage.cols,rawImage.rows));
        
        paintedFrame = cvCreateImage( cvSize(cameraResolutions["width"],cameraResolutions["height"]), IPL_DEPTH_8U, 3 );
        foregroundImage = cvCreateImage( cvSize(cameraResolutions["roiW"],cameraResolutions["roiH"]), IPL_DEPTH_8U, 1 );
        
        debugFrame = cvCreateImage(  cvSize(cameraResolutions["roiW"],cameraResolutions["roiH"]), IPL_DEPTH_8U, 1 );
        
        initializedProcess = true;
        BgCbstarted = false;
        bgsStarted = false;
        pParticles.processParticlesStarted = false;
        
        readyForParticles = false;
        allocatedInitFrames = true;
}
Esempio n. 21
0
//
// Open filename specified and return the size.
//
ULONG FSOpenFile(char* pFileName)
{
    USHORT i = 0;
    USHORT j = 0;
    ULONG DirLBA = 1;
    CHAR* Sector = (CHAR*)READ_BUFFER_START;
    CHAR FileName[30] = { 0 };
    BOOL bFound = FALSE;

    // Check caller's parameters.
    if (pFileName == NULL)
        return(0);

    memset( &g_FileInfo, 0, sizeof(FILEINFO) );

    // Convert the filename to the form stored on disk.
    for (i = 0 ; i < 15 && *(pFileName + i) ; i++)
        FileName[i*2] = TO_UPPER(*(pFileName + i));

    // Look for the filename in directory list.
    for( bFound = FALSE, DirLBA = g_FATParms.RootDirLBA ;
         !bFound && DirLBA ;
         DirLBA = NextSector( DirLBA ) )
    {
        // Read a sector from the root directory.
        if (!ReadSectors(pBPB->DriveID, DirLBA, 1, Sector))
        {
            ERRMSG(MSG_CANNOT_READ_ROOT_DIR, ("Couldn't read root directory sector (LBA=0x%x)\n", DirLBA));
            return(0);
        }

        // Try to find the specified file in the root directory...
        for (j = 0 ; (j < (1 << (pBPB->BytesPerSector - 5))) && !bFound; j++)
        {
            BYTE* pCurrent = Sector + (j << 5);

            //
            // We've found a stream entry, record this in case it's our file.
            //
            if( ((pCurrent[0] & 0x7F) == 64) && (pCurrent[0] & 0x80) )
            {
                EXFAT_STREAM_RECORD* pEntry;
                pEntry = (EXFAT_STREAM_RECORD*)(pCurrent);

                g_FileInfo.Flags = pEntry->Flags;
                g_FileInfo.FileSize = (ULONG)pEntry->FileSize;
                g_FileInfo.FirstCluster = pEntry->FirstCluster;
                g_FileInfo.CurCluster = g_FileInfo.FirstCluster;
                g_FileInfo.pCurReadBuffAddr = g_pReadBuffStart;

            }
            else if( ((pCurrent[0] & 0x7F) == 65) && (pCurrent[0] & 0x80) )
            {
                BYTE Current = 0;
                bFound = TRUE;


                for (i = 0 ; i < 30 ; i++)
                {
                    Current = TO_UPPER( (pCurrent)[2 + i] );
                    if( FileName[i] != Current )
                    {
                        bFound = FALSE;
                    }
                }
            }
        }
    }

    if (!bFound)
    {
        WARNMSG(MSG_FILE_NOT_FOUND, ("File '%s' not found\n", pFileName));
        return(0);
    }
    else
    {
        INFOMSG(MSG_FILE_FOUND, ("Found file '%s' (start=0x%x size=0x%x)\n", pFileName, g_FileInfo.FirstCluster, g_FileInfo.FileSize));
    }

    return(g_FileInfo.FileSize);
}
/* this function handles the link with other elements */
static gboolean
gst_slvideo_set_caps (GstBaseSink * bsink, GstCaps * caps)
{
	GstSLVideo *filter;
	GstStructure *structure;
//	GstCaps *intersection;
	
	GST_DEBUG ("set caps with %" GST_PTR_FORMAT, caps);
	
	filter = GST_SLVIDEO(bsink);

/*	
	intersection = gst_caps_intersect (filter->caps, caps);
	if (gst_caps_is_empty (intersection))
	{
		// no overlap between our caps and requested caps
		return FALSE;
	}
	gst_caps_unref(intersection);
*/	
	int width = 0;
	int height = 0;
	gboolean ret;
	const GValue *fps;
	const GValue *par;
	structure = gst_caps_get_structure (caps, 0);
	ret = gst_structure_get_int (structure, "width", &width);
	ret = ret && gst_structure_get_int (structure, "height", &height);
	fps = gst_structure_get_value (structure, "framerate");
	ret = ret && (fps != NULL);
	par = gst_structure_get_value (structure, "pixel-aspect-ratio");
	if (!ret)
		return FALSE;

	INFOMSG("** filter caps set with width=%d, height=%d", width, height);

	GST_OBJECT_LOCK(filter);

	filter->width = width;
	filter->height = height;
	filter->fps_n = gst_value_get_fraction_numerator(fps);
	filter->fps_d = gst_value_get_fraction_denominator(fps);
	if (par)
	{
		filter->par_n = gst_value_get_fraction_numerator(par);
		filter->par_d = gst_value_get_fraction_denominator(par);
	}
	else
	{
		filter->par_n = 1;
		filter->par_d = 1;
	}

	GST_VIDEO_SINK_WIDTH(filter) = width;
	GST_VIDEO_SINK_HEIGHT(filter) = height;

	// crufty lump - we *always* accept *only* RGBX now.
	/*
	
	filter->format = SLV_PF_UNKNOWN;
	if (0 == strcmp(gst_structure_get_name(structure),
			"video/x-raw-rgb"))
	{
		int red_mask;
		int green_mask;
		int blue_mask;
		gst_structure_get_int(structure, "red_mask", &red_mask);
		gst_structure_get_int(structure, "green_mask", &green_mask);
		gst_structure_get_int(structure, "blue_mask", &blue_mask);
		if ((unsigned int)red_mask   == 0xFF000000 &&
		    (unsigned int)green_mask == 0x00FF0000 &&
		    (unsigned int)blue_mask  == 0x0000FF00)
		{
			filter->format = SLV_PF_RGBX;
			//fprintf(stderr, "\n\nPIXEL FORMAT RGB\n\n");
		} else if ((unsigned int)red_mask   == 0x0000FF00 &&
			   (unsigned int)green_mask == 0x00FF0000 &&
			   (unsigned int)blue_mask  == 0xFF000000)
		{
			filter->format = SLV_PF_BGRX;
			//fprintf(stderr, "\n\nPIXEL FORMAT BGR\n\n");
		}
		
	}*/

	filter->format = SLV_PF_RGBX;

	GST_OBJECT_UNLOCK(filter);
	
	return TRUE;
}
Esempio n. 23
0
//static
gboolean
LLMediaImplGStreamer::bus_callback (GstBus     *bus,
				    GstMessage *message,
				    gpointer    data)
{
	if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_STATE_CHANGED &&
	    GST_MESSAGE_TYPE(message) != GST_MESSAGE_BUFFERING)
	{
		DEBUGMSG("Got GST message type: %s",
			LLGST_MESSAGE_TYPE_NAME (message));
	}
	else
	{
		DEBUGMSG("Got GST message type: %s",
			 LLGST_MESSAGE_TYPE_NAME (message));
	}

	LLMediaImplGStreamer *impl = (LLMediaImplGStreamer*)data;

	switch (GST_MESSAGE_TYPE (message)) {
	case GST_MESSAGE_BUFFERING: {
		// NEEDS GST 0.10.11+
		if (llgst_message_parse_buffering)
		{
			gint percent = 0;
			llgst_message_parse_buffering(message, &percent);
			DEBUGMSG("GST buffering: %d%%", percent);
			LLMediaEvent event( impl, percent );
			impl->getEventEmitter().update( &LLMediaObserver::onUpdateProgress, event );

		}
		break;
	}
	case GST_MESSAGE_STATE_CHANGED: {
		GstState old_state;
		GstState new_state;
		GstState pending_state;
		llgst_message_parse_state_changed(message,
						&old_state,
						&new_state,
						&pending_state);
#ifdef LL_GST_REPORT_STATE_CHANGES
		// not generally very useful, and rather spammy.
		DEBUGMSG("state change (old,<new>,pending): %s,<%s>,%s",
			 get_gst_state_name(old_state),
			 get_gst_state_name(new_state),
			 get_gst_state_name(pending_state));
#endif // LL_GST_REPORT_STATE_CHANGES

		switch (new_state) {
		case GST_STATE_VOID_PENDING:
			break;
		case GST_STATE_NULL:
			break;
		case GST_STATE_READY:
			break;
		case GST_STATE_PAUSED:
			break;
		case GST_STATE_PLAYING:
			LLMediaEvent event( impl, 100 );
			impl->getEventEmitter().update( &LLMediaObserver::onUpdateProgress, event );
			// emit an event to say that a media source was loaded
			LLMediaEvent event2( impl );
			impl->getEventEmitter().update( &LLMediaObserver::onMediaLoaded, event2 );
			break;
		}
		break;
	}
	case GST_MESSAGE_ERROR: {
		GError *err = NULL;
		gchar *debug = NULL;

		llgst_message_parse_error (message, &err, &debug);
		WARNMSG("GST error: %s", err->message);
		g_error_free (err);
		g_free (debug);

		impl->addCommand(LLMediaBase::COMMAND_STOP);

		break;
	}
	case GST_MESSAGE_INFO: {
		if (llgst_message_parse_info)
		{
			GError *err = NULL;
			gchar *debug = NULL;
			
			llgst_message_parse_info (message, &err, &debug);
			INFOMSG("GST info: %s", err->message);
			g_error_free (err);
			g_free (debug);
		}
		break;
	}
	case GST_MESSAGE_WARNING: {
		GError *err = NULL;
		gchar *debug = NULL;

		llgst_message_parse_warning (message, &err, &debug);
		WARNMSG("GST warning: %s", err->message);
		g_error_free (err);
		g_free (debug);

		break;
	}
	case GST_MESSAGE_EOS:
		/* end-of-stream */
		DEBUGMSG("GST end-of-stream.");
		if (impl->isLooping())
		{
			DEBUGMSG("looping media...");
			impl->stop();
			impl->play();
		}
		else
		{
			// inject a COMMAND_STOP
			impl->addCommand(LLMediaBase::COMMAND_STOP);
		}
		break;
	default:
		/* unhandled message */
		break;
	}

	/* we want to be notified again the next time there is a message
	 * on the bus, so return true (false means we want to stop watching
	 * for messages on the bus and our callback should not be called again)
	 */
	return TRUE;
}
static GstFlowReturn
gst_slvideo_buffer_alloc (GstBaseSink * bsink, guint64 offset, guint size,
			  GstCaps * caps, GstBuffer ** buf)
{
	gint width, height;
	GstStructure *structure = NULL;
	GstSLVideo *slvideo;
	slvideo = GST_SLVIDEO(bsink);

	// caps == requested caps
	// we can ignore these and reverse-negotiate our preferred dimensions with
	// the peer if we like - we need to do this to obey dynamic resize requests
	// flowing in from the app.
	structure = gst_caps_get_structure (caps, 0);
	if (!gst_structure_get_int(structure, "width", &width) ||
	    !gst_structure_get_int(structure, "height", &height))
	{
		GST_WARNING_OBJECT (slvideo, "no width/height in caps %" GST_PTR_FORMAT, caps);
		return GST_FLOW_NOT_NEGOTIATED;
	}

	GstBuffer *newbuf = gst_buffer_new();
	bool made_bufferdata_ptr = false;
#define MAXDEPTHHACK 4
	
	GST_OBJECT_LOCK(slvideo);
	if (slvideo->resize_forced_always) // app is giving us a fixed size to work with
	{
		gint slwantwidth, slwantheight;
		slwantwidth = slvideo->resize_try_width;
		slwantheight = slvideo->resize_try_height;
	
		if (slwantwidth != width ||
		    slwantheight != height)
		{
			// don't like requested caps, we will issue our own suggestion - copy
			// the requested caps but substitute our own width and height and see
			// if our peer is happy with that.
		
			GstCaps *desired_caps;
			GstStructure *desired_struct;
			desired_caps = gst_caps_copy (caps);
			desired_struct = gst_caps_get_structure (desired_caps, 0);
			
			GValue value = {0};
			g_value_init(&value, G_TYPE_INT);
			g_value_set_int(&value, slwantwidth);
			gst_structure_set_value (desired_struct, "width", &value);
			g_value_unset(&value);
			g_value_init(&value, G_TYPE_INT);
			g_value_set_int(&value, slwantheight);
			gst_structure_set_value (desired_struct, "height", &value);
			
			if (gst_pad_peer_accept_caps (GST_VIDEO_SINK_PAD (slvideo),
							desired_caps))
			{
				// todo: re-use buffers from a pool?
				// todo: set MALLOCDATA to null, set DATA to point straight to shm?
				
				// peer likes our cap suggestion
				DEBUGMSG("peer loves us :)");
				GST_BUFFER_SIZE(newbuf) = slwantwidth * slwantheight * MAXDEPTHHACK;
				GST_BUFFER_MALLOCDATA(newbuf) = (guint8*)g_malloc(GST_BUFFER_SIZE(newbuf));
				GST_BUFFER_DATA(newbuf) = GST_BUFFER_MALLOCDATA(newbuf);
				gst_buffer_set_caps (GST_BUFFER_CAST(newbuf), desired_caps);

				made_bufferdata_ptr = true;
			} else {
				// peer hates our cap suggestion
				INFOMSG("peer hates us :(");
				gst_caps_unref(desired_caps);
			}
		}
	}

	GST_OBJECT_UNLOCK(slvideo);

	if (!made_bufferdata_ptr) // need to fallback to malloc at original size
	{
		GST_BUFFER_SIZE(newbuf) = width * height * MAXDEPTHHACK;
		GST_BUFFER_MALLOCDATA(newbuf) = (guint8*)g_malloc(GST_BUFFER_SIZE(newbuf));
		GST_BUFFER_DATA(newbuf) = GST_BUFFER_MALLOCDATA(newbuf);
		gst_buffer_set_caps (GST_BUFFER_CAST(newbuf), caps);
	}

	*buf = GST_BUFFER_CAST(newbuf);

	return GST_FLOW_OK;
}
Esempio n. 25
0
/*
 *  status = readerGetRecord(&out_rwrec, &out_probe, flow_processor);
 *
 *    Invoked by input_mode_type->get_record_fn();
 */
static fp_get_record_result_t
readerGetRecord(
    rwRec                  *out_rwrec,
    const skpc_probe_t    **out_probe,
    flow_proc_t            *fproc)
{
    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    skstream_t *fcfile;
    const char *filename;
    fp_get_record_result_t retVal = FP_GET_ERROR;
    int rv;

    pthread_mutex_lock(&mutex);

    /* If we don't have a source, get a file from the directory poller
     * and start processing it. */
    if (fproc->flow_src == NULL) {
        switch (readerGetNextValidFile(fproc)) {
          case 0:
            /* Success */
            break;
          case -1:
            /* Error getting file name (maybe in shutdown?) */
            goto END;
          case -2:  /* Error opening file */
          default:  /* Unexpected value */
            retVal = FP_FATAL_ERROR;
            goto END;
        }
    }
    fcfile = (skstream_t*)fproc->flow_src;

    /* Assume we can get a record from the probe. */
    retVal = FP_RECORD;
    *out_probe = fproc->probe;

    /* Try to get a record */
    rv = skStreamReadRecord(fcfile, out_rwrec);
    if (rv) {
        /* get failed: either at EOF or got an error. */
        if (rv != SKSTREAM_ERR_EOF) {
            skStreamPrintLastErr(fcfile, rv, &WARNINGMSG);
        }

        retVal = FP_FILE_BREAK;
        *out_probe = NULL;

        /* Print results for the file we just processed. */
        filename = skStreamGetPathname(fcfile);
        INFOMSG("Processed file %s, %" PRIu64 " records.",
                filename, skStreamGetRecordCount(fcfile));

        skStreamClose(fcfile);

        /* Either archive the file or remove it */
        archiveDirectoryInsertOrRemove(filename, NULL);

        /* All done with the flow source */
        skStreamDestroy(&fcfile);
        fproc->flow_src = NULL;
        fproc->probe = NULL;
    }

  END:
    pthread_mutex_unlock(&mutex);

    return retVal;
}
Esempio n. 26
0
/*
 *  reject_if_true = pduSourceRejectPacket(sz, data, pdu_source);
 *
 *    Return TRUE if the bytes in 'data' do not represent a valid PDU
 *    packet.  'sz' is the length of the packet.  'pdu_source' is
 *    PDU source object.
 *
 *    Callback function passed to the skUDPSource_t collector.
 */
static int
pduSourceRejectPacket(
    ssize_t             data_len,
    void               *data,
    void               *v_pdusource)
{
    skPDUSource_t *source = (skPDUSource_t*)v_pdusource;
    v5PDU *pdu = (v5PDU*)data;
    pdusrc_badpdu_status_t pdu_status = PDU_OK;
    uint16_t count;

    if ((size_t)data_len < sizeof(v5Header)) {
        /* length cannot even hold a PDU header */
        pdu_status = PDU_TRUNCATED_HEADER;
    } else if (ntohs(pdu->hdr.version) != 5) {
        /* reject packet */
        pdu_status = PDU_BAD_VERSION;
    } else if (0 == (count = ntohs(pdu->hdr.count))) {
        pdu_status = PDU_ZERO_RECORDS;
    } else if (count > V5PDU_MAX_RECS) {
        pdu_status = PDU_OVERFLOW_RECORDS;
    } else if ((size_t)data_len < count * sizeof(v5Record)) {
        pdu_status = PDU_TRUNCATED_DATA;
    } else {
        /* current status is PDU_OK */
        if (PDU_OK == source->badpdu_status) {
            /* previous status was also PDU_OK; return */
            pthread_mutex_lock(&source->stats_mutex);
            ++source->statistics.procPkts;
            pthread_mutex_unlock(&source->stats_mutex);
            return 0;
        }
        pdu_status = PDU_OK;
    }

    /* when here, one or both of the current status and the previous
     * status are not PDU_OKAY */

    /* if status is same as before, increment counters and return */
    if (pdu_status == source->badpdu_status) {
        ++source->badpdu_consec;
        pthread_mutex_lock(&source->stats_mutex);
        ++source->statistics.procPkts;
        ++source->statistics.badPkts;
        pthread_mutex_unlock(&source->stats_mutex);
        return 1;
    }

    /* status has changed; we need to write a log message about the
     * previous status unless it was PDU_OK */
    if (PDU_OK != source->badpdu_status) {
        /* note, we have already logged about 1 bad packet */
        if (source->badpdu_consec) {
            NOTICEMSG(("'%s': Rejected %" PRIu32 " additional PDU record%s %s"),
                      source->name, source->badpdu_consec,
                      ((source->badpdu_consec == 1) ? "" : "s"),
                      pdusrc_badpdu_msgs[source->badpdu_status]);
        }

        if (PDU_OK == pdu_status) {
            source->badpdu_status = PDU_OK;
            pthread_mutex_lock(&source->stats_mutex);
            ++source->statistics.procPkts;
            pthread_mutex_unlock(&source->stats_mutex);
            return 0;
        }
    }

    INFOMSG("'%s': Rejected PDU record %s",
            source->name, pdusrc_badpdu_msgs[pdu_status]);

    /* Since we logged about this packet, no need to count it */
    source->badpdu_consec = 0;
    source->badpdu_status = pdu_status;
    pthread_mutex_lock(&source->stats_mutex);
    ++source->statistics.procPkts;
    ++source->statistics.badPkts;
    pthread_mutex_unlock(&source->stats_mutex);
    return 1;
}
void MediaPluginGStreamer010::receiveMessage(const char *message_string)
{
	//std::cerr << "MediaPluginGStreamer010::receiveMessage: received message: \"" << message_string << "\"" << std::endl;

	LLPluginMessage message_in;

	if(message_in.parse(message_string) >= 0)
	{
		std::string message_class = message_in.getClass();
		std::string message_name = message_in.getName();
		if(message_class == LLPLUGIN_MESSAGE_CLASS_BASE)
		{
			if(message_name == "init")
			{
				LLPluginMessage message("base", "init_response");
				LLSD versions = LLSD::emptyMap();
				versions[LLPLUGIN_MESSAGE_CLASS_BASE] = LLPLUGIN_MESSAGE_CLASS_BASE_VERSION;
				versions[LLPLUGIN_MESSAGE_CLASS_MEDIA] = LLPLUGIN_MESSAGE_CLASS_MEDIA_VERSION;
				versions[LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME] = LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME_VERSION;
				message.setValueLLSD("versions", versions);

				if ( load() )
				{
					DEBUGMSG("GStreamer010 media instance set up");
				}
				else
				{
					WARNMSG("GStreamer010 media instance failed to set up");
				}

				message.setValue("plugin_version", getVersion());
				sendMessage(message);
			}
			else if(message_name == "idle")
			{
				// no response is necessary here.
				double time = message_in.getValueReal("time");
				
				// Convert time to milliseconds for update()
				update((int)(time * 1000.0f));
			}
			else if(message_name == "cleanup")
			{
				unload();
				closedown();
			}
			else if(message_name == "shm_added")
			{
				SharedSegmentInfo info;
				info.mAddress = message_in.getValuePointer("address");
				info.mSize = (size_t)message_in.getValueS32("size");
				std::string name = message_in.getValue("name");

				std::ostringstream str;
				INFOMSG("MediaPluginGStreamer010::receiveMessage: shared memory added, name: %s, size: %d, address: %p", name.c_str(), int(info.mSize), info.mAddress);

				mSharedSegments.insert(SharedSegmentMap::value_type(name, info));
			}
			else if(message_name == "shm_remove")
			{
				std::string name = message_in.getValue("name");

				DEBUGMSG("MediaPluginGStreamer010::receiveMessage: shared memory remove, name = %s", name.c_str());
				
				SharedSegmentMap::iterator iter = mSharedSegments.find(name);
				if(iter != mSharedSegments.end())
				{
					if(mPixels == iter->second.mAddress)
					{
						// This is the currently active pixel buffer.  Make sure we stop drawing to it.
						mPixels = NULL;
						mTextureSegmentName.clear();
						
						// Make sure the movie decoder is no longer pointed at the shared segment.
						sizeChanged();						
					}
					mSharedSegments.erase(iter);
				}
				else
				{
					WARNMSG("MediaPluginGStreamer010::receiveMessage: unknown shared memory region!");
				}

				// Send the response so it can be cleaned up.
				LLPluginMessage message("base", "shm_remove_response");
				message.setValue("name", name);
				sendMessage(message);
			}
			else
			{
				std::ostringstream str;
				INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown base message: %s", message_name.c_str());
			}
		}
		else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA)
		{
			if(message_name == "init")
			{
				// Plugin gets to decide the texture parameters to use.
				LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "texture_params");
				// lame to have to decide this now, it depends on the movie.  Oh well.
				mDepth = 4;

				mCurrentWidth = 1;
				mCurrentHeight = 1;
				mPreviousWidth = 1;
				mPreviousHeight = 1;
				mNaturalWidth = 1;
				mNaturalHeight = 1;
				mWidth = 1;
				mHeight = 1;
				mTextureWidth = 1;
				mTextureHeight = 1;

				message.setValueU32("format", GL_RGBA);
				message.setValueU32("type", GL_UNSIGNED_INT_8_8_8_8_REV);

				message.setValueS32("depth", mDepth);
				message.setValueS32("default_width", mWidth);
				message.setValueS32("default_height", mHeight);
				message.setValueU32("internalformat", GL_RGBA8);
				message.setValueBoolean("coords_opengl", true);	// true == use OpenGL-style coordinates, false == (0,0) is upper left.
				message.setValueBoolean("allow_downsample", true); // we respond with grace and performance if asked to downscale
				sendMessage(message);
			}
			else if(message_name == "size_change")
			{
				std::string name = message_in.getValue("name");
				S32 width = message_in.getValueS32("width");
				S32 height = message_in.getValueS32("height");
				S32 texture_width = message_in.getValueS32("texture_width");
				S32 texture_height = message_in.getValueS32("texture_height");

				std::ostringstream str;
				INFOMSG("---->Got size change instruction from application with shm name: %s - size is %d x %d", name.c_str(), width, height);

				LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "size_change_response");
				message.setValue("name", name);
				message.setValueS32("width", width);
				message.setValueS32("height", height);
				message.setValueS32("texture_width", texture_width);
				message.setValueS32("texture_height", texture_height);
				sendMessage(message);

				if(!name.empty())
				{
					// Find the shared memory region with this name
					SharedSegmentMap::iterator iter = mSharedSegments.find(name);
					if(iter != mSharedSegments.end())
					{
						INFOMSG("*** Got size change with matching shm, new size is %d x %d", width, height);
						INFOMSG("*** Got size change with matching shm, texture size size is %d x %d", texture_width, texture_height);

						mPixels = (unsigned char*)iter->second.mAddress;
						mTextureSegmentName = name;
						mWidth = width;
						mHeight = height;

						if (texture_width > 1 ||
						    texture_height > 1) // not a dummy size from the app, a real explicit forced size
						{
							INFOMSG("**** = REAL RESIZE REQUEST FROM APP");
							
							GST_OBJECT_LOCK(mVideoSink);
							mVideoSink->resize_forced_always = true;
							mVideoSink->resize_try_width = texture_width;
							mVideoSink->resize_try_height = texture_height;
							GST_OBJECT_UNLOCK(mVideoSink);
 						}

						mTextureWidth = texture_width;
						mTextureHeight = texture_height;
					}
				}
			}
			else if(message_name == "load_uri")
			{
				std::string uri = message_in.getValue("uri");
				navigateTo( uri );
				sendStatus();		
			}
			else if(message_name == "mouse_event")
			{
				std::string event = message_in.getValue("event");
				S32 x = message_in.getValueS32("x");
				S32 y = message_in.getValueS32("y");
				
				if(event == "down")
				{
					mouseDown(x, y);
				}
				else if(event == "up")
				{
					mouseUp(x, y);
				}
				else if(event == "move")
				{
					mouseMove(x, y);
				};
			};
		}
		else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME)
		{
			if(message_name == "stop")
			{
				stop();
			}
			else if(message_name == "start")
			{
				double rate = 0.0;
				if(message_in.hasValue("rate"))
				{
					rate = message_in.getValueReal("rate");
				}
				// NOTE: we don't actually support rate.
				play(rate);
			}
			else if(message_name == "pause")
			{
				pause();
			}
			else if(message_name == "seek")
			{
				double time = message_in.getValueReal("time");
				// defer the actual seek in case we haven't
				// really truly started yet in which case there
				// is nothing to seek upon
				mSeekWanted = true;
				mSeekDestination = time;
			}
			else if(message_name == "set_loop")
			{
				bool loop = message_in.getValueBoolean("loop");
				mIsLooping = loop;
			}
			else if(message_name == "set_volume")
			{
				double volume = message_in.getValueReal("volume");
				setVolume(volume);
			}
		}
		else
		{
			INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown message class: %s", message_class.c_str());
		}
	}
}
gboolean
MediaPluginGStreamer010::processGSTEvents(GstBus     *bus,
					  GstMessage *message)
{
	if (!message) 
		return TRUE; // shield against GStreamer bug

	if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_STATE_CHANGED &&
	    GST_MESSAGE_TYPE(message) != GST_MESSAGE_BUFFERING)
	{
		DEBUGMSG("Got GST message type: %s",
			GST_MESSAGE_TYPE_NAME (message));
	}
	else
	{
		// TODO: grok 'duration' message type
		DEBUGMSG("Got GST message type: %s",
			 GST_MESSAGE_TYPE_NAME (message));
	}

	switch (GST_MESSAGE_TYPE (message))
	{
		case GST_MESSAGE_BUFFERING:
		{
			// NEEDS GST 0.10.11+ and America discovered by C.Columbus
			gint percent = 0;
			gst_message_parse_buffering(message, &percent);
			DEBUGMSG("GST buffering: %d%%", percent);

			break;
		}
		case GST_MESSAGE_STATE_CHANGED: {
			GstState old_state;
			GstState new_state;
			GstState pending_state;
			gst_message_parse_state_changed(message,
							&old_state,
							&new_state,
							&pending_state);
			#ifdef LL_GST_REPORT_STATE_CHANGES
			// not generally very useful, and rather spammy.
			DEBUGMSG("state change (old,<new>,pending): %s,<%s>,%s",
				get_gst_state_name(old_state),
				get_gst_state_name(new_state),
				get_gst_state_name(pending_state));
			#endif // LL_GST_REPORT_STATE_CHANGES

			switch (new_state) 
			{
				case GST_STATE_VOID_PENDING:
					break;
				case GST_STATE_NULL:
					break;
				case GST_STATE_READY:
					setStatus(STATUS_LOADED);
					break;
				case GST_STATE_PAUSED:
					setStatus(STATUS_PAUSED);
					break;
				case GST_STATE_PLAYING:
					setStatus(STATUS_PLAYING);
					break;
			}
			break;
		}
		case GST_MESSAGE_ERROR:
		{
			GError *err = NULL;
			gchar *debug = NULL;
	
			gst_message_parse_error (message, &err, &debug);
			WARNMSG("GST error: %s", err?err->message:"(unknown)");
			if (err)
				g_error_free (err);
			g_free (debug);
	
			mCommand = COMMAND_STOP;
	
			setStatus(STATUS_ERROR);
	
			break;
		}
		case GST_MESSAGE_INFO:
		{
			GError *err = NULL;
			gchar *debug = NULL;
			
			gst_message_parse_info (message, &err, &debug);
			INFOMSG("GST info: %s", err?err->message:"(unknown)");
			if (err)
				g_error_free (err);
			g_free (debug);

			break;
		}
		case GST_MESSAGE_WARNING:
		{
			GError *err = NULL;
			gchar *debug = NULL;
	
			gst_message_parse_warning (message, &err, &debug);
			WARNMSG("GST warning: %s", err?err->message:"(unknown)");
			if (err)
				g_error_free (err);
			g_free (debug);
	
			break;
		}
		case GST_MESSAGE_TAG: 
		{
			GstTagList *new_tags;

			gst_message_parse_tag( message, &new_tags );

			gchar *title = NULL;

			if ( gst_tag_list_get_string(new_tags, GST_TAG_TITLE, &title) )
			{
				//WARMING("Title: %s", title);
				std::string newtitle(title);
				gst_tag_list_free(new_tags);

				if ( newtitle != mLastTitle && !newtitle.empty() )
				{
					LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "name_text");
					message.setValue("name", newtitle );
					sendMessage( message );
					mLastTitle = newtitle;
				}
				g_free(title);
			}

			break;
		}
		case GST_MESSAGE_EOS:
		{
			/* end-of-stream */
			DEBUGMSG("GST end-of-stream.");
			if (mIsLooping)
			{
				DEBUGMSG("looping media...");
				double eos_pos_sec = 0.0F;
				bool got_eos_position = getTimePos(eos_pos_sec);
	
				if (got_eos_position && eos_pos_sec < MIN_LOOP_SEC)
				{
					// if we know that the movie is really short, don't
					// loop it else it can easily become a time-hog
					// because of GStreamer spin-up overhead
					DEBUGMSG("really short movie (%0.3fsec) - not gonna loop this, pausing instead.", eos_pos_sec);
					// inject a COMMAND_PAUSE
					mCommand = COMMAND_PAUSE;
				}
				else
				{
					#undef LLGST_LOOP_BY_SEEKING
					// loop with a stop-start instead of a seek, because it actually seems rather
					// faster than seeking on remote streams.
					#ifdef LLGST_LOOP_BY_SEEKING
					// first, try looping by an explicit rewind
					bool seeksuccess = seek(0.0);
					if (seeksuccess)
					{
						play(1.0);
					}
					else
					#endif // LLGST_LOOP_BY_SEEKING
					{  // use clumsy stop-start to loop
						DEBUGMSG("didn't loop by rewinding - stopping and starting instead...");
						stop();
						play(1.0);
					}
				}
			}
			else // not a looping media
			{
				// inject a COMMAND_STOP
				mCommand = COMMAND_STOP;
			}
		} break;

		default:
			/* unhandled message */
			break;
	}

	/* we want to be notified again the next time there is a message
	 * on the bus, so return true (false means we want to stop watching
	 * for messages on the bus and our callback should not be called again)
	 */
	return TRUE;
}
Esempio n. 29
0
/*
 *    This function is called by the handleConnection() function in
 *    rwtransfer.c once the connection has been established.  This
 *    function returns -1 on error, 0 if no files were transferred, or
 *    1 if one or more files were successfully received.
 */
int
transferFiles(
    sk_msg_queue_t     *q,
    skm_channel_t       channel,
    transfer_t         *sndr)
{
    static pthread_mutex_t open_file_mutex = PTHREAD_MUTEX_INITIALIZER;
    int fd = -1;
    uint64_t size = 0;
    uint64_t pa_size = 0;
    uint8_t *map = NULL;
    char *name = NULL;
    char *dotname = NULL;
    char dotpath[PATH_MAX];
    char destpath[sizeof(dotpath)-1];
    struct stat st;
    ino_t *inode;
    int proto_err;
    int rv;
    sk_dll_iter_t iter;
    const char *duplicate_dir;
    enum transfer_state {File_info, File_info_ack,
                         Send_file, Complete_ack, Error} state;
    int thread_exit;
    int transferred_file = 0;

    state = File_info;
    proto_err = 0;
    thread_exit = 0;
    destpath[0] = '\0';
    dotpath[0] = '\0';
    memset(&st, 0, sizeof(st));

    while (!shuttingdown && !proto_err && !thread_exit && !sndr->disconnect
           && (state != Error))
    {
        sk_msg_t *msg;

        /* Handle reads */
        switch (state) {
          case File_info:
          case Send_file:
            rv = skMsgQueueGetMessage(q, &msg);
            if (rv == -1) {
                ASSERT_ABORT(shuttingdown);
                continue;
            }
            if (handleDisconnect(msg, sndr->ident)) {
                state = Error;
            }
            break;
          case Error:
            ASSERT_ABORT(0);
            break;
          default:
            msg = NULL;
        }

        /* Handle all states */
        switch (state) {
          case File_info:
            /* Create the placeholder and dot files and mmap() the
             * space. */
            {
                file_info_t *finfo;
                uint32_t len;
                mode_t mode;
                off_t offrv;

                if ((proto_err = checkMsg(msg, q, CONN_NEW_FILE))) {
                    break;
                }
                DEBUG_PRINT1("Received CONN_NEW_FILE");
                finfo = (file_info_t *)skMsgMessage(msg);
                size = (uint64_t)ntohl(finfo->high_filesize) << 32 |
                       ntohl(finfo->low_filesize);
                pa_size = size;
                /* blocksize = ntohl(finfo->block_size); --- UNUSED */
                mode = ntohl(finfo->mode) & 0777;
                len = skMsgLength(msg) - offsetof(file_info_t, filename);
                dotname = (char *)calloc(1, len + 1);
                CHECK_ALLOC(dotname);
                name = dotname + 1;
                dotname[0] = '.';
                memcpy(name, finfo->filename, len);
                if (!memchr(name, '\0', len)) {
                    sendString(q, channel, EXTERNAL, SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Illegal filename (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    break;
                }

                INFOMSG("Receiving from %s: '%s' (%" PRIu64 " bytes)",
                        sndr->ident, name, size);

                /* Check filesystem for enough space for file */
                if (CHECK_DISK_SPACE(pa_size)) {
                    WARNINGMSG(("Not enough space on filesystem for %" PRIu64
                                " byte file '%s'"),
                               pa_size, name);
                    pa_size = 0;
                    state = FILESYSTEM_FULL_ERROR_STATE(sndr);
                    break;
                }

                /* Create the placeholder file */
                rv = snprintf(destpath, sizeof(destpath), "%s/%s",
                              destination_dir, name);
                if ((size_t)rv >= sizeof(destpath)) {
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Filename too long (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    destpath[0] = '\0';
                    break;
                }

                assert((size_t)rv < sizeof(destpath));

                pthread_mutex_lock(&open_file_mutex);
              reopen:
                fd = open(destpath, O_CREAT | O_EXCL | O_WRONLY, 0);
                if (fd == -1) {
                    if (errno != EEXIST) {
                        CRITMSG("Could not create '%s': %s",
                                destpath, strerror(errno));
                        thread_exit = 1;
                        pthread_mutex_unlock(&open_file_mutex);
                        break;
                    }

                    if (stat(destpath, &st) == -1) {
                        WARNINGMSG("Unable to stat '%s': %s",
                                   destpath, strerror(errno));
                    } else if (S_ISREG(st.st_mode)
                               && ((st.st_mode & 0777) == 0)
                               && ((st.st_size == 0)))
                    {
                        /* looks like a placeholder file.  are we
                         * receiving a file with the same name from a
                         * different rwsender? */
                        int found = 0;
                        skDLLAssignIter(&iter, open_file_list);
                        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                            if (st.st_ino == *inode) {
                                WARNINGMSG(("Multiple rwsenders attempting"
                                            " to send file '%s'"),
                                           name);
                                found = 1;
                                break;
                            }
                        }
                        if (!found) {
                            WARNINGMSG(("Filename already exists (from a"
                                        " previous run?). Removing '%s'"),
                                       destpath);
                            if (unlink(destpath) == 0) {
                                goto reopen;
                            }
                            WARNINGMSG("Failed to unlink '%s': %s",
                                       destpath, strerror(errno));
                            /* treat file as a duplicate */
                        }
                    }
                    /* else file is a duplicate */
                    st.st_ino = 0;
                    destpath[0] = dotpath[0] = '\0';
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_DUPLICATE(sndr),
                               LOG_WARNING,
                               "Filename already exists (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                /* else, successfully opened placeholder file */
                if (fstat(fd, &st) == -1) {
                    CRITMSG("Could not fstat newly created file '%s': %s",
                            destpath, strerror(errno));
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                if (skDLListPushTail(open_file_list, &st.st_ino)) {
                    CRITMSG("Unable to grow open file list");
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                pthread_mutex_unlock(&open_file_mutex);

                DEBUGMSG("Created '%s'", destpath);

                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            destpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Create the dotfile */
                rv = snprintf(dotpath, sizeof(dotpath), "%s/%s",
                              destination_dir, dotname);
              reopen2:
                fd = open(dotpath, O_RDWR | O_CREAT | O_EXCL, mode);
                if (fd == -1) {
                    int saveerrno = errno;
                    if (errno == EEXIST) {
                        WARNINGMSG("Filename already exists. Removing '%s'",
                                   dotpath);
                        if (unlink(dotpath) == 0) {
                            goto reopen2;
                        }
                        WARNINGMSG("Failed to unlink '%s': %s",
                                   dotpath, strerror(errno));
                    }
                    CRITMSG("Could not create '%s': %s",
                            dotpath, strerror(saveerrno));
                    thread_exit = 1;
                    dotpath[0] = '\0';
                    break;
                }
                DEBUGMSG("Created '%s'", dotpath);

                /* Allocate space on disk */
                offrv = lseek(fd, size - 1, SEEK_SET);
                if (offrv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = write(fd, "", 1);
                if (rv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Map space */
                map = (uint8_t *)mmap(0, size, PROT_READ | PROT_WRITE,
                                      MAP_SHARED, fd, 0);
                if ((void *)map == MAP_FAILED) {
                    CRITMSG("Could not map '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                GOT_DISK_SPACE(pa_size);
                pa_size = 0;
                state = File_info_ack;
            }
            break;

          case File_info_ack:
            DEBUG_PRINT1("Sending CONN_NEW_FILE_READY");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_NEW_FILE_READY, NULL, 0);
            state = Send_file;
            break;

          case Send_file:
            /* Get the content of the file and write into the dot file */
            {
                block_info_t *block;
                uint64_t offset;
                uint32_t len;

                if (skMsgType(msg) != CONN_FILE_BLOCK) {
                    if ((proto_err = checkMsg(msg, q, CONN_FILE_COMPLETE))) {
                        break;
                    }
                    DEBUG_PRINT1("Received CONN_FILE_COMPLETE");
                    state = Complete_ack;
                    break;
                }

                block = (block_info_t *)skMsgMessage(msg);
                len = skMsgLength(msg) - offsetof(block_info_t, block);
                offset = (uint64_t)ntohl(block->high_offset) << 32 |
                         ntohl(block->low_offset);
                DEBUG_CONTENT_PRINT("Receiving offset=%" PRIu64 " len=%" PRIu32,
                                    offset, len);
                if (offset + len > size) {
                    sendString(q, channel, EXTERNAL, CONN_DISCONNECT,
                               LOG_WARNING,
                               ("Illegal block (offset/size %" PRIu64
                                "/%" PRIu32 ")"), offset, len);
                    state = Error;
                    break;
                }
                memcpy(map + offset, block->block, len);
            }
            break;

          case Complete_ack:
            /* Un-mmap() the file, create any duplicate files, and
             * move the dotfile over the placeholder file */
            rv = munmap(map, size);
            map = NULL;
            if (rv == -1) {
                CRITMSG("Could not unmap file '%s': %s",
                        dotpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* Handle duplicate-destinations. Any errors here are
             * simply logged and processing continues. */
            skDLLAssignIter(&iter, duplicate_dirs);
            while (skDLLIterForward(&iter, (void **)&duplicate_dir) == 0) {
                char path[sizeof(destpath)];

                snprintf(path, sizeof(path), "%s/%s", duplicate_dir, name);
                if (unique_duplicates) {
                    rv = skCopyFile(dotpath, path);
                    if (rv != 0) {
                        WARNINGMSG("Could not copy '%s' to '%s': %s",
                                   dotpath, path, strerror(rv));
                    }
                } else {
                    DEBUGMSG("Linking '%s' as '%s'", dotpath, path);
                    rv = link(dotpath, path);
                    if (EXDEV == errno) {
                        DEBUGMSG("Link failed EXDEV; copying '%s' to '%s'",
                                 dotpath, path);
                        rv = skCopyFile(dotpath, path);
                        if (rv != 0) {
                            WARNINGMSG("Could not copy '%s' to '%s': %s",
                                       dotpath, path, strerror(rv));
                        }
                    } else if (rv != 0) {
                        WARNINGMSG("Could not link '%s' as '%s': %s",
                                   dotpath, path, strerror(errno));
                    }
                }
            }

            DEBUGMSG("Renaming '%s' to '%s'", dotpath, destpath);
            rv = rename(dotpath, destpath);
            if (rv != 0) {
                CRITMSG("Failed rename of '%s' to '%s': %s",
                        dotpath, destpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* remove the file from the open_file_list */
            pthread_mutex_lock(&open_file_mutex);
            skDLLAssignIter(&iter, open_file_list);
            while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                if (st.st_ino == *inode) {
                    skDLLIterDel(&iter);
                    break;
                }
            }
            st.st_ino = 0;
            pthread_mutex_unlock(&open_file_mutex);

            DEBUG_PRINT1("Sending CONN_FILE_COMPLETE");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_FILE_COMPLETE, NULL, 0);
            if (proto_err == 0) {
                /* Run the post command on the file */
                if (post_command) {
                    runPostCommand(post_command, destpath, sndr->ident);
                }
                destpath[0] = '\0';
                INFOMSG("Finished receiving from %s: '%s'", sndr->ident, name);
                free(dotname);
                dotname = NULL;
            }

            destpath[0] = dotpath[0] = '\0';
            transferred_file = 1;

            state = File_info;
            break;

          case Error:
            break;
        }

        if (msg != NULL) {
            skMsgDestroy(msg);
        }
    }

    if (fd != -1) {
        close(fd);
    }
    if (map != NULL) {
        munmap(map, size);
    }
    if (dotname != NULL) {
        free(dotname);
    }
    if (dotpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", dotpath);
        unlink(dotpath);
    }
    if (destpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", destpath);
        unlink(destpath);
    }
    if (st.st_ino != 0) {
        skDLLAssignIter(&iter, open_file_list);
        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
            if (st.st_ino == *inode) {
                skDLLIterDel(&iter);
                break;
            }
        }
    }
    if (pa_size) {
        GOT_DISK_SPACE(pa_size);
    }
    if (thread_exit) {
        return -1;
    }

    return transferred_file;
}
Esempio n. 30
0
void SequenceViewer::ExportAlignment(eExportType type)
{
    // get filename
    wxString extension, wildcard;
    if (type == asFASTA) { extension = ".fsa"; wildcard = "FASTA Files (*.fsa)|*.fsa"; }
    else if (type == asFASTAa2m) { extension = ".a2m"; wildcard = "A2M FASTA (*.a2m)|*.a2m"; }
    else if (type == asText) { extension = ".txt"; wildcard = "Text Files (*.txt)|*.txt"; }
    else if (type == asHTML) { extension = ".html"; wildcard = "HTML Files (*.html)|*.html"; }
    else if (type == asPSSM) { extension = ".pssm"; wildcard = "PSSM Files (*.pssm)|*.pssm"; }

    wxString outputFolder = wxString(GetUserDir().c_str(), GetUserDir().size() - 1); // remove trailing /
    wxString baseName, outputFile;
    wxFileName::SplitPath(GetWorkingFilename().c_str(), NULL, &baseName, NULL);
    wxFileDialog dialog(sequenceWindow, "Choose a file for alignment export:", outputFolder,
#ifdef __WXGTK__
        baseName + extension,
#else
        baseName,
#endif
        wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
    dialog.SetFilterIndex(0);
    if (dialog.ShowModal() == wxID_OK)
        outputFile = dialog.GetPath();

    if (outputFile.size() > 0) {

        // create output stream
        auto_ptr<CNcbiOfstream> ofs(new CNcbiOfstream(WX_TO_STD(outputFile).c_str(), IOS_BASE::out));
        if (!(*ofs)) {
            ERRORMSG("Unable to open output file " << outputFile.c_str());
            return;
        }

        // map display row order to rows in BlockMultipleAlignment
        vector < int > rowOrder;
        const SequenceDisplay *display = GetCurrentDisplay();
        for (unsigned int i=0; i<display->rows.size(); ++i) {
            DisplayRowFromAlignment *alnRow = dynamic_cast<DisplayRowFromAlignment*>(display->rows[i]);
            if (alnRow) rowOrder.push_back(alnRow->row);
        }

        // actually write the alignment
        if (type == asFASTA || type == asFASTAa2m) {
            INFOMSG("exporting" << (type == asFASTAa2m ? " A2M " : " ") << "FASTA to " << outputFile.c_str());
            DumpFASTA((type == asFASTAa2m), alignmentManager->GetCurrentMultipleAlignment(),
                rowOrder, sequenceWindow->GetCurrentJustification(), *ofs);
        } else if (type == asText || type == asHTML) {
            INFOMSG("exporting " << (type == asText ? "text" : "HTML") << " to " << outputFile.c_str());
            DumpText((type == asHTML), alignmentManager->GetCurrentMultipleAlignment(),
                rowOrder, sequenceWindow->GetCurrentJustification(), *ofs);
        } else if (type == asPSSM) {
            static string prevTitle;
            if (prevTitle.size() == 0)
                prevTitle = GetWorkingTitle();
            string title = WX_TO_STD(wxGetTextFromUser(
                "Enter a name for this PSSM (to be used by other applications like PSI-BLAST or RPS-BLAST):",
                "PSSM Title?", prevTitle.c_str(), *viewerWindow).Strip(wxString::both));
            if (title.size() > 0) {
                INFOMSG("exporting PSSM (" << title << ") to " << outputFile.c_str());
                alignmentManager->GetCurrentMultipleAlignment()->GetPSSM().OutputPSSM(*ofs, title);
                prevTitle = title;
            }
        }
    }
}