Exemple #1
0
void VideoWidget::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
	if (newGeometry == oldGeometry)
	{
		QDeclarativeItem::geometryChanged(newGeometry,oldGeometry);
		return;
	}
	if (mediaLoaded)
	{
		//qDebug() << "Geometry Change:" << newGeometry;
		pixmapMutex.lock();
		delete pix;
		pix = new QImage(newGeometry.width(),newGeometry.height(),QImage::Format_RGB32);
		//qDebug() << libvlc_media_get_state(pm);
		libvlc_video_set_format(mp, "RV32", newGeometry.width(), newGeometry.height(), newGeometry.width()*4);
		pixmapMutex.unlock();
	}
	else
	{
		//qDebug() << "Geometry Change:" << newGeometry;
		pixmapMutex.lock();
		delete pix;
		pix = new QImage(newGeometry.width(),newGeometry.height(),QImage::Format_RGB32);
		//qDebug() << libvlc_media_get_state(pm);
		pixmapMutex.unlock();

	}
	QDeclarativeItem::geometryChanged(newGeometry,oldGeometry);

}
Exemple #2
0
void VPlayer::play()
{
	if(mp){
		if(state==Stop){
			libvlc_media_track_info_t *info;
			libvlc_media_parse(m);
			int i=libvlc_media_get_tracks_info(m,&info);
			for(--i;i>=0;--i){
				if(info[i].i_type==libvlc_track_video){
					srcSize.setWidth (info[i].u.video.i_width);
					srcSize.setHeight(info[i].u.video.i_height);
				}
			}
			free(info);
			dstSize=srcSize;
			avpicture_alloc(&srcFrame,PIX_FMT_RGB32,srcSize.width(),srcSize.height());
			avpicture_alloc(&dstFrame,PIX_FMT_RGB32,dstSize.width(),dstSize.height());
			valid=true;
			libvlc_video_set_format(mp,"RV32",srcSize.width(),srcSize.height(),srcSize.width()*4);
			libvlc_video_set_callbacks(mp,lock,NULL,display,this);
			Utils::delayExec(50,[this](){libvlc_media_player_play(mp);});
		}
		else{
			libvlc_media_player_pause(mp);
			if(state==Play){
				state=Pause;
				emit paused();
			}
			else{
				state=Play;
			}
		}
	}
}
int LibvlcCamera::PrimeCapture() {
  Info("Priming capture from %s", mPath.c_str());

  StringVector opVect = split(Options(), ",");

  // Set transport method as specified by method field, rtpUni is default
  if ( Method() == "rtpMulti" )
    opVect.push_back("--rtsp-mcast");
  else if ( Method() == "rtpRtsp" )
    opVect.push_back("--rtsp-tcp");
  else if ( Method() == "rtpRtspHttp" )
    opVect.push_back("--rtsp-http");

  opVect.push_back("--no-audio");

  if ( opVect.size() > 0 ) {
    mOptArgV = new char*[opVect.size()];
    Debug(2, "Number of Options: %d",opVect.size());
    for (size_t i=0; i< opVect.size(); i++) {
      opVect[i] = trimSpaces(opVect[i]);
      mOptArgV[i] = (char *)opVect[i].c_str();
      Debug(2, "set option %d to '%s'", i,  opVect[i].c_str());
    }
  }

  mLibvlcInstance = libvlc_new(opVect.size(), (const char* const*)mOptArgV);
  if ( mLibvlcInstance == NULL ) {
    Error("Unable to create libvlc instance due to: %s", libvlc_errmsg());
    return -1;
  }

  mLibvlcMedia = libvlc_media_new_location(mLibvlcInstance, mPath.c_str());
  if ( mLibvlcMedia == NULL ) {
    Error("Unable to open input %s due to: %s", mPath.c_str(), libvlc_errmsg());
    return -1;
  }

  mLibvlcMediaPlayer = libvlc_media_player_new_from_media(mLibvlcMedia);
  if ( mLibvlcMediaPlayer == NULL ) {
    Error("Unable to create player for %s due to: %s", mPath.c_str(), libvlc_errmsg());
    return -1;
  }

  libvlc_video_set_format(mLibvlcMediaPlayer, mTargetChroma.c_str(), width, height, width * mBpp);
  libvlc_video_set_callbacks(mLibvlcMediaPlayer, &LibvlcLockBuffer, &LibvlcUnlockBuffer, NULL, &mLibvlcData);

  mLibvlcData.bufferSize = width * height * mBpp;
  // Libvlc wants 32 byte alignment for images (should in theory do this for all image lines)
  mLibvlcData.buffer = (uint8_t*)zm_mallocaligned(64, mLibvlcData.bufferSize);
  mLibvlcData.prevBuffer = (uint8_t*)zm_mallocaligned(64, mLibvlcData.bufferSize);
  
  mLibvlcData.newImage.setValueImmediate(false);

  libvlc_media_player_play(mLibvlcMediaPlayer);

  return 0;
}
Exemple #4
0
 /** File has to be in one of the following formats:
     [file://]filename              Plain media file
     http://ip:port/file            HTTP URL
     ftp://ip:port/file             FTP URL
     mms://ip:port/file             MMS URL
     screen://                      Screen capture
     [dvd://][device][@raw_device]  DVD device
     [vcd://][device]               VCD device
     [cdda://][device]              Audio CD device
     udp:[[<source address>]@[<bind address>][:<bind port>]]
 */
 void open( const std::string& file, bool needPlay=true, unsigned int w=512, unsigned int h=512 )
 {
     _vlcMedia = libvlc_media_new_path( _vlc, file.c_str() );
     libvlc_media_player_set_media( _vlcPlayer, _vlcMedia );
     libvlc_video_set_callbacks( _vlcPlayer, &VLCImageStream::lockFunc, &VLCImageStream::unlockFunc,
                                 &VLCImageStream::displayFunc, this );
     libvlc_video_set_format( _vlcPlayer, "RGBA", w, h, w*4 );
     
     allocateImage( w, h, 1, GL_RGBA, GL_UNSIGNED_BYTE );
     if ( needPlay ) play();
 }
void VideoPlayer::open( const std::string& file, unsigned int w, unsigned int h )
{
    if ( libvlc_media_player_is_playing(_vlcPlayer)==1 )
    {
        libvlc_media_player_stop( _vlcPlayer );
        libvlc_media_release( _vlcMedia );
    }
    
    std::string protocol = osgDB::getServerProtocol( file );
    if ( !protocol.empty() ) _vlcMedia = libvlc_media_new_location( _vlc, file.c_str() );
    else _vlcMedia = libvlc_media_new_path( _vlc, file.c_str() );
    
    libvlc_media_player_set_media( _vlcPlayer, _vlcMedia );
    libvlc_video_set_callbacks( _vlcPlayer, &VideoPlayer::lockFunc, &VideoPlayer::unlockFunc,
                                &VideoPlayer::displayFunc, this );
    libvlc_video_set_format( _vlcPlayer, "RGBA", w, h, w*4 );
    
    allocateImage( w, h, 1, GL_RGBA, GL_UNSIGNED_BYTE );
    setInternalTextureFormat( GL_RGBA );
}
Exemple #6
0
static void
_file_set(struct _App *app)
{
   if (app->opening)
     {
	libvlc_media_release(app->m);
	libvlc_media_player_release(app->mp);
	free(app->filename);
     }

   _em_str_read(app->em_read, &app->filename);

   app->m = libvlc_media_new_path(app->libvlc, app->filename);
   if (!app->m)
     {
	fprintf(stderr, "could not open path: \"%s\"\n", app->filename);
	return;
     }
   app->mp = libvlc_media_player_new_from_media(app->m);

   if (!app->mp)
     {
	fprintf(stderr, "could not create new player from media.\n");
	return;
     }

   app->opening = 1;
   libvlc_video_set_format(app->mp, "RV32", DEFAULTWIDTH, DEFAULTHEIGHT, DEFAULTWIDTH * 4);
   libvlc_video_set_callbacks(app->mp, _tmp_lock, _tmp_unlock, _tmp_display, app);
   app->event_mgr = libvlc_media_player_event_manager(app->mp);
   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerPositionChanged,
		       _event_cb, app);
   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerStopped,
		       _event_cb, app);

   app->mevent_mgr = libvlc_media_event_manager(app->m);

   app->tmpbuffer = malloc(sizeof(char) * DEFAULTWIDTH * DEFAULTHEIGHT * 4);
   libvlc_audio_set_mute(app->mp, 1);
   libvlc_media_player_play(app->mp);
}
Exemple #7
0
static void
_file_set_done(struct _App *app)
{
   int r;

   app->opening = 0;

   r = emotion_generic_shm_get(app->shmname, &app->vs, &app->vf);
   if (!r)
     {
	free(app->filename);
        libvlc_media_release(app->m);
        libvlc_media_player_release(app->mp);
	app->filename = NULL;
	app->m = NULL;
	app->mp = NULL;
	_send_cmd_start(app, EM_RESULT_FILE_SET_DONE);
	SEND_CMD_PARAM(app, r);
	_send_cmd_finish(app);
     }
   app->w = app->vs->width;
   app->h = app->vs->height;
   libvlc_video_set_format(app->mp, "RV32", app->w, app->h, app->w * 4);
   libvlc_video_set_callbacks(app->mp, _lock, _unlock, _display, app);


   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerPlaying,
		       _event_cb, app);
   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerTimeChanged,
		       _event_cb, app);
   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerLengthChanged,
		       _event_cb, app);
   libvlc_event_attach(app->event_mgr, libvlc_MediaPlayerSeekableChanged,
		       _event_cb, app);

   libvlc_audio_set_mute(app->mp, 0);

   _send_cmd_start(app, EM_RESULT_FILE_SET_DONE);
   SEND_CMD_PARAM(app, r);
   _send_cmd_finish(app);
}
Exemple #8
0
void VideoWidget::load(QString file)
{
	qDebug() << "Loading media:" << file;

	m = libvlc_media_new_path(inst,file.toAscii());//libvlc_media_new_location (inst, file.toAscii());
	if (!m)
	{
		qDebug() << "Error loading media location:" << libvlc_errmsg();
	}
	mp = libvlc_media_player_new_from_media (m);
	if (!mp)
	{
		qDebug() << "Error loading media player" << libvlc_errmsg();
	}
	libvlc_media_release (m);
	//libvlc_media_player_set_xwindow(mp, this->winId()); //Old code for loading to a winId
	libvlc_video_set_callbacks(mp, lock, unlock, display, this);

	libvlc_video_set_format(mp, "RV32", pix->width(), pix->height(), pix->width()*4);
	mediaLoaded = true;
}
void VlcVideoWidget::RestartPlayback()
{
    if (!status.doRestart)
        return;
    status.doRestart = false;
    
    vlcPlayer_ = libvlc_media_player_new_from_media(vlcMedia_);
    
    libvlc_event_manager_t *em = libvlc_media_player_event_manager(vlcPlayer_);
    libvlc_event_attach(em, libvlc_MediaPlayerMediaChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerOpening, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerBuffering, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPlaying, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPaused, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerStopped, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerEncounteredError, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerTimeChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPositionChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerSeekableChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPausableChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerTitleChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerLengthChanged, &VlcEventHandler, this);

    libvlc_video_set_callbacks(
        vlcPlayer_,
        &CallBackLock,
        &CallBackUnlock,
        &CallBackDisplay,
        this);

    renderPixmap_ = QImage(status.sourceSize.width(), status.sourceSize.height(), QImage::Format_RGB32);
    libvlc_video_set_format(vlcPlayer_, "RV32", renderPixmap_.width(), renderPixmap_.height(), renderPixmap_.bytesPerLine());

    if (!status.doNotPlayAfterRestart)
    {
        Play();
        status.doNotPlayAfterRestart = false;
    }
}
NetworkStream::NetworkStream(const char * networkStream, ImageProcessor * proc, int mediaWidth, int mediaHeight)
{
#if USE_VLC
    imageProcessor = proc;
    libVlcInstance = NULL;
    mediaPlayer = NULL;

    // Hack since callback functions require static instance.
    imProc = imageProcessor;

    const char * const vlc_args[] = {
    "--no-media-library",
    "--reset-plugins-cache",
    "--no-stats",
    "--no-osd",
    "--no-video-title-show",
    "--plugin-path=/usr/local/lib/"};
    printf("Starting Network Stream: %dx%d\n", mediaWidth, mediaHeight);
    libVlcInstance = libvlc_new(6,vlc_args);

    libvlc_media_t * media = libvlc_media_new_path(libVlcInstance, networkStream);

    mediaPlayer = libvlc_media_player_new_from_media(media);

    libvlc_media_release(media);


    context = ( struct ctx* )malloc( sizeof( *context ) );
    context->image = cvCreateImage(cvSize(mediaWidth, mediaHeight), IPL_DEPTH_8U, 4);
    context->pixels = (unsigned char *)context->image->imageData;

    //libvlc_media_player_set_media( mediaPlayer, media);
    libvlc_video_set_callbacks(mediaPlayer, lock, unlock, display, context);
    libvlc_video_set_format(mediaPlayer, "RV32", mediaWidth, mediaHeight, mediaWidth*4);
#endif
}
bool VideoPlayer::initPlayer(string mediaURL) {
	if(VideoPlayer::disabled == true) {
		return true;
	}

#ifdef HAS_LIBVLC
	ctxPtr->libvlc = NULL;
	ctxPtr->m = NULL;
	ctxPtr->mp = NULL;
	ctxPtr->vlc_argv.clear();
	ctxPtr->vlc_argv.push_back("--intf=dummy");
	//ctxPtr->vlc_argv.push_back("--intf=http");
	//ctxPtr->vlc_argv.push_back("--no-media-library");
	ctxPtr->vlc_argv.push_back("--ignore-config"); /* Don't use VLC's config */
	ctxPtr->vlc_argv.push_back("--no-xlib"); /* tell VLC to not use Xlib */
	ctxPtr->vlc_argv.push_back("--no-video-title-show");
	//ctxPtr->vlc_argv.push_back("--network-caching=10000");

	if(loop == true) {
		ctxPtr->vlc_argv.push_back("--loop");
		ctxPtr->vlc_argv.push_back("--repeat");
	}

#if defined(LIBVLC_VERSION_PRE_2)
	ctxPtr->vlc_argv_str.push_back("--plugin-path=" + pluginsPath);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
#endif

#if defined(LIBVLC_VERSION_PRE_2) && defined(LIBVLC_VERSION_PRE_1_1_0)
	char clock[64], cunlock[64], cdata[64];
    char cwidth[32], cheight[32], cpitch[32];
	/*
         *  Initialise libVLC
	 */
	sprintf(clock, "%lld", (long long int)(intptr_t)lock);
	sprintf(cunlock, "%lld", (long long int)(intptr_t)unlock);
	sprintf(cdata, "%lld", (long long int)(intptr_t)ctxPtr);
	sprintf(cwidth, "%i", width);
	sprintf(cheight, "%i", height);
	sprintf(cpitch, "%i", colorBits);

	vlc_argv.push_back("--vout");
	vlc_argv.push_back("vmem");
	vlc_argv.push_back("--vmem-width");
	ctxPtr->vlc_argv_str.push_back(cwidth);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
    vlc_argv.push_back("--vmem-height");
	ctxPtr->vlc_argv_str.push_back(cheight);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
    vlc_argv.push_back("--vmem-pitch");
	ctxPtr->vlc_argv_str.push_back(cpitch);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
    vlc_argv.push_back("--vmem-chroma");
	vlc_argv.push_back("RV16");
    vlc_argv.push_back("--vmem-lock");
	ctxPtr->vlc_argv_str.push_back(clock);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
    vlc_argv.push_back("--vmem-unlock");
	ctxPtr->vlc_argv_str.push_back(cunlock);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());
    vlc_argv.push_back("--vmem-data");
	ctxPtr->vlc_argv_str.push_back(cdata);
	ctxPtr->vlc_argv.push_back(ctxPtr->vlc_argv_str[ctxPtr->vlc_argv_str.size()-1].c_str());

#endif

	if(verboseEnabled) ctxPtr->vlc_argv.push_back("--verbose=2");
	if(verboseEnabled) ctxPtr->vlc_argv.push_back("--extraintf=logger"); //log anything
#if defined(WIN32)
	if(verboseEnabled) _putenv("VLC_VERBOSE=2");
#endif
	int vlc_argc = ctxPtr->vlc_argv.size();

//	char const *vlc_argv[] =
//	{
//		//"--no-audio", /* skip any audio track */
//		"--no-xlib", /* tell VLC to not use Xlib */
//		"--no-video-title-show",
//		pluginParam.c_str(),
//	};
//	int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);
#endif

	ctxPtr->empty = NULL;
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
	// Init Texture
	glGenTextures(1, &ctxPtr->textureId);
	glBindTexture(GL_TEXTURE_2D, ctxPtr->textureId);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	ctxPtr->empty = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height,
			colorBits, 0, 0, 0, 0);
	ctxPtr->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height,
			colorBits, 0x001f, 0x07e0, 0xf800, 0);
	ctxPtr->mutex = SDL_CreateMutex();

#ifdef HAS_LIBVLC
	/*
	 *  Initialize libVLC
	 */
	if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));

#if defined(LIBVLC_VERSION_PRE_2) && defined(LIBVLC_VERSION_PRE_1_1_0)
	libvlc_exception_t ex;
	libvlc_exception_init(&ex);

	ctxPtr->libvlc = libvlc_new(ctxPtr->vlc_argc, &ctxPtr->vlc_argv[0],&ex);
	catchError(&ex);
#else
	ctxPtr->libvlc = libvlc_new(vlc_argc, &ctxPtr->vlc_argv[0]);
#endif

	if(verboseEnabled) printf("In [%s] Line: %d, libvlc [%p]\n",__FUNCTION__,__LINE__,ctxPtr->libvlc);

/* It is meaningless to try all this because we have to restart mg to pickup new env vars
#if defined(WIN32)
	if(libvlc == NULL) {
		// For windows check registry for install path
		std::string strValue = getRegKey("Software\\VideoLAN\\VLC", "InstallDir");
		if(strValue != "") {
			if(strValue.length() >= 2) {
				if(strValue[0] == '"') {
					strValue = strValue.erase(0);
				}
				if(strValue[strValue.length()-1] == '"') {
					strValue = strValue.erase(strValue.length()-1);
				}
			}
			strValue = "VLC_PLUGIN_PATH=" + strValue;
			_putenv(strValue.c_str());

			if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));
			libvlc = libvlc_new(vlc_argc, &vlc_argv[0]);
		}

		if(libvlc == NULL) {
			_putenv("VLC_PLUGIN_PATH=c:\\program files\\videolan\\vlc\\plugins");

			if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));
			libvlc = libvlc_new(vlc_argc, &vlc_argv[0]);
		}
		if(libvlc == NULL) {
			_putenv("VLC_PLUGIN_PATH=\\program files\\videolan\\vlc\\plugins");

			if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));
			libvlc = libvlc_new(vlc_argc, &vlc_argv[0]);
		}
		if(libvlc == NULL) {
			_putenv("VLC_PLUGIN_PATH=c:\\program files (x86)\\videolan\\vlc\\plugins");

			if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));
			libvlc = libvlc_new(vlc_argc, &vlc_argv[0]);
		}
		if(libvlc == NULL) {
			_putenv("VLC_PLUGIN_PATH=\\program files (x86)\\videolan\\vlc\\plugins");

			if(verboseEnabled) printf("Trying [%s]\n",getenv("VLC_PLUGIN_PATH"));
			libvlc = libvlc_new(vlc_argc, &vlc_argv[0]);
		}
	}
#endif
*/

	if(ctxPtr->libvlc != NULL) {
#if defined(LIBVLC_VERSION_PRE_2) && defined(LIBVLC_VERSION_PRE_1_1_0)
		ctxPtr->m = libvlc_media_new(ctxPtr->libvlc, mediaURL.c_str(), &ex);
		if(verboseEnabled) printf("In [%s] Line: %d, m [%p]\n",__FUNCTION__,__LINE__,ctxPtr->m);

		catchError(&ex);
		ctxPtr->mp = libvlc_media_player_new_from_media(ctxPtr->m);
		if(verboseEnabled) printf("In [%s] Line: %d, mp [%p]\n",__FUNCTION__,__LINE__,ctxPtr->mp);

		libvlc_media_release(ctxPtr->m);
#else
		if(mediaURL.find(HTTP_PREFIX) == 0) {
			ctxPtr->mlp = libvlc_media_list_player_new(ctxPtr->libvlc);
			ctxPtr->ml = libvlc_media_list_new(ctxPtr->libvlc);
			ctxPtr->m = libvlc_media_new_location(ctxPtr->libvlc, mediaURL.c_str());

			libvlc_media_list_add_media(ctxPtr->ml, ctxPtr->m);
		}
		else {
			ctxPtr->m = libvlc_media_new_path(ctxPtr->libvlc, mediaURL.c_str());
		}

		/* Create a new item */
		if(verboseEnabled) printf("In [%s] Line: %d, m [%p]\n",__FUNCTION__,__LINE__,ctxPtr->m);

		if(loop == true) {
			libvlc_media_add_option(ctxPtr->m, "input-repeat=-1");
		}

		if(mediaURL.find(HTTP_PREFIX) == 0) {
			ctxPtr->mp = libvlc_media_player_new(ctxPtr->libvlc);
		}
		else {
			ctxPtr->mp = libvlc_media_player_new_from_media(ctxPtr->m);
		}
		if(verboseEnabled) printf("In [%s] Line: %d, mp [%p]\n",__FUNCTION__,__LINE__,ctxPtr->mp);

		libvlc_media_player_set_media(ctxPtr->mp, ctxPtr->m);

		libvlc_media_release(ctxPtr->m);

		if(mediaURL.find(HTTP_PREFIX) == 0) {
			// Use our media list
			libvlc_media_list_player_set_media_list(ctxPtr->mlp, ctxPtr->ml);

			// Use a given media player
			libvlc_media_list_player_set_media_player(ctxPtr->mlp, ctxPtr->mp);
		}

		// Get an event manager for the media player.
		if(mediaURL.find(HTTP_PREFIX) == 0) {
			libvlc_event_manager_t *eventManager = libvlc_media_list_player_event_manager(ctxPtr->mlp);

			if(eventManager) {
//				libvlc_event_attach(eventManager, libvlc_MediaPlayerPlaying, (libvlc_callback_t)trapPlayingEvent, NULL, &ex);
//				libvlc_event_attach(eventManager, libvlc_MediaPlayerEndReached, (libvlc_callback_t)trapEndReachedEvent, NULL, &ex);
//				libvlc_event_attach(eventManager, libvlc_MediaPlayerBuffering, (libvlc_callback_t)trapBufferingEvent, NULL, &ex);
//				libvlc_event_attach(eventManager, libvlc_MediaPlayerEncounteredError, (libvlc_callback_t)trapErrorEvent, NULL, &ex);

				int event_added = libvlc_event_attach( eventManager, libvlc_MediaListPlayerNextItemSet, callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListPlayerNextItemSet]\n");
				}
			}
		}
		//else {
			//libvlc_event_manager_t *eventManager = libvlc_media_player_event_manager(mp, &ex);
			libvlc_event_manager_t *eventManager = libvlc_media_player_event_manager(ctxPtr->mp);
			if(eventManager) {
				int event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerSnapshotTaken,   callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerSnapshotTaken]\n");
				}
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerTimeChanged,     callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerTimeChanged]\n");
//				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerPlaying,         callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerPlaying]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerPaused,          callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerPaused]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerStopped,         callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerStopped]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerEndReached,      callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerEndReached]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerPositionChanged, callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerPositionChanged]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerLengthChanged,   callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerLengthChanged]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerEncounteredError,callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerEncounteredError]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerPausableChanged, callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerPausableChanged]\n");
				}

				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerSeekableChanged, callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerSeekableChanged]\n");
				}

//				event_added = libvlc_event_attach( eventManager, libvlc_MediaStateChanged, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaStateChanged]\n");
//				}

//				event_added = libvlc_event_attach( eventManager, libvlc_MediaParsedChanged, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaParsedChanged]\n");
//				}

#if defined(LIBVLC_VERSION_PRE_2) && defined(LIBVLC_VERSION_PRE_1_1_0)
				event_added = libvlc_event_attach( eventManager, libvlc_MediaPlayerVout, callbacks, ctxPtr );
				if(event_added != 0) {
					printf("ERROR CANNOT ADD EVENT [libvlc_MediaPlayerVout]\n");
				}
#endif

//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListItemAdded, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListItemAdded]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListWillAddItem, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListWillAddItem]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListItemDeleted, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListItemDeleted]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListWillDeleteItem, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListWillDeleteItem]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListViewItemAdded, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListViewItemAdded]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListViewWillAddItem, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListViewWillAddItem]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListViewItemDeleted, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListViewItemDeleted]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListViewWillDeleteItem, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListViewWillDeleteItem]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListPlayerPlayed, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListPlayerPlayed]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListPlayerNextItemSet, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListPlayerNextItemSet]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaListPlayerStopped, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaListPlayerStopped]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaDiscovererStarted, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaDiscovererStarted]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_MediaDiscovererEnded, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_MediaDiscovererEnded]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaAdded, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaAdded]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaRemoved, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaRemoved]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaChanged, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaChanged]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStarted, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStarted]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStopped, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStopped]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusInit, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusInit]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusOpening, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusOpening]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusPlaying, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusPlaying]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusPause, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusPause]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusEnd, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusEnd]\n");
//				}
//
//				event_added = libvlc_event_attach( eventManager, libvlc_VlmMediaInstanceStatusError, callbacks, ctxPtr );
//				if(event_added != 0) {
//					printf("ERROR CANNOT ADD EVENT [libvlc_VlmMediaInstanceStatusError]\n");
//				}

			}
		//}

		//libvlc_media_release(ctxPtr->m);
#endif


#if !defined(LIBVLC_VERSION_PRE_2) && !defined(LIBVLC_VERSION_PRE_1_1_0)
		libvlc_video_set_callbacks(ctxPtr->mp, lock, unlock, display, ctxPtr);
		libvlc_video_set_format(ctxPtr->mp, "RV16", width, height, this->surface->pitch);

#endif

		ctxPtr->isPlaying = true;

#if defined(LIBVLC_VERSION_PRE_2) && defined(LIBVLC_VERSION_PRE_1_1_0)
		int play_result = libvlc_media_player_play(ctxPtr->mp,&ex);
#else
		int play_result = 0;
		if(mediaURL.find(HTTP_PREFIX) == 0) {
			libvlc_media_list_player_play(ctxPtr->mlp);
		}
		else {
			play_result = libvlc_media_player_play(ctxPtr->mp);
		}
		// Play
		//int play_result = 0;
		//libvlc_media_list_player_play(ctxPtr->mlp);
#endif

		//SDL_Delay(5);
		if(verboseEnabled) printf("In [%s] Line: %d, play_result [%d]\n",__FUNCTION__,__LINE__,play_result);

		successLoadingLib = (play_result == 0);

	}
#endif

	return successLoadingLib;
}
/**
 * Thumbnailer main function.
 * return null if the thumbail generation failed.
 **/
jbyteArray Java_org_videolan_vlc_LibVLC_getThumbnail(JNIEnv *env, jobject thiz,
        jint instance, jstring filePath,
        jint width, jint height)
{
    libvlc_instance_t *libvlc = (libvlc_instance_t *)instance;
    jbyteArray byteArray = NULL;

    /* Create the thumbnailer data structure */
    thumbnailer_sys_t *sys = calloc(1, sizeof(thumbnailer_sys_t));
    if (sys == NULL)
    {
        LOGE("Couldn't create the thumbnailer data structure!");
        return NULL;
    }

    /* Initialize the barrier. */
    pthread_mutex_init(&sys->doneMutex, NULL);
    pthread_cond_init(&sys->doneCondVar, NULL);

    /* Create a media player playing environment */
    sys->mp = libvlc_media_player_new(libvlc);

    libvlc_media_t *m = new_media(instance, env, thiz, filePath);
    if (m == NULL)
    {
        LOGE("Couldn't create the media to play!");
        goto end;
    }
    libvlc_media_add_option( m, ":no-audio" );

    libvlc_media_player_set_media(sys->mp, m);
    libvlc_media_release(m);

    /* Get the size of the video with the tracks information of the media. */
    libvlc_media_track_info_t *tracks;
    libvlc_media_parse(m);
    int nbTracks = libvlc_media_get_tracks_info(m, &tracks);

    unsigned i, videoWidth, videoHeight;
    bool hasVideoTrack = false;
    for (i = 0; i < nbTracks; ++i)
        if (tracks[i].i_type == libvlc_track_video)
        {
            videoWidth = tracks[i].u.video.i_width;
            videoHeight = tracks[i].u.video.i_height;
            hasVideoTrack = true;
            break;
        }

    free(tracks);

    /* Abord if we have not found a video track. */
    if (!hasVideoTrack)
    {
        LOGE("Could not find a video track in this file.\n");
        goto end;
    }

    /* Compute the size parameters of the frame to generate. */
    unsigned picWidth  = width;
    unsigned picHeight = height;
    float videoAR = (float)videoWidth / videoHeight;
    float screenAR = (float)width / height;
    if (screenAR < videoAR)
    {
        picHeight = (float)width / videoAR;
        sys->thumbnailOffset = (height - picHeight) / 2 * width * PIXEL_SIZE;
    }
    else
    {
        picWidth = (float)height * videoAR;
        sys->thumbnailOffset = (width - picWidth) / 2 * PIXEL_SIZE;
    }

    sys->picPitch = picWidth * PIXEL_SIZE;
    sys->lineSize = width * PIXEL_SIZE;
    sys->nbLines = picHeight;

    /* Allocate the memory to store the frames. */
    unsigned picSize = sys->picPitch * picHeight;
    sys->frameData = malloc(picSize);
    if (sys->frameData == NULL)
    {
        LOGE("Couldn't allocate the memory to store the frame!");
        goto end;
    }

    /* Allocate the memory to store the thumbnail. */
    unsigned thumbnailSize = width * height * PIXEL_SIZE;
    sys->thumbnail = calloc(thumbnailSize, 1);
    if (sys->thumbnail == NULL)
    {
        LOGE("Couldn't allocate the memory to store the thumbnail!");
        goto end;
    }

    /* Set the video format and the callbacks. */
    libvlc_video_set_format(sys->mp, "RGBA", picWidth, picHeight, sys->picPitch);
    libvlc_video_set_callbacks(sys->mp, thumbnailer_lock, thumbnailer_unlock,
                               NULL, (void*)sys);

    /* Play the media. */
    libvlc_media_player_play(sys->mp);
    libvlc_media_player_set_position(sys->mp, THUMBNAIL_POSITION);

    /* Wait for the thumbnail to be generated. */
    pthread_mutex_lock(&sys->doneMutex);
    while (!sys->hasThumb)
        pthread_cond_wait(&sys->doneCondVar, &sys->doneMutex);
    pthread_mutex_unlock(&sys->doneMutex);

    /* Stop and realease the media player. */
    libvlc_media_player_stop(sys->mp);
    libvlc_media_player_release(sys->mp);

    /* Create the Java byte array to return the create thumbnail. */
    byteArray = (*env)->NewByteArray(env, thumbnailSize);
    if (byteArray == NULL)
    {
        LOGE("Couldn't allocate the Java byte array to store the frame!");
        goto end;
    }

    (*env)->SetByteArrayRegion(env, byteArray, 0, thumbnailSize,
                               (jbyte *)sys->thumbnail);

    (*env)->DeleteLocalRef(env, byteArray);

end:
    pthread_mutex_destroy(&sys->doneMutex);
    pthread_cond_destroy(&sys->doneCondVar);
    free(sys->thumbnail);
    free(sys->frameData);
    free(sys);

    return byteArray;
}
Exemple #13
0
bool VLCVideoWrapper::open(const std::string& ThePath, Window* const TheWindow)
{
    bool errorOpening(false);

    //BoostPath PluginsDirPath("/Applications/VLC.app/Contents/MacOS/modules");
    BoostPath PluginsDirPath("/Applications/VLC-1.1.7.app/Contents/MacOS/modules");

    std::vector<std::string> VLCArguments;

    VLCArguments.push_back("-I");
    VLCArguments.push_back("dummy"); /* no interface */

    VLCArguments.push_back(std::string("--plugin-path=") + PluginsDirPath.string());

    //VLCArguments.push_back("--no-audio"); [> we don't want audio <]
    VLCArguments.push_back("--verbose=0"); /* show only errors */
    VLCArguments.push_back("--no-media-library");/* don't want that */
    VLCArguments.push_back("--services-discovery=");/* don't want that */
    VLCArguments.push_back("--no-video-title-show");/* don't want that */
    VLCArguments.push_back("--no-stats");/* don't want that */
    VLCArguments.push_back("--ignore-config"); /* don't use/overwrite the config */
    VLCArguments.push_back("--no-sub-autodetect");/* don't want subtitles */
    VLCArguments.push_back("--control=");/* don't want interface (again) */
    VLCArguments.push_back("--no-disable-screensaver");/* don't want that */

    // libvlc settings 
    const char** args = new const char*[VLCArguments.size()];
    for(UInt32 i(0) ; i<VLCArguments.size() ; ++i)
    {
        args[i] = VLCArguments[i].c_str();
    }

    /*
     *  Initialise libVLC
     */
    UInt32 nargs = VLCArguments.size();
    _VLCInstance = libvlc_new( nargs, args );
    if(_VLCInstance == NULL)
    {
        checkVLCError("creating new vlc instance");
        return false;
    }

    delete [] args;


    // creates vlc struct holding data to the video file
    libvlc_media_t *TheMedia = libvlc_media_new_path( _VLCInstance, ThePath.c_str() );
    checkVLCError("initializing media file");

    // initialize a temporary media player so we can get height and width before
    // adding the vmem options to TheMedia
    libvlc_media_player_t * tempMediaPlayer = libvlc_media_player_new_from_media( TheMedia );

    unsigned Width(200), Height(200);
    libvlc_video_set_callbacks(tempMediaPlayer,
                               lock,
                               unlock,
                               display,
                               &_VideoMemContext);

    _VideoMemContext._pixels = ( UInt8* )malloc( ( sizeof( *( _VideoMemContext._pixels ) )
                                                   * Width
                                                   * Height ) * 4 );

    libvlc_video_set_format(tempMediaPlayer,
                            "RV24",
                            Width,
                            Height,
                            Width * 3);

    //Release the media file
    libvlc_media_release( TheMedia );

    libvlc_media_player_play( tempMediaPlayer );
    checkVLCError("playing the media");

    libvlc_state_t currentState;
    do
    {
        currentState = libvlc_media_player_get_state(tempMediaPlayer);
        checkVLCError("getting state");
    } while(currentState != libvlc_Playing);

    int VLCResult;
    do
    {
        VLCResult = libvlc_video_get_size(tempMediaPlayer, 0, &Width, &Height);
    } while(VLCResult != 0);
    checkVLCError("getting size");
    libvlc_media_player_stop( tempMediaPlayer );
    libvlc_media_player_release(tempMediaPlayer);// releases media currently in use


    //Now that we have the size initialize the media again
    TheMedia = libvlc_media_new_path( _VLCInstance, ThePath.c_str() );
    checkVLCError("initializing media file");

    // initialize the media player
    _MediaPlayer = libvlc_media_player_new_from_media( TheMedia );
    checkVLCError("initializing media player");

    //Release the media file
    libvlc_media_release( TheMedia );

#ifdef __APPLE__
    //set agl handle (if TheWindow is pointing to a carbon window)
    if (TheWindow->getType().isDerivedFrom(CarbonWindow::getClassType()))
    {
        HIWindowRef windowRef = aglGetWindowRef(dynamic_cast<CarbonWindow* const>(TheWindow)->getContext());

        HIViewRef contentView = 0;
        GetRootControl(windowRef, &contentView);


        //uint32_t aglHandler = CarbonWindowPtr::dcast(TheWindow)->winId();
        libvlc_media_player_set_agl (_MediaPlayer, reinterpret_cast<uint32_t>(contentView) );
        checkVLCError("attaching media player to carbon window");
    }
#endif
#ifdef WIN32
    if (TheWindow->getType().isDerivedFrom(WIN32Window::getClassType()))
    {
        libvlc_media_player_set_hwnd (_MediaPlayer, dynamic_cast<WIN32Window* const>(TheWindow)->getHwnd() );
        checkVLCError("attaching media player to WIN32 window");
    }
#endif
#ifdef __linux
    if (TheWindow->getType().isDerivedFrom(XWindow::getClassType()))
    {
        libvlc_media_player_set_xwindow (_MediaPlayer, dynamic_cast<XWindow* const>(TheWindow)->getDisplay() );
        checkVLCError("attaching media player to Xwindow");
    }
#endif

    libvlc_video_set_callbacks(_MediaPlayer,
                               lock,
                               unlock,
                               display,
                               &_VideoMemContext);

    _VideoMemContext._pixels = ( UInt8* )malloc( ( sizeof( *( _VideoMemContext._pixels ) )
                                                   * Width
                                                   * Height ) * 4 );

    libvlc_video_set_format(_MediaPlayer,
                            "RV24",
                            Width,
                            Height,
                            Width * 3);

    //Start playing the video
    libvlc_media_player_play( _MediaPlayer );
    checkVLCError("playing the media");

    do
    {
        currentState = libvlc_media_player_get_state(_MediaPlayer);
        checkVLCError("getting state");
    } while(currentState != libvlc_Playing);

    clock_t endwait;
    endwait = clock () + 2 * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}



    _Initialized = true;

    // check if the player can be paused
    if(libvlc_media_player_can_pause(_MediaPlayer))
    {	// can pause it?  do it
        libvlc_media_player_pause(_MediaPlayer);
        // error checking of course
        checkVLCError("pausing media player");

        libvlc_media_player_set_position( _MediaPlayer, 0.0f );
        checkVLCError("setting position during player initialization");
    }

    return errorOpening;
}
int Ibex::VLCVideoPlayer::playVLCVideo(const char *fileName, Display *dpy, GLXDrawable root) {
    libvlc_instance_t *libvlc;
    libvlc_media_t *m;
    libvlc_media_player_t *mp;
    char const *vlc_argv[] = {
        //"-H"
        "--text-renderer","none"
        //"--reset-plugins-cache",
        //"--reset-config"
      //"--no-audio", // Don't play audio.
       //"--no-xlib" // Don't use Xlib.

        // Apply a video filter.
        //"--video-filter", "sepia",
        //"--sepia-intensity=200"
    };
    int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);

    int done = 0, action = 0, pause = 0;
    struct context context;
    context.isStereo = 0;
    context.videoTexture = videoTexture;
    context.player = this;
    context.dpy = dpy;
    context.root = root;
    context.data = data;

    // create texture/mutex

    // If you don't have this variable set you must have plugins directory
    // with the executable or libvlc_new() will not work!
    printf("VLC_PLUGIN_PATH=%s\n", getenv("VLC_PLUGIN_PATH"));

    // Initialise libVLC.
    libvlc = libvlc_new(vlc_argc, vlc_argv);
    if(NULL == libvlc) {
        printf("LibVLC initialization failure.\n");
        return EXIT_FAILURE;
    }

    m = libvlc_media_new_path(libvlc, fileName);
    mp = libvlc_media_player_new_from_media(m);
    libvlc_media_release(m);
    pixels = new uint32_t[VIDEOWIDTH*VIDEOHEIGHT*4];
    memset(pixels, 0, sizeof(uint32_t)*VIDEOWIDTH*VIDEOHEIGHT*4);
    libvlc_video_set_callbacks(mp, vlclock, vlcunlock, vlcdisplay, &context);
    libvlc_video_set_format(mp, "RV32", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH*sizeof(uint32_t));
    //libvlc_video_set_format(mp, "YUYV", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH*2);
    
    if(libvlc_video_get_size(mp, 0, &width, & height) == 0) {
        VIDEOWIDTH = width;
        VIDEOHEIGHT = height;
    }
        context.mp = mp;
    
    libvlc_media_player_play(mp);
    
    // Main loop.
    while(!done) {
        action = 0;
        switch(action) {
            case 'q':
                done = 1;
                break;
            case ' ':
                printf("Pause toggle.\n");
                pause = !pause;
                break;
        }

        if(!pause) { context.n++; }

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    // Stop stream and clean up libVLC.
    libvlc_media_player_stop(mp);
    libvlc_media_player_release(mp);
    libvlc_release(libvlc);

    // delete mutex/texture info

    quit(0);

    return 0;
}
Exemple #15
0
/**
 * Entry point (main func)
 */
int main(int argc, char **argv) {

    // Init SDL + OpenGL
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) == -1) {
        return -1;
    }
    SDL_SetVideoMode(W, H, 16, SDL_OPENGL);
    glewInit();
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_DEPTH_TEST);

    // Init Textures
    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_2D, textureId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glGenTextures(1, &textureId2);
    glBindTexture(GL_TEXTURE_2D, textureId2);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glGenTextures(1, &textureId3);
    glBindTexture(GL_TEXTURE_2D, textureId3);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Init SDL_surfaces
    sdlStruct.sdlSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, W, H, 16, 0xf800, 0x07e0, 0x001f, 0);
    sdlStruct.sdlMutex = SDL_CreateMutex();
    sdlStruct2.sdlSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, W, H, 16, 0xf800, 0x07e0, 0x001f, 0);
    sdlStruct2.sdlMutex = SDL_CreateMutex();
    sdlStruct3.sdlSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, W, H, 16, 0xf800, 0x07e0, 0x001f, 0);
    sdlStruct3.sdlMutex = SDL_CreateMutex();

    // Init LibVLC + media player
    const char *vlc_argv[] = {};
    int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);
    libvlc_instance_t * libVlcInstance = libvlc_new(vlc_argc, vlc_argv);
    libvlc_media_t * media = libvlc_media_new_path(libVlcInstance, VIDEOFILE);
    libvlc_media_player_t * mediaPlayer = libvlc_media_player_new_from_media(media);
    libvlc_media_release(media);
    libvlc_release(libVlcInstance);

    libvlc_video_set_callbacks(mediaPlayer, lockfct, unlockfct, NULL, &sdlStruct);
    libvlc_video_set_format(mediaPlayer, "RV16", W, H, W*2);

    // Init LibVLC Round2
    libvlc_instance_t * libVlcInstance2 = libvlc_new(vlc_argc, vlc_argv);
    libvlc_media_t * media2 = libvlc_media_new_path(libVlcInstance2, VIDEOFILE2);
    libvlc_media_player_t * mediaPlayer2 = libvlc_media_player_new_from_media(media2);
    libvlc_media_release(media2);
    libvlc_release(libVlcInstance2);

    libvlc_video_set_callbacks(mediaPlayer2, lockfct2, unlockfct2, NULL, &sdlStruct2);
    libvlc_video_set_format(mediaPlayer2, "RV16", W, H, W*2);

    //Round 3
    libvlc_instance_t * libVlcInstance3 = libvlc_new(vlc_argc, vlc_argv);
    libvlc_media_t * media3 = libvlc_media_new_path(libVlcInstance3, VIDEOFILE3);
    libvlc_media_player_t * mediaPlayer3 = libvlc_media_player_new_from_media(media3);
    libvlc_media_release(media3);
    libvlc_release(libVlcInstance3);

    libvlc_video_set_callbacks(mediaPlayer3, lockfct3, unlockfct3, NULL, &sdlStruct3);
    libvlc_video_set_format(mediaPlayer3, "RV16", W, H, W*2);

    // Start reading the video
    libvlc_media_player_play(mediaPlayer);
    libvlc_media_player_play(mediaPlayer2);
    libvlc_media_player_play(mediaPlayer3);
    libvlc_state_t state = libvlc_media_player_get_state(mediaPlayer);

    while ((state != libvlc_Ended) && (state != libvlc_Error)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


        loadTexture(); // Loading the texture

        // Square
        glBegin(GL_QUADS);
        glTexCoord2d(0, 0);
        glVertex2f(-0.95, 0.00);
        glTexCoord2d(0, 1);
        glVertex2f(-0.95, 0.95);
        glTexCoord2d(1, 1);
        glVertex2f(0.00, 0.95);
        glTexCoord2d(1, 0);
        glVertex2f(0.00, 0.00);
        glEnd();

        loadTexture2();

        glBegin(GL_QUADS);
        glTexCoord2d(0, 0);
        glVertex2f(0.05, 0.00);
        glTexCoord2d(0, 1);
        glVertex2f(0.05, 0.95);
        glTexCoord2d(1, 1);
        glVertex2f(0.95, 0.95);
        glTexCoord2d(1, 0);
        glVertex2f(0.95, 0.00);
        glEnd();

        loadTexture3();

        glBegin(GL_QUADS);
        glTexCoord2d(0, 0);
        glVertex2f(-0.95, -0.95);
        glTexCoord2d(0, 1);
        glVertex2f(-0.95, -0.05);
        glTexCoord2d(1, 1);
        glVertex2f(0.00, -0.05);
        glTexCoord2d(1, 0);
        glVertex2f(0.0, -0.95);
        glEnd();

        glFlush();
        SDL_GL_SwapBuffers();
        SDL_Delay(10);
        state = libvlc_media_player_get_state(mediaPlayer);
    }

    // Frees
    libvlc_media_player_stop(mediaPlayer);
    libvlc_media_player_stop(mediaPlayer2);
    libvlc_media_player_stop(mediaPlayer3);
    libvlc_media_player_release(mediaPlayer);
    libvlc_media_player_release(mediaPlayer2);
    libvlc_media_player_release(mediaPlayer3);
    SDL_DestroyMutex(sdlStruct.sdlMutex);
    SDL_FreeSurface(sdlStruct.sdlSurface);
    SDL_DestroyMutex(sdlStruct2.sdlMutex);
    SDL_FreeSurface(sdlStruct2.sdlSurface);
    SDL_DestroyMutex(sdlStruct3.sdlMutex);
    SDL_FreeSurface(sdlStruct3.sdlSurface);

    SDL_Quit();
    return 0;
}
bool VLCVideoTextureObjChunk::createVLCInstance(libvlc_time_t start_time, 
                                                bool          play      )
{
    libvlc_media_t *m;
    
    char const *vlc_argv[] =
    {       
        "-I", "dumy",      // No special interface
        "--ignore-config", // Don't use VLC's config        
        "--quiet",         // deactivates VLCs console outputs
        "--no-xlib",       // tell VLC to not use Xlib                   
        "--no-video-title-show", // no titles
    };
        
    int vlc_argc        = sizeof(vlc_argv       ) / sizeof(*vlc_argv       );
         
    // Initialize libVLC   
    if (libvlc==NULL) 
    {        
        libvlc = libvlc_new(vlc_argc, vlc_argv);        
    } 
    else 
    {
        if (vlcmediaplayer!=NULL) 
        {
            ctx.idstr = NULL;
            libvlc_media_player_stop(vlcmediaplayer);    
            libvlc_media_player_release(vlcmediaplayer);
            vlcmediaplayer = NULL;
            if (ctx.videothread!=NULL) {
                ctx.videothread->runFunction(NULL,NULL); // reset thread structure: isInititialized=false
            }
            ctx.videothread = NULL;            
        }
    }
    m = libvlc_media_new_path(libvlc, getUrl().c_str());
   
    vlcmediaplayer = libvlc_media_player_new_from_media(m);
   
    libvlc_media_release(m);

    ctx.idstr = strdup((std::string("video")+getVideoID()).c_str());
    ctx.videothread = NULL;            
    ctx.img = Image::create();
    ctx.img->set(OSG::Image::OSG_BGR_PF,getWidth(), getHeight());
    ctx.lock = Lock::create();
    
    this->setImage(ctx.img);
    this->setTarget(GL_TEXTURE_2D);
    ctx.self = this;


    vlceventmgr = libvlc_media_player_event_manager( vlcmediaplayer );
    // attach event to defined event handler callback
    libvlc_event_attach( vlceventmgr, libvlc_MediaPlayerEndReached, vlc_event, &ctx);

    libvlc_video_set_callbacks(vlcmediaplayer, vlc_lock, vlc_unlock, vlc_display, &ctx);
    libvlc_video_set_format(vlcmediaplayer, "RV24", getWidth(), getHeight(), getWidth()*3);
    if (getIsMaster()==false) libvlc_audio_set_mute(vlcmediaplayer, 1);
    
#if 0
    {
        SLOG << "available filters:" << std::endl;
        libvlc_module_description_t *list = libvlc_video_filter_list_get(libvlc);
        libvlc_module_description_t *iter = list;
        while(iter!=NULL) {
            SLOG << iter->psz_name << std::endl;
            iter = iter->p_next;
        }                
        libvlc_module_description_list_release(list);
    }
#endif
        

    libvlc_media_player_play(vlcmediaplayer);
    libvlc_media_player_set_time(vlcmediaplayer, start_time);
    if (!play) libvlc_media_player_pause(vlcmediaplayer); //not working?
    
    // add to static list
    //allVideoTextures.push_back(&ctx);

    lastSync=OSG::getTimeStamp();

    return true;
}
int main(int argc, char *argv[]) {

	libvlc_instance_t *libvlc;
	libvlc_media_t *m;
	libvlc_media_player_t *mp;
	char const *vlc_argv[] = {

		"--no-audio", // Don't play audio.
		"--no-xlib", // Don't use Xlib.

		// Apply a video filter.
		//"--video-filter", "sepia",
		//"--sepia-intensity=200"
	};
	int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);

	SDL_Event event;
	int done = 0, action = 0, pause = 0, n = 0;

	struct context context;

	if (argc < 2) {
		printf("Usage: %s <filename>\n", argv[0]);
		return EXIT_FAILURE;
	}

	// Initialise libSDL.
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		printf("Could not initialize SDL: %s.\n", SDL_GetError());
		return EXIT_FAILURE;
	}

	// Create SDL graphics objects.
	SDL_Window * window = SDL_CreateWindow(
		"Simple VLC player",
		SDL_WINDOWPOS_UNDEFINED,
		SDL_WINDOWPOS_UNDEFINED,
		WIDTH, HEIGHT,
		SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
	if (!window) {
		fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError());
		quit(3);
	}

	context.renderer = SDL_CreateRenderer(window, -1, 0);
	if (!context.renderer) {
		fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError());
		quit(4);
	}

	context.texture = SDL_CreateTexture(
		context.renderer,
		SDL_PIXELFORMAT_BGR565, SDL_TEXTUREACCESS_STREAMING,
		VIDEOWIDTH, VIDEOHEIGHT);
	if (!context.texture) {
		fprintf(stderr, "Couldn't create texture: %s\n", SDL_GetError());
		quit(5);
	}

	context.mutex = SDL_CreateMutex();

	// If you don't have this variable set you must have plugins directory
	// with the executable or libvlc_new() will not work!
	printf("VLC_PLUGIN_PATH=%s\n", getenv("VLC_PLUGIN_PATH"));

	// Initialise libVLC.
	libvlc = libvlc_new(vlc_argc, vlc_argv);
	if (NULL == libvlc) {
		printf("LibVLC initialization failure.\n");
		return EXIT_FAILURE;
	}

	m = libvlc_media_new_path(libvlc, argv[1]);
	mp = libvlc_media_player_new_from_media(m);
	libvlc_media_release(m);

	libvlc_video_set_callbacks(mp, lock, unlock, display, &context);
	libvlc_video_set_format(mp, "RV16", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH * 2);
	int result = libvlc_media_player_play(mp);

	// Main loop.
	while (!done) {

		action = 0;

		// Keys: enter (fullscreen), space (pause), escape (quit).
		while (SDL_PollEvent(&event)) {

			switch (event.type) {
			case SDL_QUIT:
				done = 1;
				break;
			case SDL_KEYDOWN:
				action = event.key.keysym.sym;
				break;
			}
		}

		switch (action) {
		case SDLK_ESCAPE:
		case SDLK_q:
			done = 1;
			break;
		case ' ':
			printf("Pause toggle.\n");
			pause = !pause;
			break;
		}

		if (!pause) { context.n++; }

		SDL_Delay(1000 / 10);
	}

	// Stop stream and clean up libVLC.
	libvlc_media_player_stop(mp);
	libvlc_media_player_release(mp);
	libvlc_release(libvlc);

	// Close window and clean up libSDL.
	SDL_DestroyMutex(context.mutex);
	SDL_DestroyRenderer(context.renderer);

	quit(0);

	return 0;
}
Exemple #18
0
/**
 * Thumbnailer main function.
 * return null if the thumbail generation failed.
 **/
jbyteArray Java_org_videolan_vlc_LibVLC_getThumbnail(JNIEnv *env, jobject thiz,
                                                     jlong instance, jstring filePath,
                                                     const jint frameWidth, const jint frameHeight)
{
    libvlc_instance_t *libvlc = (libvlc_instance_t *)(intptr_t)instance;
    jbyteArray byteArray = NULL;

    /* Create the thumbnailer data structure */
    thumbnailer_sys_t *sys = calloc(1, sizeof(thumbnailer_sys_t));
    if (sys == NULL)
    {
        LOGE("Could not create the thumbnailer data structure!");
        return NULL;
    }

    /* Initialize the barrier. */
    pthread_mutex_init(&sys->doneMutex, NULL);
    pthread_cond_init(&sys->doneCondVar, NULL);

    /* Create a media player playing environment */
    libvlc_media_player_t *mp = libvlc_media_player_new(libvlc);

    libvlc_media_t *m = new_media(instance, env, thiz, filePath, true, false);
    if (m == NULL)
    {
        LOGE("Could not create the media to play!");
        goto end;
    }

    /* Fast and no options */
    libvlc_media_add_option( m, ":no-audio" );
    libvlc_media_add_option( m, ":no-spu" );
    libvlc_media_add_option( m, ":no-osd" );

    libvlc_media_player_set_media(mp, m);

    /* Get the size of the video with the tracks information of the media. */
    libvlc_media_track_info_t *tracks;
    libvlc_media_parse(m);
    int nbTracks = libvlc_media_get_tracks_info(m, &tracks);
    libvlc_media_release(m);

    /* Parse the results */
    unsigned videoWidth, videoHeight;
    bool hasVideoTrack = false;
    for (unsigned i = 0; i < nbTracks; ++i)
        if (tracks[i].i_type == libvlc_track_video)
        {
            videoWidth = tracks[i].u.video.i_width;
            videoHeight = tracks[i].u.video.i_height;
            hasVideoTrack = true;
            break;
        }

    free(tracks);

    /* Abort if we have not found a video track. */
    if (!hasVideoTrack)
    {
        LOGE("Could not find any video track in this file.\n");
        goto end;
    }

    /* VLC could not tell us the size */
    if( videoWidth == 0 || videoHeight == 0 )
    {
        LOGE("Could not find the video dimensions.\n");
        goto end;
    }

    /* Compute the size parameters of the frame to generate. */
    unsigned thumbWidth  = frameWidth;
    unsigned thumbHeight = frameHeight;
    const float inputAR = (float)videoWidth / videoHeight;
    const float screenAR = (float)frameWidth / frameHeight;

    /* Most of the cases, video is wider than tall */
    if (screenAR < inputAR)
    {
        thumbHeight = (float)frameWidth / inputAR + 1;
        sys->blackBorders = ( (frameHeight - thumbHeight) / 2 ) * frameWidth;
    }
    else
    {
        LOGD("Weird aspect Ratio.\n");
        thumbWidth = (float)frameHeight * inputAR;
        sys->blackBorders = (frameWidth - thumbWidth) / 2;
    }

    sys->thumbPitch  = thumbWidth * PIXEL_SIZE;
    sys->thumbHeight = thumbHeight;
    sys->frameWidth  = frameWidth;

    /* Allocate the memory to store the frames. */
    size_t thumbSize = sys->thumbPitch * (sys->thumbHeight+1);
    sys->thumbData = malloc(thumbSize);
    if (sys->thumbData == NULL)
    {
        LOGE("Could not allocate the memory to store the frame!");
        goto end;
    }

    /* Allocate the memory to store the thumbnail. */
    unsigned frameSize = frameWidth * frameHeight * PIXEL_SIZE;
    sys->frameData = calloc(frameSize, 1);
    if (sys->frameData == NULL)
    {
        LOGE("Could not allocate the memory to store the thumbnail!");
        goto end;
    }

    /* Set the video format and the callbacks. */
    libvlc_video_set_format(mp, "RGBA", thumbWidth, thumbHeight, sys->thumbPitch);
    libvlc_video_set_callbacks(mp, thumbnailer_lock, thumbnailer_unlock,
                               NULL, (void*)sys);
    sys->state = THUMB_SEEKING;

    /* Play the media. */
    libvlc_media_player_play(mp);
    libvlc_media_player_set_position(mp, THUMBNAIL_POSITION);

    int loops = 100;
    for (;;) {
        float pos = libvlc_media_player_get_position(mp);
        if (pos > THUMBNAIL_POSITION || !loops--)
            break;
        usleep(50000);
    }

    /* Wait for the thumbnail to be generated. */
    pthread_mutex_lock(&sys->doneMutex);
    sys->state = THUMB_SEEKED;
    struct timespec deadline;
    clock_gettime(CLOCK_REALTIME, &deadline);
    deadline.tv_sec += 10; /* amount of seconds before we abort thumbnailer */
    do {
        int ret = pthread_cond_timedwait(&sys->doneCondVar, &sys->doneMutex, &deadline);
        if (ret == ETIMEDOUT)
            break;
    } while (sys->state != THUMB_DONE);
    pthread_mutex_unlock(&sys->doneMutex);

    /* Stop and release the media player. */
    libvlc_media_player_stop(mp);
    libvlc_media_player_release(mp);

    if (sys->state == THUMB_DONE) {
        /* Create the Java byte array to return the create thumbnail. */
        byteArray = (*env)->NewByteArray(env, frameSize);
        if (byteArray == NULL)
        {
            LOGE("Could not allocate the Java byte array to store the frame!");
            goto end;
        }

        (*env)->SetByteArrayRegion(env, byteArray, 0, frameSize,
                (jbyte *)sys->frameData);
    }

end:
    pthread_mutex_destroy(&sys->doneMutex);
    pthread_cond_destroy(&sys->doneCondVar);
    free(sys->frameData);
    free(sys->thumbData);
    free(sys);

    return byteArray;
}
Exemple #19
0
/**
 * Thumbnailer main function.
 * return null if the thumbail generation failed.
 **/
jbyteArray
Java_org_videolan_libvlc_util_VLCUtil_nativeGetThumbnail(JNIEnv *env,
                                                         jobject thiz,
                                                         jobject jmedia,
                                                         const jint frameWidth,
                                                         const jint frameHeight)
{
    vlcjni_object *p_obj = VLCJniObject_getInstance(env, jmedia);
    jbyteArray byteArray = NULL;

    /* Create the thumbnailer data structure */
    thumbnailer_sys_t *sys = calloc(1, sizeof(thumbnailer_sys_t));
    if (sys == NULL)
    {
        LOGE("Could not create the thumbnailer data structure!");
        goto enomem;
    }

    /* Initialize the barrier. */
    pthread_mutex_init(&sys->doneMutex, NULL);
    pthread_cond_init(&sys->doneCondVar, NULL);

    /* Create a media player playing environment */
    libvlc_media_player_t *mp = libvlc_media_player_new_from_media(p_obj->u.p_m);
    libvlc_media_player_set_video_title_display(mp, libvlc_position_disable, 0);

    /* Get the size of the video with the tracks information of the media. */
    libvlc_media_track_t **tracks;
    libvlc_media_parse(p_obj->u.p_m);
    int nbTracks = libvlc_media_tracks_get(p_obj->u.p_m, &tracks);

    /* Parse the results */
    unsigned videoWidth = 0, videoHeight = 0;
    bool hasVideoTrack = false;
    for (unsigned i = 0; i < nbTracks; ++i)
        if (tracks[i]->i_type == libvlc_track_video)
        {
            videoWidth = tracks[i]->video->i_width;
            videoHeight = tracks[i]->video->i_height;
            hasVideoTrack = true;
            break;
        }

    libvlc_media_tracks_release(tracks, nbTracks);

    /* Abort if we have not found a video track. */
    if (!hasVideoTrack)
    {
        LOGE("Could not find any video track in this file.\n");
        goto end;
    }

    LOGD("Video dimensions: %ix%i.\n", videoWidth, videoHeight );

    /* VLC could not tell us the size */
    if( videoWidth == 0 || videoHeight == 0 )
    {
        LOGE("Could not find the video dimensions.\n");
        goto end;
    }

    if( videoWidth < THUMBNAIL_MIN_WIDTH || videoHeight < THUMBNAIL_MIN_HEIGHT
        || videoWidth > THUMBNAIL_MAX_WIDTH || videoHeight > THUMBNAIL_MAX_HEIGHT )
    {
        LOGE("Wrong video dimensions.\n");
        goto end;
    }

    /* Compute the size parameters of the frame to generate. */
    unsigned thumbWidth  = frameWidth;
    unsigned thumbHeight = frameHeight;
    const float inputAR = (float)videoWidth / videoHeight;
    const float screenAR = (float)frameWidth / frameHeight;

    /* Most of the cases, video is wider than tall */
    if (screenAR < inputAR)
    {
        thumbHeight = (float)frameWidth / inputAR + 1;
        sys->blackBorders = ( (frameHeight - thumbHeight) / 2 ) * frameWidth;
    }
    else
    {
        LOGD("Weird aspect Ratio.\n");
        thumbWidth = (float)frameHeight * inputAR;
        sys->blackBorders = (frameWidth - thumbWidth) / 2;
    }

    sys->thumbPitch  = thumbWidth * PIXEL_SIZE;
    sys->thumbHeight = thumbHeight;
    sys->frameWidth  = frameWidth;

    /* Allocate the memory to store the frames. */
    size_t thumbSize = sys->thumbPitch * (sys->thumbHeight+1);
    sys->thumbData = malloc(thumbSize);
    if (sys->thumbData == NULL)
    {
        LOGE("Could not allocate the memory to store the frame!");
        goto end;
    }

    /* Allocate the memory to store the thumbnail. */
    unsigned frameSize = frameWidth * frameHeight * PIXEL_SIZE;
    sys->frameData = calloc(frameSize, 1);
    if (sys->frameData == NULL)
    {
        LOGE("Could not allocate the memory to store the thumbnail!");
        goto end;
    }

    /* Set the video format and the callbacks. */
    libvlc_video_set_format(mp, "RGBA", thumbWidth, thumbHeight, sys->thumbPitch);
    libvlc_video_set_callbacks(mp, thumbnailer_lock, thumbnailer_unlock,
                               NULL, (void*)sys);
    sys->state = THUMB_SEEKING;

    /* Play the media. */
    libvlc_media_player_play(mp);
    libvlc_media_player_set_position(mp, THUMBNAIL_POSITION);

    const int wait_time = 50000;
    const int max_attempts = 100;
    for (int i = 0; i < max_attempts; ++i) {
        if (libvlc_media_player_is_playing(mp) && libvlc_media_player_get_position(mp) >= THUMBNAIL_POSITION)
            break;
        usleep(wait_time);
    }

    /* Wait for the thumbnail to be generated. */
    pthread_mutex_lock(&sys->doneMutex);
    sys->state = THUMB_SEEKED;
    struct timespec deadline;
    clock_gettime(CLOCK_REALTIME, &deadline);
    deadline.tv_sec += 10; /* amount of seconds before we abort thumbnailer */
    do {
        int ret = pthread_cond_timedwait(&sys->doneCondVar, &sys->doneMutex, &deadline);
        if (ret == ETIMEDOUT)
            break;
    } while (sys->state != THUMB_DONE);
    pthread_mutex_unlock(&sys->doneMutex);

    /* Stop and release the media player. */
    libvlc_media_player_stop(mp);
    libvlc_media_player_release(mp);

    if (sys->state == THUMB_DONE) {
        /* Create the Java byte array to return the create thumbnail. */
        byteArray = (*env)->NewByteArray(env, frameSize);
        if (byteArray == NULL)
        {
            LOGE("Could not allocate the Java byte array to store the frame!");
            goto end;
        }

        (*env)->SetByteArrayRegion(env, byteArray, 0, frameSize,
                (jbyte *)sys->frameData);
    }

end:
    pthread_mutex_destroy(&sys->doneMutex);
    pthread_cond_destroy(&sys->doneCondVar);
    free(sys->frameData);
    free(sys->thumbData);
    free(sys);
enomem:
    return byteArray;
}
Exemple #20
0
int main(int argc, char *argv[]) {
    libvlc_instance_t *libvlc;
    libvlc_media_t *m;
    libvlc_media_player_t *mp;
    char const *vlc_argv[] = {
        "--no-audio", /* skip any audio track */
        "--no-xlib", /* tell VLC to not use Xlib */
        "--no-video-on-top",
        "--no-video-title-show",
    };
    int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);

    SDL_Surface *screen, *empty;
    SDL_Event event;
    SDL_Rect rect;
    int done = 0, action = 0, pause = 0, n = 0;

    struct ctx ctx;

    if(argc < 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        return EXIT_FAILURE;
    }

    /*
     *  Initialise libSDL
     */
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) == -1) {
        printf("cannot initialize SDL\n");
        return EXIT_FAILURE;
    }

    empty = SDL_CreateRGBSurface(SDL_SWSURFACE, VIDEOWIDTH, VIDEOHEIGHT,
                                 32, 0, 0, 0, 0);
    ctx.surf = SDL_CreateRGBSurface(SDL_SWSURFACE, VIDEOWIDTH, VIDEOHEIGHT,
                                    16, 0x001f, 0x07e0, 0xf800, 0);

    ctx.mutex = SDL_CreateMutex();

    int options = SDL_ANYFORMAT | SDL_HWSURFACE | SDL_DOUBLEBUF;

    screen = SDL_SetVideoMode(WIDTH, HEIGHT, 0, options);
    if(!screen) {
        printf("cannot set video mode\n");
        return EXIT_FAILURE;
    }

    /*
     *  Initialise libVLC
     */
    libvlc = libvlc_new(vlc_argc, vlc_argv);
    m = libvlc_media_new_path(libvlc, argv[1]);
    mp = libvlc_media_player_new_from_media(m);
    libvlc_media_release(m);

    libvlc_video_set_callbacks(mp, lock, unlock, display, &ctx);
    libvlc_video_set_format(mp, "RV16", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH*2);
    libvlc_media_player_play(mp);

    /*
     *  Main loop
     */
    rect.w = 0;
    rect.h = 0;

    while(!done) {
        action = 0;

        /* Keys: enter (fullscreen), space (pause), escape (quit) */
        while( SDL_PollEvent( &event ) ) {
            switch(event.type) {
            case SDL_QUIT:
                done = 1;
                break;
            case SDL_KEYDOWN:
                action = event.key.keysym.sym;
                break;
            }
        }

        switch(action) {
        case SDLK_ESCAPE:
            done = 1;
            break;
        case SDLK_RETURN:
            options ^= SDL_FULLSCREEN;
            screen = SDL_SetVideoMode(WIDTH, HEIGHT, 0, options);
            break;
        case ' ':
            pause = !pause;
            break;
        }

        //rect.x = (int)((1. + .5 * sin(0.03 * n)) * (WIDTH - VIDEOWIDTH) / 2);
        //rect.y = (int)((1. + .5 * cos(0.03 * n)) * (HEIGHT - VIDEOHEIGHT) / 2);
        rect.x = (int)(WIDTH - VIDEOWIDTH) / 2;
        rect.y = (int)(HEIGHT - VIDEOHEIGHT) / 2;

        if(!pause)
            n++;

        /* Blitting the surface does not prevent it from being locked and
         * written to by another thread, so we use this additional mutex. */
        SDL_LockMutex(ctx.mutex);
        SDL_BlitSurface(ctx.surf, NULL, screen, &rect);
        SDL_UnlockMutex(ctx.mutex);

        SDL_Flip(screen);
        SDL_Delay(10);

        SDL_BlitSurface(empty, NULL, screen, &rect);
    }

    /*
     * Stop stream and clean up libVLC
     */
    libvlc_media_player_stop(mp);
    libvlc_media_player_release(mp);
    libvlc_release(libvlc);

    /*
     * Close window and clean up libSDL
     */
    SDL_DestroyMutex(ctx.mutex);
    SDL_FreeSurface(ctx.surf);
    SDL_FreeSurface(empty);

    SDL_Quit();

    return 0;
}
VlcVideoWidget::VlcVideoWidget(const QList<QByteArray> &args) :
    QFrame(0),
    vlcInstance_(0),
    vlcPlayer_(0),
    vlcMedia_(0),
    hasVideoOut_(false)
{
    /// Convert the arguments into a proper form
    QVarLengthArray<const char*, 64> vlcArgs(args.size());
    for (int i = 0; i < args.size(); ++i)
        vlcArgs[i] = args.at(i).constData();

    // Create new libvlc instance
    vlcInstance_ = libvlc_new(vlcArgs.size(), vlcArgs.constData());

    // Check if instance is running
    if (!vlcInstance_)
    {
        std::string errorMsg;
        if (libvlc_errmsg())
            errorMsg = std::string("VlcVideoWidget: Failed to create VLC instance: ") + libvlc_errmsg();
        else
            errorMsg = "VlcVideoWidget: Failed to create VLC instance";
        LogError(errorMsg);
        return;
    }

    libvlc_set_user_agent(vlcInstance_, "realXtend Tundra Media Player 1.0", "Tundra/1.0");

    /// Create the vlc player and set event callbacks
    vlcPlayer_ = libvlc_media_player_new(vlcInstance_);
    libvlc_event_manager_t *em = libvlc_media_player_event_manager(vlcPlayer_);
    libvlc_event_attach(em, libvlc_MediaPlayerMediaChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerOpening, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerBuffering, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPlaying, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPaused, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerStopped, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerEncounteredError, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerTimeChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPositionChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerSeekableChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerPausableChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerTitleChanged, &VlcEventHandler, this);
    libvlc_event_attach(em, libvlc_MediaPlayerLengthChanged, &VlcEventHandler, this);

    /// register callbacks so that we can implement custom drawing of video frames
    libvlc_video_set_callbacks(
        vlcPlayer_,
        &CallBackLock,
        &CallBackUnlock,
        &CallBackDisplay,
        this);

    // Initialize rendering
    //idleLogo_ = QImage(":/images/vlc-cone.png");
    idleLogo_ = QImage(":/images/play-video.png");
    idleLogo_ = idleLogo_.convertToFormat(QImage::Format_ARGB32);

    //audioLogo_ = QImage(":/images/audio.png");
    audioLogo_ = QImage(":/images/play-audio.png");
    audioLogo_ = audioLogo_.convertToFormat(QImage::Format_ARGB32);
    
    pausePixmap_ = QPixmap(":/images/pause-big.png");
    bufferingPixmap_ = QPixmap(":/images/buffering.png");

    QSize startSize(600, 360);
    renderPixmap_ = QImage(startSize.width(), startSize.height(), QImage::Format_RGB32);
    libvlc_video_set_format(vlcPlayer_, "RV32", renderPixmap_.width(), renderPixmap_.height(), renderPixmap_.bytesPerLine());

    // Initialize widget properties
    setMinimumSize(startSize);
    resize(startSize);

    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setStyleSheet("background-color: black;");

    // Connect and start status poller
    connect(&pollTimer_, SIGNAL(timeout()), SLOT(StatusPoller()));
    pollTimer_.start(10);
}
Exemple #22
-1
VideoStream::VideoStream(const std::string& uri, irr::video::IVideoDriver* const videoDriver,
                         IrrIMGUI::IIMGUIHandle* const gui) :
    gui_{gui}
{
    videoTexture_ = videoDriver->createImage(irr::video::ECF_A8R8G8B8, irr::core::dimension2du(1280, 720));
    guiVideoTexture_ = gui_->createTexture(videoTexture_);

    char const *vlc_argv[] =
    {
        //        "-I", "dummy", // Don't use any interface
        //"--ignore-config", // Don't use VLC's config
        "--no-audio", /* skip any audio track */
        "--no-xlib", /* tell VLC to not use Xlib */
        "--network-caching=4000",
    };
    int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);

    vlcInstance_ = libvlc_new(vlc_argc, vlc_argv);
    auto vlcMedia = libvlc_media_new_location(vlcInstance_,
        "http://iphone-streaming.ustream.tv/uhls/17074538/streams/live/iphone/playlist.m3u8");
    vlcMediaPlayer_ = libvlc_media_player_new_from_media(vlcMedia);
    libvlc_media_release(vlcMedia);

    libvlc_video_set_callbacks(vlcMediaPlayer_,
                               VideoStream::preRenderCallback,
                               VideoStream::postRenderCallback,
                               VideoStream::displayCallback,
                               this);

    libvlc_video_set_format(vlcMediaPlayer_, "RV32", 1280, 720, videoTexture_->getPitch());
    libvlc_media_player_play(vlcMediaPlayer_);
}
Exemple #23
-1
int LibvlcCamera::PrimeCapture()
{
    Info("Priming capture from %s", mPath.c_str());
	 
    mLibvlcInstance = libvlc_new (0, NULL);
    if(mLibvlcInstance == NULL)
        Fatal("Unable to create libvlc instance due to: %s", libvlc_errmsg());
     
    mLibvlcMedia = libvlc_media_new_location(mLibvlcInstance, mPath.c_str());
    if(mLibvlcMedia == NULL)
        Fatal("Unable to open input %s due to: %s", mPath.c_str(), libvlc_errmsg());
	
    mLibvlcMediaPlayer = libvlc_media_player_new_from_media(mLibvlcMedia);
    if(mLibvlcMediaPlayer == NULL)
        Fatal("Unable to create player for %s due to: %s", mPath.c_str(), libvlc_errmsg());

	libvlc_video_set_format(mLibvlcMediaPlayer, mTargetChroma.c_str(), width, height, width * mBpp);
    libvlc_video_set_callbacks(mLibvlcMediaPlayer, &LibvlcLockBuffer, &LibvlcUnlockBuffer, NULL, &mLibvlcData);

    mLibvlcData.bufferSize = width * height * mBpp;
    // Libvlc wants 32 byte alignment for images (should in theory do this for all image lines)
    mLibvlcData.buffer = (uint8_t*)zm_mallocaligned(32, mLibvlcData.bufferSize);
    mLibvlcData.prevBuffer = (uint8_t*)zm_mallocaligned(32, mLibvlcData.bufferSize);
    
    mLibvlcData.newImage.setValueImmediate(false);

    libvlc_media_player_play(mLibvlcMediaPlayer);
    
    return(0);
}