Пример #1
0
VideoSource::~VideoSource()
{ 

    // media list and media list player
    libvlc_media_list_player_stop(mediaListPlayer);
    libvlc_media_list_player_release(mediaListPlayer);
    libvlc_media_list_release(mediaList);

    // media player
    libvlc_video_set_callbacks(mediaPlayer, nullptr, nullptr, nullptr, nullptr);
    libvlc_media_player_stop(mediaPlayer);
        

    delete audioOutputStreamHandler;
    audioOutputStreamHandler = nullptr;


    libvlc_media_player_release(mediaPlayer);

    if (pixelData) {
        free(pixelData);
        pixelData = nullptr;
    }

    if (texture) {
        delete texture;
        texture = nullptr;
    }

    delete config;
    config = nullptr;

    DeleteCriticalSection(&textureLock);
}
Пример #2
0
void VlcAbstractVideoStream::unsetCallbacks(VlcMediaPlayer *player)
{
    if (player) {
        libvlc_video_set_callbacks(player->core(), 0, 0, 0, 0);
        libvlc_video_set_format_callbacks(player->core(), 0, 0);
    }
}
Пример #3
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;
			}
		}
	}
}
Пример #4
0
    void
    VLC::load(const std::string & theFilename) {

        AC_DEBUG << "VLC::load('" << theFilename << "')";

        _EOF = false;
        _playTime = 0;
        
        std::vector<std::string> elements = asl::splitString(theFilename, "#");
        if (elements.size() == 2) {
            _playTime = as<asl::Unsigned64>(elements[1]);
            AC_DEBUG << "parsed playback position at " << _playTime << " milliseconds.";
        }
        
        _mediaURL = elements[0];
        libvlc_media_t *media = libvlc_media_new_location(_libvlc, _mediaURL.c_str());
        libvlc_media_player_set_media(_mediaPlayer, media);
        libvlc_media_release(media);

        libvlc_video_set_callbacks(_mediaPlayer, VLC::lock, VLC::unlock, VLC::display, this);
        _rasterEncoding = BGR;
        setPixelFormat(_rasterEncoding);
        libvlc_video_set_format_callbacks(_mediaPlayer, VLC::setup_video, VLC::cleanup_video);

        libvlc_media_player_play(_mediaPlayer);
        if (_playTime > 0) {
            libvlc_media_player_set_time(_mediaPlayer, _playTime);
        }
    }
Пример #5
0
void VideoDataOutput::addToMedia(libvlc_media_t *media)
{
    const int width = 300;
    const int height = width;
//    videoSizeChanged(width, height);
    libvlc_media_add_option_flag(media, ":vmem-chroma=RV24", libvlc_media_option_trusted);
    libvlc_video_set_callbacks(p_vlc_player, lock, unlock, 0, this);
}
Пример #6
0
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;
}
Пример #7
0
void VlcWindowlessBase::set_player_window() {
    libvlc_video_set_format_callbacks(getMD(),
                                      video_format_proxy,
                                      video_cleanup_proxy);
    libvlc_video_set_callbacks(getMD(),
                               video_lock_proxy,
                               video_unlock_proxy,
                               video_display_proxy,
                               this);
}
Пример #8
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();
 }
Пример #9
0
void VlcAbstractVideoStream::setCallbacks(VlcMediaPlayer *player)
{
    libvlc_video_set_callbacks(player->core(),
                               lockCallbackInternal,
                               unlockCallbackInternal,
                               displayCallbackInternal,
                               this);
    libvlc_video_set_format_callbacks(player->core(),
                                      formatCallbackInternal,
                                      formatCleanUpCallbackInternal);
}
Пример #10
0
void VideoMemoryStream::unsetCallbacks(VlcMediaPlayer *player)
{
    libvlc_video_set_callbacks(player->core(),
                               0,
                               0,
                               0,
                               0);
    libvlc_video_set_format_callbacks(player->core(),
                                      0,
                                      0);
}
Пример #11
0
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 );
}
Пример #12
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);
}
Пример #13
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);
}
Пример #14
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;
}
Пример #15
0
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;
    }
}
Пример #16
0
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
}
Пример #17
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;
}
Пример #18
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", // 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;
}
Пример #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!");
        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_from_media(p_obj->u.p_m);
    if (!mp)
        goto end;
    libvlc_media_player_set_video_title_display(mp, libvlc_position_disable, 0);

    sys->frameWidth = frameWidth;
    sys->frameHeight = frameHeight;
    /* Set the video format and the callbacks. */
    libvlc_video_set_callbacks(mp, thumbnailer_lock, thumbnailer_unlock,
                               thumbnailer_display, (void*)sys);
    libvlc_video_set_format_callbacks(mp, thumbnailer_setup, NULL);

    libvlc_event_attach(libvlc_media_player_event_manager(mp),
                        libvlc_MediaPlayerPositionChanged,
                        thumbnailer_event, sys);

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

    /* Wait for the thumbnail to be generated. */
    pthread_mutex_lock(&sys->doneMutex);
    struct timespec deadline;
    clock_gettime(CLOCK_REALTIME, &deadline);
    deadline.tv_sec += 3;

    /* Wait for a VOUT for 3 seconds, some input format like *.TS make some time
     * to initialize a VOUT */
    int ret = 0;
    while (!(sys->state & THUMB_VOUT) && ret != ETIMEDOUT)
        ret = pthread_cond_timedwait(&sys->doneCondVar, &sys->doneMutex, &deadline);

    if (sys->state & THUMB_VOUT)
    {
        ret = 0;
        /* Wait an additional 7 seconds for a frame */
        deadline.tv_sec += 7;
        while (!(sys->state & THUMB_DONE) && ret != ETIMEDOUT)
            ret = pthread_cond_timedwait(&sys->doneCondVar, &sys->doneMutex, &deadline);
    }
    else
        LOGE("media has not VOUT");
    pthread_mutex_unlock(&sys->doneMutex);

    /* Stop and release the media player. */
    libvlc_media_player_stop(mp);
    libvlc_event_detach(libvlc_media_player_event_manager(mp),
                        libvlc_MediaPlayerPositionChanged,
                        thumbnailer_event, sys);
    libvlc_media_player_release(mp);

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

        (*env)->SetByteArrayRegion(env, byteArray, 0, sys->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;
}
Пример #20
0
int Ibex::VLCVideoPlayer::playVLCVideo(const char *fileName, Display *dpy, GLXDrawable root) {
	if(mp != 0) {
		try {
			pixels = 0;
			done = true;

			// Stop stream and clean up libVLC.
			libvlc_media_player_stop(mp);
			libvlc_media_player_release(mp);
			mp = 0;
		} catch(...) {
			mp = 0;
		}
	}

    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 action = 0, pause = 0;
    context = new struct context();
    context->isStereo = isStereo;
    context->videoTexture = videoTexture;
    context->player = this;
    context->dpy = dpy;
    context->root = root;
    context->data = data;

    // create texture/mutex
    //setenv("VLC_PLUGIN_PATH", "/Applications/VLC.app/Contents/MacOS/plugins", 1);
    // 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.
	if(libvlc == 0) {
		libvlc = libvlc_new(vlc_argc, vlc_argv);
		if(NULL == libvlc) {
			printf("LibVLC initialization failure.\n");
			return EXIT_FAILURE;
		}
	}

    libvlc_media_t *m = libvlc_media_new_path(libvlc, fileName);
    mp = libvlc_media_player_new_from_media(m);
    libvlc_media_release(m);
	m = 0;

    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);
    libvlc_video_set_format_callbacks(mp,
                                           my_libvlc_video_format_cb,
                                           my_libvlc_video_cleanup_cb );

    
    if(libvlc_video_get_size(mp, 0, &width, & height) == 0) {
        VIDEOWIDTH = width;
        VIDEOHEIGHT = height;
    }
    context->mp = mp;
    
	done = false;
    libvlc_media_player_play(mp);

    // Main loop.
    while(!done) {
        action = 0;
        switch(action) {
			case 's':
				libvlc_media_player_stop(mp);
				break;
            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));
    }

    return 0;
}
Пример #21
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;
}
Пример #22
0
/**
 * 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;
}
Пример #23
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;
}
Пример #24
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;
}
Пример #25
0
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;
}
Пример #26
0
bool CVlcRtspSDK::StartPlay(int screenNum,char *name,HWND inhWnd,char *Rtspurl,int Direction)
{
	StopPlay();

	screenNo=screenNum;
	m_direction=Direction;

	hWnd=inhWnd;
	hDC   =   ::GetDC(hWnd); 
	pDc   =   CDC::FromHandle(hDC);   
	pDc->SetStretchBltMode(COLORONCOLOR);

	wchar_t wbuff[1024];
	char utf8[1024];
	MultiByteToWideChar(CP_ACP, 0, Rtspurl, -1, wbuff, 1024);  
	// buffLen = WideCharToMultiByte(CP_UTF8, 0, wbuff, -1, NULL, 0, 0, 0);  
	//  utf8 = new char[buffLen+1];  
	WideCharToMultiByte(CP_UTF8, 0, wbuff, -1, (LPSTR)utf8, 1024, 0, 0);  
	const char *p=NULL;

	// 判断rtsp地址是否可以连接
	// 使用url去创建一个CYuanRtspClient对象
#if !TEST_DEBUG
	CYuanRtspClient YuanRtsp(Rtspurl);
	ERTSPERROR eRet = YuanRtsp.InitSocket();
	if (eRet == E_RTSP_SUCCESS)
	{
		eRet = YuanRtsp.JudgeCorrect();
		if (eRet != E_RTSP_SUCCESS)
		{
			DlgMain->ShowCameraMessage(name,"RTSP连接失败 socket不通",FALSE);
			return false;
		}
	}
	else
	{
		DlgMain->ShowCameraMessage(name,"RTSP连接失败 socket不通",FALSE);
		return false;
	}
#endif


#if TEST_DEBUG
	m_pLibvlc_m =	libvlc_media_new_path(m_pLibvlc_Inst,utf8);
#else
	m_pLibvlc_m = libvlc_media_new_location(m_pLibvlc_Inst, utf8);
#endif

	//libvlc_media_new_path
	m_pLibvlc_Mp = libvlc_media_player_new_from_media(m_pLibvlc_m);

	libvlc_media_release(m_pLibvlc_m);

	//libvlc_media_player_set_hwnd(m_pLibvlc_Mp, hWnd);

	libvlc_video_set_callbacks(m_pLibvlc_Mp, Libvlc_Video_Lock_Callback, Libvlc_Video_UnLock_Callback,
		Libvlc_Video_Display_Callback, (void *)this);

	libvlc_video_set_format_callbacks(m_pLibvlc_Mp, Libvlc_Video_Format_Callback, Libvlc_Video_Cleanup_Callback);


	if(0==libvlc_media_player_play(m_pLibvlc_Mp)) 
	{	

		DlgMain->ShowCameraMessage(name,"连接成功",FALSE);
	}
	else
	{	

		DlgMain->ShowCameraMessage(name,"RTSP连接失败",FALSE);
		return false;
	}

	return true;
}
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;
}
Пример #28
0
void VideoSource::UpdateSettings()
{
    
    EnterCriticalSection(&textureLock);
    isRendering = false;
    LeaveCriticalSection(&textureLock);

    if (mediaPlayer) {
        libvlc_video_set_callbacks(mediaPlayer, nullptr, nullptr, nullptr, nullptr);
        libvlc_media_player_stop(mediaPlayer);
    }
    
    config->Reload();

    hasSetVolume = false;

    videoSize.x = float(config->width);
    videoSize.y = float(config->height);

    if (mediaPlayer == nullptr) {
        mediaPlayer = libvlc_media_player_new(vlc);
        libvlc_event_manager_t *em = libvlc_media_player_event_manager(mediaPlayer);
        libvlc_event_attach(em, libvlc_MediaPlayerEndReached, vlcEvent, this);
        libvlc_event_attach(em, libvlc_MediaPlayerPlaying, vlcEvent, this);
    }

    if (mediaListPlayer == nullptr) {
        mediaListPlayer = libvlc_media_list_player_new(vlc);
        libvlc_media_list_player_set_media_player(mediaListPlayer, mediaPlayer);
    } else {
        libvlc_media_list_player_stop(mediaListPlayer);
    }

    if (mediaList) {
        libvlc_media_list_lock(mediaList);
        while(libvlc_media_list_count(mediaList)) {
            libvlc_media_list_remove_index(mediaList, 0);
        }
        libvlc_media_list_unlock(mediaList);
    } else {
        mediaList = libvlc_media_list_new(vlc);
        libvlc_media_list_player_set_media_list(mediaListPlayer, mediaList);
    }

    

    char *utf8PathOrUrl;
    for(unsigned int i = 0; i < config->playlist.Num(); i++) {
        String &mediaEntry = config->playlist[i];
        String token = mediaEntry.GetToken(1, L':');
     
        // .. Yup.
        bool isStream = token.Length() >= 2 && token[0] == L'/' && token[1] == L'/';
        utf8PathOrUrl = config->playlist[i].CreateUTF8String();
        if (utf8PathOrUrl) {
            libvlc_media_t *media;
            if (!isStream) {
                media = libvlc_media_new_path(vlc, utf8PathOrUrl);
            } else {
                media = libvlc_media_new_location(vlc, utf8PathOrUrl);
            }
            
            libvlc_media_list_lock(mediaList);
            libvlc_media_list_add_media(mediaList, media);
            libvlc_media_list_unlock(mediaList);

            libvlc_media_release(media);
            Free(utf8PathOrUrl);
        }
    }

    if (!config->isPlaylistLooping) {
        remainingVideos = config->playlist.Num();
    }

    libvlc_video_set_callbacks(mediaPlayer, lock, unlock, display, this);
    libvlc_video_set_format_callbacks(mediaPlayer, videoFormatProxy, videoCleanupProxy);

    libvlc_media_list_player_set_playback_mode(mediaListPlayer, config->isPlaylistLooping ? libvlc_playback_mode_loop : libvlc_playback_mode_default);
    

    if (!audioOutputStreamHandler) {
        audioOutputStreamHandler = new AudioOutputStreamHandler(vlc, mediaPlayer);
    }

    audioOutputStreamHandler->SetOutputParameters(
        config->audioOutputType, 
        config->audioOutputTypeDevice,
        config->audioOutputDevice, 
        config->isAudioOutputToStream);
    
    audioOutputStreamHandler->SetVolume(config->volume);
    
    // set (possibly in vane) the volume.  If it doesn't work it will try later until it works
    // vlc... que pasa amigo
    hasSetVolume = libvlc_audio_set_volume(mediaPlayer, config->volume) == 0;
    
    EnterCriticalSection(&textureLock);
    isRendering = true;
    LeaveCriticalSection(&textureLock);

    libvlc_media_list_player_play(mediaListPlayer);
    
}
Пример #29
-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);
}
Пример #30
-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_);
}