Ejemplo n.º 1
0
        private void Record(string source, string directory, string pattern)
        {
            var filename = Path.Combine(directory, string.Format(pattern, DateTime.Now.ToString("yyyyMMddHHmmss")));

            var opts   = $":sout=#std{{access=file,dst='{filename}'}}";
            var player = new VlcMediaPlayer(new DirectoryInfo(ConfigurationManager.AppSettings["VlcDirectory"]), new[] { "--rtsp-tcp" });

            player.SetMedia(source, opts);
            player.EncounteredError += (sender, eventArgs) =>
            {
                player.Dispose();
                Upload(filename);
            };
            player.Play();
            var recordTimer = new Timer((duration + 2) * 1000);

            recordTimer.AutoReset = false;
            recordTimer.Elapsed  += (sender, eventArgs) =>
            {
                player.Stop();
                player.Dispose();
                recordTimer.Dispose();
                Console.WriteLine($"recorded {filename}");
                Upload(filename);
            };
            Console.WriteLine($"start recording to {filename}");
            recordTimer.Start();
        }
Ejemplo n.º 2
0
        private void VlcMediaPlayerMediaStateChanged(object sender, MediaStateChangedEventArgs e)
        {
            if (_disposing || _isStopping)
            {
                return;
            }

            Debug.WriteLine($"StateChanged : {e.State}");

            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { StateChanged?.Invoke(this, e); }));

            if (e.State == MediaState.Ended)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    switch (EndBehavior)
                    {
                    case EndBehavior.Nothing:

                        break;

                    case EndBehavior.Stop:
                        Stop();
                        break;

                    case EndBehavior.Repeat:
                        StopInternal();
                        VlcMediaPlayer.Play();
                        break;
                    }
                }));
            }
        }
Ejemplo n.º 3
0
        public async Task <VideoAudioInfo> Execute(Stream thumbnailStream)
        {
            ThumbnailStream = thumbnailStream;
            LibVlcManager.LoadLibVlc(AppDomain.CurrentDomain.BaseDirectory + @"..\..\libvlc");
            Vlc vlc = new Vlc(new[] { "-I", "dummy", "--ignore-config", "--no-video-title" });

            Console.WriteLine($"LibVlcManager: {LibVlcManager.GetVersion()}s");
            mediaPlayer = vlc.CreateMediaPlayer();
            mediaPlayer.SetVideoDecodeCallback(LockCB, unLockCB, DisplayCB, IntPtr.Zero);
            mediaPlayer.SetVideoFormatCallback(VideoFormatCallback, VideoCleanupCallback);
            mediaPlayer.Playing += MediaPlayer_Playing;
            mediaPlayer.Media    = vlc.CreateMediaFromLocation(FilePath);

            await Task.Run(() =>
            {
                mediaPlayer.Play();
                mediaPlayer.IsMute = true;
                Stopwatch s        = new Stopwatch();
                s.Start();
                while (waiting)
                {
                    Thread.Sleep(100);
                }
                s.Stop();
                TimeSpan sec = new TimeSpan(s.ElapsedTicks);
                Console.WriteLine(sec.ToString());
                mediaPlayer.Dispose();
                vlc.Dispose();
            });

            _VideoAudioInfo.Resolution = JsonConvert.SerializeObject(_VideoResolution);
            //_VideoAudioInfo.Thumbnail = ThumbnailStream;
            return(_VideoAudioInfo);
        }
Ejemplo n.º 4
0
        private void TryToCreateClient()
        {
            if (myHandle == IntPtr.Zero)
                return;

            string path = string.IsNullOrEmpty(myVlcLibPath) ? AppDomain.CurrentDomain.BaseDirectory : myVlcLibPath;
            if (!File.Exists(Path.Combine(path, "libvlc.dll")) || !File.Exists(Path.Combine(path, "libvlccore.dll")))
                return;
            myClient = new VideoLanClient(path);
            myClient.PluginPath = Path.Combine(path, "plugins");
            myPlayer = myClient.CreateMediaPlayer(myHandle);
            myPlayer.Audio.Volume = Volume;
            myPlayer.Audio.Mute = Mute;
            //todo
            //myPlayer.PositionChanged +=
            //    delegate(object sender, VlcPositionChangedEventArgs e)
            //    {
            //        Position = e.Position;
            //    };
            myPlayer.StateChanged +=
                delegate(object sender, VlcStateChangedEventArgs e)
                {
                    if (e.NewState == VlcState.Ended)
                    {
                        Position = 0;
                    }
                };
        }
Ejemplo n.º 5
0
        private static void Main(string[] args)
        {
            var file = new FileInfo(@"path");

            var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);

            // Default installation path of VideoLAN.LibVLC.Windows
            var libDirectory =
                new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));

            using (var mediaPlayer = new VlcMediaPlayer(libDirectory))
            {
                // Options without any encode
                var mediaOptions = new[]
                {
                    ":sout=#rtp{sdp=rtsp://192.168.1.162:8008/test}",
                    ":sout-keep"
                };

                mediaPlayer.SetMedia(file, mediaOptions);

                mediaPlayer.Play();

                Console.WriteLine("Streaming on rtsp://192.168.1.162:8008/test");
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
Ejemplo n.º 6
0
        private void VlcMediaPlayerEndReached(object sender, ObjectEventArgs <MediaState> e)
        {
            if (_disposing || _isStopping)
            {
                return;
            }

            Dispatcher.BeginInvoke(new Action(() =>
            {
                switch (EndBehavior)
                {
                case EndBehavior.Nothing:

                    break;

                case EndBehavior.Stop:
                    Stop();
                    break;

                case EndBehavior.Repeat:
                    StopInternal();
                    VlcMediaPlayer.Play();
                    break;
                }

                _isPublished = false;
                if (Win32Api.SetThreadExecutionState(Win32Api.ES_CONTINUOUS) == null)
                {
                    // try XP variant as well just to make sure
                    Win32Api.SetThreadExecutionState(Win32Api.ES_CONTINUOUS);
                }
            }));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Class describing a video file, manipulated using VLC libraries
        /// </summary>
        /// <param name="fileName"></param>
        public Video(string fileName)
        {
            FileInfo file        = new FileInfo(fileName);
            bool     initialized = false;

            if (!VideoTools.checkVlcLib())
            {
                throw new Exception("Cannot find the VLC library... Please make sure you're running this application from inside your PinUp folder...");
            }
            try
            {
                VlcMediaPlayer mediaPlayer = new VlcMediaPlayer(VideoTools.GetLibVlcLocation(), VideoTools.GetVlcOptionsHeadless(0));
                initialized = true;
                mediaPlayer.SetMedia(file);
                mediaPlayer.GetMedia().Parse();
                this.Duration = mediaPlayer.GetMedia().Duration.TotalSeconds;
                this.Width    = (int)mediaPlayer.GetMedia().TracksInformations[0].Video.Width;
                this.Height   = (int)mediaPlayer.GetMedia().TracksInformations[0].Video.Height;
                this.FileName = fileName;
                mediaPlayer.Dispose();
            }
            catch (Exception exc)
            {
                if (!initialized)
                {
                    throw (new Exception("Cannot initialize VLC player library: " + exc.Message));
                }
                else
                {
                    throw (new Exception("VLC library error: " + exc.Message));
                }
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 ///     Toggle mute mode.
 /// </summary>
 public void ToggleMute()
 {
     if (VlcMediaPlayer != null)
     {
         VlcMediaPlayer.ToggleMute();
     }
 }
Ejemplo n.º 9
0
        private void VlcMediaPlayerEndReached(object sender, ObjectEventArgs <MediaState> e)
        {
            if (_disposing || _isStopping)
            {
                return;
            }

            Dispatcher.BeginInvoke(new Action(() =>
            {
                switch (EndBehavior)
                {
                case EndBehavior.Nothing:

                    break;

                case EndBehavior.Stop:
                    Stop();
                    break;

                case EndBehavior.Repeat:
                    StopInternal();
                    VlcMediaPlayer.Play();
                    break;
                }
            }));
        }
Ejemplo n.º 10
0
 /// <summary>
 ///     Show next frame.
 /// </summary>
 public void NextFrame()
 {
     if (VlcMediaPlayer != null)
     {
         VlcMediaPlayer.NextFrame();
     }
 }
Ejemplo n.º 11
0
        public void EndInit()
        {
            if (IsInDesignMode() || myVlcMediaPlayer != null)
            {
                return;
            }
            if (VlcLibDirectory == null && (VlcLibDirectory = OnVlcLibDirectoryNeeded()) == null)
            {
                throw new Exception("'VlcLibDirectory' must be set.");
            }

            if (VlcMediaplayerOptions == null)
            {
                myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory);
            }
            else
            {
                myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory, VlcMediaplayerOptions);
            }

            if (log != null)
            {
                RegisterLogging();
            }
            myVlcMediaPlayer.VideoHostControlHandle = Handle;

            RegisterEvents();
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Replay media.
        /// </summary>
        public void Replay()
        {
            ThrowIfNotInitialize();

            StopInternal();
            VlcMediaPlayer.Play();
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     Cleanup the player used resource.
        /// </summary>
        /// <param name="disposing"></param>
        protected void Dispose(bool disposing)
        {
            if (_disposed || _disposing)
            {
                return;
            }

            _disposing = true;

            Stop();

            if (VlcMediaPlayer != null)
            {
                VlcMediaPlayer.Media?.Dispose();
                VlcMediaPlayer.Dispose();
                VlcMediaPlayer = null;
            }

            _lockCallbackHandle.Free();
            _unlockCallbackHandle.Free();
            _displayCallbackHandle.Free();
            _formatCallbackHandle.Free();
            _cleanupCallbackHandle.Free();
            //_audioSetupCallbackHandle.Free();
            //_audioCleanupCallbackHandle.Free();
            //_audioPlayCallbackHandle.Free();
            //_audioPauseCallbackHandle.Free();
            //_audioResumeCallbackHandle.Free();
            //_audioFlushCallbackHandle.Free();
            //_audioDrainCallbackHandle.Free();
            //_audioSetVolumeCallbackHandle.Free();

            _disposed  = true;
            _disposing = false;
        }
Ejemplo n.º 14
0
        public void AlarmActivated( )
        {
            IsHandlerBusy = true;
            _sleepFor     = _recordForSeconds;
            var saveTo = new FileInfo(Path.Combine(_videoDumpDirectory, $"{DateTime.Now.ToFileDateTime()}.mpg"));

            if (!Directory.Exists(saveTo.DirectoryName))
            {
                Directory.CreateDirectory(saveTo.DirectoryName);
            }


            var player = new VlcMediaPlayer(new System.IO.DirectoryInfo(_settings.VlcFolder));

            player.SetMedia(_camera.RtspSource, $":sout=#transcode{{acodec=mp3}}:duplicate{{dst=std{{access=file,mux=ts,dst=\'{saveTo.FullName}\'}}}}");
            player.EncounteredError += PlayerEncounteredError;
            _logger.Write(LogEventLevel.Information, $"Saving video to {saveTo.FullName} for {_recordForSeconds} ");
            player.Play();
            while (_sleepFor > 0)
            {
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
                _sleepFor--;
            }

            _logger.Write(LogEventLevel.Information, $"Stopping log write to {saveTo.FullName}");
            player.Stop();
            IsHandlerBusy = false;
        }
Ejemplo n.º 15
0
        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);

            if (_isDVD && (VlcMediaPlayer != null) && State == MediaState.Playing &&
                (LibVlcManager.LibVlcVersion.DevString == "Meta"))
            {
                switch (e.ChangedButton)
                {
                case MouseButton.Left:
                    VlcMediaPlayer.SetMouseDown(0, Interop.MediaPlayer.MouseButton.Left);
                    break;

                case MouseButton.Right:
                    VlcMediaPlayer.SetMouseDown(0, Interop.MediaPlayer.MouseButton.Right);
                    break;

                case MouseButton.Middle:
                case MouseButton.XButton1:
                case MouseButton.XButton2:
                default:
                    VlcMediaPlayer.SetMouseDown(0, Interop.MediaPlayer.MouseButton.Other);
                    break;
                }
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 ///     Inactive with DVD menu.
 /// </summary>
 /// <param name="mode"></param>
 public void Navigate(NavigateMode mode)
 {
     if (VlcMediaPlayer != null)
     {
         VlcMediaPlayer.Navigate(mode);
     }
 }
 public void IsStoppedTest()
 {
     player = instance.CreatePlayer(BaseTestFilePath + "n900_extremely_short.avi");
     player.Play();
     player.Stop();
     Assert.IsTrue(player.IsStopped);
 }
Ejemplo n.º 18
0
        public PlayerVlcService()
        {
            var currentAssembly = Assembly.GetEntryAssembly();

            try
            {
                if (currentAssembly != null)
                {
                    var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
                    if (currentDirectory == null)
                    {
                        return;
                    }

                    var vlcLibDirectory = new DirectoryInfo(Path.Combine(currentDirectory, @"lib\x86"));

                    _vlcMediaPlayer = new VlcMediaPlayer(vlcLibDirectory);
                }
                else
                {
                    throw new FileNotFoundException(Localization.strings.PlayerEngineNotFound);
                }
            }
            catch (Exception e)
            {
                LoggerFacade.WriteError(Localization.strings.PlayerNotLoaded, e, isShow: true);
            }

            _vlcMediaPlayer.EndReached      += VlcMediaPlayer_OnEndReached;
            _vlcMediaPlayer.PositionChanged += VlcMediaPlayer_OnPositionChanged;
            _vlcMediaPlayer.LengthChanged   += VlcMediaPlayer_OnLengthChanged;
            _vlcMediaPlayer.Stopped         += VlcMediaPlayer_OnStopped;
            _vlcMediaPlayer.Paused          += VlcMediaPlayer_OnPaused;
            _vlcMediaPlayer.Playing         += VlcMediaPlayer_OnPlaying;
        }
Ejemplo n.º 19
0
 /// <summary>
 ///     Pause or resume media.
 /// </summary>
 public void PauseOrResume()
 {
     if (VlcMediaPlayer != null)
     {
         VlcMediaPlayer.PauseOrResume();
     }
 }
Ejemplo n.º 20
0
        public PlayerVLCService(bool isDebugEnabled = false)
        {
            Assembly currentAssembly  = Assembly.GetEntryAssembly();
            string   currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;

            if (currentDirectory == null)
            {
                return;
            }

            DirectoryInfo vlcLibDirectory;

            if (IntPtr.Size == 4)
            {
                vlcLibDirectory = new DirectoryInfo(Path.Combine(currentDirectory, @"libvlc\win-x86\"));
            }
            else
            {
                vlcLibDirectory = new DirectoryInfo(Path.Combine(currentDirectory, @"libvlc\win-x64\"));
            }

            string[] vlcOptions = InitVlcOptions(isDebugEnabled);

            DestinationFolder = Path.Combine(currentDirectory, "streams");

            if (!Directory.Exists(DestinationFolder))
            {
                Directory.CreateDirectory(DestinationFolder);
            }

            _vlcMediaPlayer = new VlcMediaPlayer(vlcLibDirectory, vlcOptions);

            InitEventHandlers();
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Cleanup the player used resource.
        /// </summary>
        /// <param name="disposing"></param>
        protected void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            BeginStop(() =>
            {
                if (VlcMediaPlayer != null)
                {
                    if (VlcMediaPlayer.Media != null)
                    {
                        VlcMediaPlayer.Media.Dispose();
                    }
                    VlcMediaPlayer.Dispose();
                }

                _lockCallbackHandle.Free();
                _unlockCallbackHandle.Free();
                _displayCallbackHandle.Free();
                _formatCallbackHandle.Free();
                _cleanupCallbackHandle.Free();
                //_audioSetupCallbackHandle.Free();
                //_audioCleanupCallbackHandle.Free();
                //_audioPlayCallbackHandle.Free();
                //_audioPauseCallbackHandle.Free();
                //_audioResumeCallbackHandle.Free();
                //_audioFlushCallbackHandle.Free();
                //_audioDrainCallbackHandle.Free();
                //_audioSetVolumeCallbackHandle.Free();

                _disposed = true;
            });
        }
        public void VlcMediaPlayerConstructorTest()
        {
            VlcInstance    instance = new VlcInstance(VlcInstanceArgs);
            VlcMediaPlayer player   = instance.CreatePlayer(BaseTestFilePath + "n900_extremely_short.avi");

            Assert.IsInstanceOfType(player, typeof(VlcMediaPlayer));
            Assert.IsInstanceOfType(player.Media, typeof(VlcMedia));
        }
        public void VolumeTest()
        {
            player = instance.CreatePlayer(BaseTestFilePath + "n900_extremely_short.avi");
            player.Play();
            int currentVolume = player.Volume;

            player.Volume = currentVolume + 10;
            Assert.IsTrue(currentVolume < player.Volume);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///     Pause or resume media.
        /// </summary>
        public void PauseOrResume()
        {
            if (VlcMediaPlayer == null)
            {
                return;
            }

            VlcMediaPlayer.PauseOrResume();
        }
Ejemplo n.º 25
0
        /// <summary>
        ///     Resume media.
        /// </summary>
        public void Resume()
        {
            if (VlcMediaPlayer == null)
            {
                return;
            }

            VlcMediaPlayer.Resume();
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Get the current audio output device identifier.
        /// </summary>
        public string GetAudioDevice()
        {
            if (VlcMediaPlayer == null)
            {
                throw new InvalidOperationException("VlcMediaPlayer doesn't have initialize.");
            }

            return(VlcMediaPlayer.GetAudioDevice());
        }
Ejemplo n.º 27
0
        /// <summary>
        ///     Gets the list of available audio output modules.
        /// </summary>
        /// <returns></returns>
        public AudioOutputList GetAudioOutputList()
        {
            if (VlcMediaPlayer == null)
            {
                throw new InvalidOperationException("VlcMediaPlayer doesn't have initialize.");
            }

            return(VlcMediaPlayer.GetAudioOutputList());
        }
Ejemplo n.º 28
0
 public void Dispose()
 {
     if (Player != null)
     {
         Stop();
         Player.Dispose();
         Player = null;
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        ///     Configures an explicit audio output device. If the module paramater is NULL,
        ///     audio output will be moved to the device specified by the device identifier string immediately.
        ///     This is the recommended usage. A list of adequate potential device strings can be obtained with
        ///     <see cref="EnumAudioDeviceList" />.
        ///     However passing NULL is supported in LibVLC version 2.2.0 and later only; in earlier versions, this function would
        ///     have no effects when the module parameter was NULL.
        ///     If the module parameter is not NULL, the device parameter of the corresponding audio output, if it exists, will be
        ///     set to the specified string.
        ///     Note that some audio output modules do not have such a parameter (notably MMDevice and PulseAudio).
        ///     A list of adequate potential device strings can be obtained with <see cref="GetAudioDeviceList" />.
        /// </summary>
        public void SetAudioDevice(AudioOutput audioOutput, AudioDevice audioDevice)
        {
            if (VlcMediaPlayer == null)
            {
                throw new InvalidOperationException("VlcMediaPlayer doesn't have initialize.");
            }

            VlcMediaPlayer.SetAudioDevice(audioOutput, audioDevice);
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     Gets a list of potential audio output devices.
        /// </summary>
        /// <returns></returns>
        public AudioDeviceList EnumAudioDeviceList()
        {
            if (VlcMediaPlayer == null)
            {
                throw new InvalidOperationException("VlcMediaPlayer doesn't have initialize.");
            }

            return(VlcMediaPlayer.EnumAudioDeviceList());
        }
Ejemplo n.º 31
0
        /// <summary>
        ///     Selects an audio output module.
        ///     Any change will take be effect only after playback is stopped and restarted. Audio output cannot be changed while
        ///     playing.
        /// </summary>
        /// <param name="audioOutput"></param>
        /// <returns></returns>
        public bool SetAudioOutput(AudioOutput audioOutput)
        {
            if (VlcMediaPlayer == null)
            {
                throw new InvalidOperationException("VlcMediaPlayer doesn't have initialize.");
            }

            return(VlcMediaPlayer.SetAudioOutput(audioOutput));
        }
Ejemplo n.º 32
0
        private void PlaySong(Song song)
        {
            // If the song is null there is nothing to play
            if (song == null)
            {
                if (PlaylistEnded != null)
                    PlaylistEnded();
                return;
            }

            // As soon as we are trying to play any song we are moving forward again.
            playbackDirection = TP_PLAYBACKDIRECTION.Forward;

            string temp = FindAudiofile(song);
            if (temp == "" || temp == null)
            {
                throw new Exception("Zu diesem Song wurde kein Audiofile gefunden.");
            }
            else if (System.IO.File.Exists(temp))
            {
                Stop();

                // This is the point where the song is actually played for real.
                //IMedia media = factory.CreateMedia<IMedia>(temp);
                //factory.CreatePlayer<IAudioPlayer>().Open(media);
                VlcMedia media = new VlcMedia(instance, temp);
                CurrentSong = song;
                if (vlc == null)
                    vlc = new VlcMediaPlayer(media);
                else
                    vlc.Media = media;
                vlc.Play();
                PlaybackState = TP_PLAYBACKSTATE.Playing;
                // If we are not already navigating, log the song to the navigation history so it is available in case the user starts skipping
                if (playbackMode == TP_PLAYBACKMODE.Playlist)
                {
                    totalHistory.Add(song);
                    historyPosition++;
                }
            }
            else
            {
                //TODO: Automatically re-scan
                throw new System.IO.FileNotFoundException("Die Datei des abzuspielenden Songs wurde nicht gefunden. Möglicherweise muss die Bibliothek aktualisiert werden.", temp);
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <b>VlcTitles</b> class.
 /// </summary>
 /// <param name="Player"></param>
 internal VlcTitles(VlcMediaPlayer Player)
 {
     _Player = Player;
     _Tracks = new Dictionary<int, VlcTrack>();
 }
Ejemplo n.º 34
-1
        public Player()
        {
            // Initialization (TODO: Make all the stuff configurable, of course)
            Playlist = new Playlist();
            PlayedHistory = new List<Song>();
            totalHistory = new List<Song>();
            Queue = new List<Song>();
            RandomSettings = new PlayerRandomSettings(100, true);
            PlaybackState = TP_PLAYBACKSTATE.Stopped;
            playbackMode = TP_PLAYBACKMODE.Playlist;
            playbackDirection = TP_PLAYBACKDIRECTION.Forward;
            PlaybackLoggingMode = TP_PLAYBACKLOG.After80Percent;
            historyPosition = -1;

            // VLC Initialization
            string[] args = new string[] {
                "--ignore-config",
                @"--plugin-path=C:\Program Files (x86)\VideoLAN\VLC\plugins",
                //,"--vout-filter=deinterlace", "--deinterlace-mode=blend"
            };

            instance = new VlcInstance(args);
            vlc = null;
            factory = new MediaPlayerFactory();
            /*vlc = factory.CreatePlayer<IVideoPlayer>();
            vlc.Events.MediaEnded += new EventHandler(Events_MediaEnded);
            vlc.Events.TimeChanged += new EventHandler<Declarations.Events.MediaPlayerTimeChanged>(Events_TimeChanged);
            vlc.Events.PlayerPlaying += new EventHandler(Events_PlayerPlaying);*/
        }