Example #1
0
        public void InitializeVideoRecorder()
        {
            if (captureSource == null)
            {
                // Create the VideoRecorder objects.
                captureSource      = new CaptureSource();
                fileSink           = new FileSink();
                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                captureSource.CaptureImageCompleted += captureSource_CaptureImageCompleted;
                // Add eventhandlers for captureSource.
                captureSource.CaptureFailed += new EventHandler <ExceptionRoutedEventArgs>(OnCaptureFailed);
                // Initialize the camera if it exists on the device.
                if (videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);

                    // Display the viewfinder image on the rectangle.
                    viewfinderRectangle.Fill = videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    captureSource.Start();

                    // Set the button state and the message.
                    UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
                }
                else
                {
                    // Disable buttons when the camera is not supported by the device.
                    UpdateUI(ButtonState.CameraNotSupported, "A camera is not supported on this device.");
                }
            }
        }
Example #2
0
        void InitializeVideoRecorder(Rectangle viewfinderRectangle)
        {
            if (captureSource == null)
              {
            // Create the VideoRecorder objects.
            captureSource = new CaptureSource();
            fileSink = new FileSink();

            videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

            // Add eventhandlers for captureSource.
            captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);

            // Initialize the camera if it exists on the device.
            if (videoCaptureDevice != null)
            {
              // Create the VideoBrush for the viewfinder.
              videoRecorderBrush = new VideoBrush();
              videoRecorderBrush.SetSource(captureSource);

              // Display the viewfinder image on the rectangle.
              viewfinderRectangle.Fill = videoRecorderBrush;

              // Start video capture and display it on the viewfinder.
              captureSource.Start();
            }
            else
            {
              // A camera is not supported on this device
            }
              }
        }
Example #3
0
        public JLogger Build()
        {
            EnsureDirectory(Path.GetDirectoryName(Configuration.FilePath));

            var   fileController = new FileController(Configuration.FilePath);
            ISink sink           = new FileSink(fileController);

            if (Configuration.FileSplitting)
            {
                sink = new BundleSink(
                    sink,
                    new SplitterSink(fileController, Configuration.SplittingDirectory, Configuration.MaxFileSize)
                    );
                EnsureDirectory(Configuration.SplittingDirectory);
            }

            if (Configuration.MinimumLogLevel > LogLevel.Trace || Configuration.MaximumLogLevel < LogLevel.Fatal)
            {
                sink = new FilterSink(sink, Configuration.MinimumLogLevel, Configuration.MaximumLogLevel);
            }

            if (Configuration.Backtrackng)
            {
                sink = new BundleSink(
                    sink,
                    new BacktrackSink(new FileSink(fileController), Configuration.MinimumLevelForBacktracking, Configuration.TriggeringLevelForBacktracking, Configuration.BacktrackingTime)
                    );
            }

            return(new JLogger(sink, new EntryFormatter(new DataFormatter())));
        }
Example #4
0
        public static void OnOpenedLifecycleHookCanWriteFileHeader()
        {
            using (var tmp = TempFolder.ForCaller())
            {
                var headerWriter = new FileHeaderWriter("This is the file header");

                var path = tmp.AllocateFilename("txt");
                using (new FileSink(path, new JsonFormatter(), null, new UTF8Encoding(false), false, headerWriter))
                {
                    // Open and write header
                }

                using (var sink = new FileSink(path, new JsonFormatter(), null, new UTF8Encoding(false), false, headerWriter))
                {
                    // Length check should prevent duplicate header here
                    sink.Emit(Some.LogEvent());
                }

                var lines = System.IO.File.ReadAllLines(path);

                Assert.Equal(2, lines.Length);
                Assert.Equal(headerWriter.Header, lines[0]);
                Assert.Equal('{', lines[1][0]);
            }
        }
Example #5
0
        public void start()
        {
            if (captureSource == null)
            {
                // Create the VideoRecorder objects.
                captureSource = new CaptureSource();
                fileSink = new FileSink();

                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                // Add eventhandlers for captureSource.
                captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);

                // Initialize the camera if it exists on the device.
                if (videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);
                    videoRecorderBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
                    viewfinderRectangle.Fill = videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    captureSource.Start();
                    System.Diagnostics.Debug.WriteLine("Started");
                    _isRunning = true;
                }

            }
        }
Example #6
0
    static OtelLogging()
    {
        ISink sink = null;

        try
        {
            var logDirectory = GetLogDirectory();
            if (logDirectory != null)
            {
                var fileName = GetLogFileName();
                var logPath  = Path.Combine(logDirectory, fileName);
                sink = new FileSink(logPath);
            }
        }
        catch (Exception)
        {
            // unable to configure logging to a file
        }

        if (sink == null)
        {
            sink = new NoopSink();
        }

        Logger = new Logger(sink);
    }
Example #7
0
        public VideoService(
            Rectangle viewFinder,
            MediaElement player
            )
        {
            // Initial State
            _State = PlayState.Paused;
            _CanRecord = false;

            _Record = new SwitchableCommand(OnRecord);
            _Play = new SwitchableCommand(OnPlay);
            _Stop = new SwitchableCommand(OnPause);

            _ViewFinder = viewFinder;

            _Player = player;
            _Player.MediaEnded += MediaEnded;

            _CaptureSource = new CaptureSource();
            _CaptureSource.CaptureFailed += CaptureFailed;

            _FileSink = new FileSink();
            _Brush = new VideoBrush();

            _HasRecording = new BehaviorSubject<bool>(false);
        }
Example #8
0
        static void WriteTwoEventsAndCheckOutputFileLength(long?maxBytes, Encoding encoding)
        {
            using (var tmp = TempFolder.ForCaller())
            {
                var path = tmp.AllocateFilename("txt");
                var evt  = Some.LogEvent("Irrelevant as it will be replaced by the formatter");
                var actualEventOutput = "x";
                var formatter         = new FixedOutputFormatter(actualEventOutput);
                var eventOuputLength  = encoding.GetByteCount(actualEventOutput);

                using (var sink = new FileSink(path, formatter, maxBytes, encoding: encoding))
                {
                    sink.Emit(evt);
                }
                var size = new FileInfo(path).Length;
                Assert.Equal(encoding.GetPreamble().Length + eventOuputLength, size);

                //write a second event to the same file
                using (var sink = new FileSink(path, formatter, maxBytes, encoding: encoding))
                {
                    sink.Emit(evt);
                }

                size = new FileInfo(path).Length;
                Assert.Equal(encoding.GetPreamble().Length + eventOuputLength * 2, size);
            }
        }
Example #9
0
        public void OnOpenedLifecycleHookCanWrapUnderlyingStream()
        {
            var gzipWrapper = new GZipHooks();

            using (var tmp = TempFolder.ForCaller())
            {
                var path = tmp.AllocateFilename("txt");
                var evt  = Some.LogEvent("Hello, world!");

                using (var sink = new FileSink(path, new JsonFormatter(), null, null, false, gzipWrapper))
                {
                    sink.Emit(evt);
                    sink.Emit(evt);
                }

                // Ensure the data was written through the wrapping GZipStream, by decompressing and comparing against
                // what we wrote
                List <string> lines;
                using (var textStream = new MemoryStream())
                {
                    using (var fs = System.IO.File.OpenRead(path))
                        using (var decompressStream = new GZipStream(fs, CompressionMode.Decompress))
                        {
                            decompressStream.CopyTo(textStream);
                        }

                    textStream.Position = 0;
                    lines = textStream.ReadAllLines();
                }

                Assert.Equal(2, lines.Count);
                Assert.Contains("Hello, world!", lines[0]);
            }
        }
Example #10
0
        void InitializeVideoRecorder(Rectangle viewfinderRectangle)
        {
            if (captureSource == null)
            {
                // Create the VideoRecorder objects.
                captureSource = new CaptureSource();
                fileSink      = new FileSink();

                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                // Add eventhandlers for captureSource.
                captureSource.CaptureFailed += new EventHandler <ExceptionRoutedEventArgs>(OnCaptureFailed);

                // Initialize the camera if it exists on the device.
                if (videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);

                    // Display the viewfinder image on the rectangle.
                    viewfinderRectangle.Fill = videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    captureSource.Start();
                }
                else
                {
                    // A camera is not supported on this device
                }
            }
        }
Example #11
0
        public void start()
        {
            if (captureSource == null)
            {
                // Create the VideoRecorder objects.
                captureSource = new CaptureSource();
                fileSink      = new FileSink();

                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                // Add eventhandlers for captureSource.
                captureSource.CaptureFailed += new EventHandler <ExceptionRoutedEventArgs>(OnCaptureFailed);

                // Initialize the camera if it exists on the device.
                if (videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);
                    videoRecorderBrush.RelativeTransform = new CompositeTransform()
                    {
                        CenterX = 0.5, CenterY = 0.5, Rotation = 90
                    };
                    viewfinderRectangle.Fill = videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    captureSource.Start();
                    System.Diagnostics.Debug.WriteLine("Started");
                    _isRunning = true;
                }
            }
        }
Example #12
0
        public void Can_Create_New_File_When_Midnight_Is_Crossed()
        {
            var beforeMidnight = DateTime.ParseExact("9/29/2020 11:51:58 PM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
            var afterMidnight  = DateTime.ParseExact("9/30/2020 00:00:58 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

            var timeServer = new TestDateTimeServer(beforeMidnight);
            var fileSink   = new FileSink(timeServer);

            using (var sut = new SimplerAsyncLog(fileSink))
            {
                sut.Write("before midnight");

                Thread.Sleep(200);

                timeServer.ChangeTestTime(() => afterMidnight);

                sut.Write("after midnight");

                sut.StopWithFlush();
            }

            var resultBeforeMidnight = File.ReadAllText(beforeMidnight.LogPath());
            var resultAfterMidnight  = File.ReadAllText(afterMidnight.LogPath());

            Assert.Contains("before midnight", resultBeforeMidnight);
            Assert.Contains("after midnight", resultAfterMidnight);

            File.Delete(beforeMidnight.LogPath());
            File.Delete(afterMidnight.LogPath());
        }
Example #13
0
    public static void Log(string message, params object[] args)
    {
        try
        {
            if (StartupLogFilePath != null)
            {
                try
                {
                    using (var fileSink = new FileSink(StartupLogFilePath))
                    {
                        fileSink.Info($"[{DateTime.UtcNow:O}] {message}{Environment.NewLine}", args);
                    }

                    return;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"Log: Exception creating FileSink {ex}");
                }
            }

            Console.Error.WriteLine(message, args);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Log: Global exception: {ex}");
        }
    }
        string GetJsonEventFile(Event <LogEventData> evt, string issueNumber)
        {
            var parser     = new MessageTemplateParser();
            var properties =
                (evt.Data.Properties ?? new Dictionary <string, object>()).Select(
                    kvp => CreateProperty(kvp.Key, kvp.Value));

            var logEvent = new LogEvent(
                evt.Data.LocalTimestamp,
                (Serilog.Events.LogEventLevel)Enum.Parse(typeof(Serilog.Events.LogEventLevel), evt.Data.Level.ToString()),
                evt.Data.Exception != null ? new WrappedException(evt.Data.Exception) : null,
                parser.Parse(evt.Data.MessageTemplate),
                properties);

            string logFilePath = Path.Combine(App.StoragePath, string.Format($"SeqAppYouTrack-{issueNumber}.json"));

            using (var jsonSink = new FileSink(logFilePath, new JsonFormatter(), null))
            {
                var logger =
                    new LoggerConfiguration().WriteTo.Sink(jsonSink, Serilog.Events.LogEventLevel.Verbose)
                    .CreateLogger();
                logger.Write(logEvent);
            }

            return(logFilePath);
        }
        /// <summary>
        /// Write log events to the specified file.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="path">Path to the file.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="fileSizeLimitBytes">The maximum size, in bytes, to which a log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration File(
            this LoggerSinkConfiguration sinkConfiguration,
            string path,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            long? fileSizeLimitBytes = DefaultFileSizeLimitBytes)
        {
            if (sinkConfiguration == null) throw new ArgumentNullException("sinkConfiguration");
            if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            
            FileSink sink;
            try
            {
                sink = new FileSink(path, formatter, fileSizeLimitBytes);
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex);
                return sinkConfiguration.Sink(new NullSink());
            }

            return sinkConfiguration.Sink(sink, restrictedToMinimumLevel);
        }
Example #16
0
        void OpenFile(DateTimeOffset timeStamp)
        {
            var limit = timeStamp.Date.AddDays(1);
            var path  = string.Format(_pathFormat, timeStamp.Date.ToString("yyyy-MM-dd"));

            _currentFile        = new FileSink(path, _textFormatter);
            _limitOfCurrentFile = limit;
        }
        public void Attach(FileSink sink)
        {
            Host = sink;

            RefreshArchiveLocation();

            Host.BeforeInitialized += Host_BeforeInitialized;
            Host.BeforeWrite += Host_BeforeWrite;
        }
 private void stop_Click(object sender, EventArgs e)
 {
     if (videoRecorder != null && videoRecorder.State == CaptureState.Started)
     {
         videoRecorder.Stop();
         videoRecorder       = null;
         fileWriter          = null;
         videoContainer.Fill = new SolidColorBrush(Colors.Gray);
     }
 }
Example #19
0
        void CloseFile()
        {
            if (_currentFile != null)
            {
                _currentFile.Dispose();
                _currentFile = null;
            }

            _nextCheckpoint = null;
        }
Example #20
0
        void OpenFile(DateTime now)
        {
            string   path;
            DateTime nextCheckpoint;

            _roller.GetLogFilePath(now, out path, out nextCheckpoint);
            _nextCheckpoint = nextCheckpoint;
            _currentFile    = new FileSink(path, _textFormatter, _fileSizeLimitBytes);
            ApplyRetentionPolicy(path);
        }
Example #21
0
        void OpenFile(DateTime now)
        {
            var date = now.Date;

            // We only take one attempt at it because repeated failures
            // to open log files REALLY slow an app down.
            _nextCheckpoint = date.AddDays(1);

            var existingFiles = Enumerable.Empty <string>();

            try
            {
                existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
                                .Select(Path.GetFileName);
            }
            catch (DirectoryNotFoundException) { }

            var latestForThisDate = _roller
                                    .SelectMatches(existingFiles)
                                    .Where(m => m.Date == date)
                                    .OrderByDescending(m => m.SequenceNumber)
                                    .FirstOrDefault();

            var sequence = latestForThisDate != null ? latestForThisDate.SequenceNumber : 0;

            const int maxAttempts = 3;

            for (var attempt = 0; attempt < maxAttempts; attempt++)
            {
                string path;
                _roller.GetLogFilePath(now, sequence, out path);

                try
                {
                    _currentFile = new FileSink(path, _textFormatter, _fileSizeLimitBytes);
                }
                catch (IOException ex)
                {
                    var errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1);
                    if (errorCode == 32 || errorCode == 33)
                    {
                        SelfLog.WriteLine("Rolling file target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1);
                        sequence++;
                        continue;
                    }

                    throw;
                }

                ApplyRetentionPolicy(path);
                return;
            }
        }
 private void DisposeVideoRecorder()
 {
     if (_captureSource != null)
     {
         if (_captureSource.VideoCaptureDevice != null
             && _captureSource.State == CaptureState.Started)
             _captureSource.Stop();
         _captureSource.CaptureFailed -= OnCaptureSourceOnCaptureFailed;
         _captureSource = null;
         _videoCaptureDevice = null;
         _fileSink = null;
         _videoBrush = null;
     }
 }
 /// <summary>
 /// Releases resources
 /// </summary>
 private void DisposeVideoRecorder()
 {
     if (captureSource != null)
     {
         if ((captureSource.VideoCaptureDevice != null) && (captureSource.State == CaptureState.Started))
         {
             captureSource.Stop();
         }
         captureSource      = null;
         videoCaptureDevice = null;
         fileSink           = null;
         videoRecorderBrush = null;
     }
 }
Example #24
0
        /// <summary>
        /// Initializes a new instance of <see cref="AsyncSingleFileSink"/>.
        /// </summary>
        /// <param name="formatter">Log formatter.</param>
        /// <param name="renderer">Renderer factory method.</param>
        /// <param name="logFilePath">Log file path.</param>
        /// <param name="encoding">File encoding. The default is UTF8.</param>
        /// <param name="bufferSize">Buffer size to be used. The default is 4096.</param>
        public AsyncSingleFileSink(ILogFormatter formatter, Func <IDataRenderer> renderer, string logFilePath,
                                   Encoding encoding = null, int bufferSize = 4096)
        {
            Formatter     = formatter;
            this.renderer = renderer;

            sink = new FileSink(Formatter, renderer, logFilePath, encoding, bufferSize);

            asyncWriter = new AsyncWriter((level, entries) =>
            {
                sink.Write(level, entries);
            });
            asyncWriter.Start();
        }
Example #25
0
        public void FileIsWrittenIfNonexistent()
        {
            using (var tmp = TempFolder.ForCaller())
            {
                var nonexistent = tmp.AllocateFilename("txt");
                var evt         = Some.LogEvent("Hello, world!");

                using (var sink = new FileSink(nonexistent, new JsonFormatter(), null))
                {
                    sink.Emit(evt);
                }

                var lines = System.IO.File.ReadAllLines(nonexistent);
                Assert.Contains("Hello, world!", lines[0]);
            }
        }
        public void InitializeVideoRecorder()
        {
            try
            {
                //fileName = string.Format(@"\Purposecode\Video{0}.mp4", DateTime.Now.ToString("yyyyMMddHHmmss"));
                fileName = string.Format("Video{0}.mp4", DateTime.Now.ToString("yyyyMMddHHmmss"));

                if (captureSource == null)
                {
                    // Create the VideoRecorder objects.
                    captureSource = new CaptureSource();
                    fileSink = new FileSink();

                    videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                    // Add eventhandlers for captureSource.
                    captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);

                    // Initialize the camera if it exists on the device.
                    if (videoCaptureDevice != null)
                    {
                        // Create the VideoBrush for the viewfinder.
                        videoRecorderBrush = new VideoBrush();
                        videoRecorderBrush.SetSource(captureSource);

                        // Display the viewfinder image on the rectangle.
                        viewfinderRectangle.Fill = videoRecorderBrush;
                        StopPlaybackRecording.IsEnabled = false;
                        // Start video capture and display it on the viewfinder.
                        captureSource.Start();

                        // Set the button state and the message.
                        UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
                    }
                    else
                    {
                        // Disable buttons when the camera is not supported by the device.
                        UpdateUI(ButtonState.CameraNotSupported, "Camera is not supported..");
                    }
                }

            }
            catch (Exception ex)
            {
                var test = ex.Message;
            }
        } //InitializeVideoRecorder()
        /// <summary>
        /// Creates a new recoding pipeline with the best (by user preference) available encoder and attaches it
        /// to the audiotee
        /// </summary>
        /// <returns>
        /// A <see cref="System.Boolean"/>, true if the pipeline was successfully created, false otherwise.
        /// </returns>
        public bool Create()
        {
            string bin_description = BuildPipeline();

            try {
                audiotee = new PlayerAudioTee(ServiceManager.PlayerEngine.ActiveEngine.GetBaseElements()[2]);

                if (bin_description.Equals(""))
                {
                    return(false);
                }

                encoder_bin = Parse.BinFromDescription(bin_description, true);
//                Hyena.Log.Debug ("DEBUG bin to string: " + encoder_bin.ToString());

                tagger    = new TagSetter(encoder_bin.GetByInterface(TagSetter.GetType()));
                file_sink = encoder_bin.GetByName("file_sink").ToFileSink();

                file_sink.Location = empty_file;
                file_sink.SetBooleanProperty("sync", true);
                file_sink.SetBooleanProperty("async", false);

                OldGLib.Object.GetObject(file_sink.ToIntPtr()).AddNotification("allow-overwrite", OnAllowOverwrite);

                ghost_pad = encoder_bin.GetStaticPad("sink").ToGhostPad();

                outputselector = encoder_bin.GetByName("sel");

                Pad filesinkpad = file_sink.GetStaticPad("sink");
                selector_filepad = filesinkpad.GetPeer();

                Element fake_sink   = encoder_bin.GetByName("fake_sink");
                Pad     fakesinkpad = fake_sink.GetStaticPad("sink");
                selector_fakepad = fakesinkpad.GetPeer();

                audiotee.AddBin(encoder_bin, ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing);
                Hyena.Log.Debug("[Recorder] Recorder attached");
            } catch (Exception e) {
                Hyena.Log.InformationFormat("[Streamrecorder] An exception occurred during pipeline construction: {0}", bin_description);
                Hyena.Log.Debug(e.Message);
                Hyena.Log.Debug(e.StackTrace);
                return(false);
            }

            return(true);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (captureSource != null)
            {
                captureSource.CaptureImageCompleted -= captureSource_CaptureImageCompleted;

                if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();
                }

                captureSource = null;
                fileSink = null;
                videoCaptureDevice = null;
            }

            base.OnNavigatedFrom(e);
        }
Example #29
0
        public void FileControllerGetsCorrectString()
        {
            bool fileControllerGotLog = false;

            var fileController = new Mock <IFileController>();

            fileController.Setup(f => f.AppendLogEntry("this is correct log"))
            .Callback(() => fileControllerGotLog = true);

            var sink = new FileSink(fileController.Object);

            sink.Emit("this is not correct log", Enums.LogLevel.Critical);

            Assert.False(fileControllerGotLog);

            sink.Emit("this is correct log", Enums.LogLevel.Trace);

            Assert.True(fileControllerGotLog);
        }
        private void StartRecordig()
        {
            if (m_captureSource == null)
            {
                m_captureSource = new CaptureSource();
                m_captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
                m_captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

                m_sink = new FileSink();
                m_sink.CaptureSource = m_captureSource;
                m_sink.IsolatedStorageFileName = m_capturedFileName;
            }

            VideoBrush brush = new VideoBrush();
            brush.SetSource(m_captureSource);
            CameraPreview.Fill = brush;

            m_captureSource.Start();
        }
    private void ConstructPipeline()
    {
        pipeline = new Pipeline("pipeline");

        filesrc                  = ElementFactory.Make("filesrc", "filesrc") as FileSrc;
        filesink                 = ElementFactory.Make("filesink", "filesink") as FileSink;
        audioconvert             = ElementFactory.Make("audioconvert", "audioconvert");
        encoder                  = ElementFactory.Make("wavenc", "wavenc");
        decodebin                = ElementFactory.Make("decodebin2", "decodebin") as DecodeBin2;
        decodebin.NewDecodedPad += OnNewDecodedPad;

        pipeline.Add(filesrc, decodebin, audioconvert, encoder, filesink);

        filesrc.Link(decodebin);
        audioconvert.Link(encoder);
        encoder.Link(filesink);

        pipeline.Bus.AddWatch(new BusFunc(OnBusMessage));
    }
        /// <summary>
        /// Write log events as JSON to the specified file.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="path">Path to the file.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="fileSizeLimitBytes">The maximum size, in bytes, to which a log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB.</param>
        /// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
        /// is false.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration JsonFile(
            this LoggerSinkConfiguration sinkConfiguration,
            string path,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IFormatProvider formatProvider         = null,
            long?fileSizeLimitBytes        = DefaultFileSizeLimitBytes,
            LoggingLevelSwitch levelSwitch = null,
            bool buffered = false)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            var formatter = new JsonFormatter(formatProvider: formatProvider);

            FileSink sink;

            try
            {
                sink = new FileSink(path, formatter, fileSizeLimitBytes
#if BUFFERING_CONTROL
                                    , buffered: buffered
#endif
                                    );
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex);
                return(sinkConfiguration.Sink(new NullSink()));
            }

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel
#if LEVEL_SWITCH
                                          , levelSwitch
#endif
                                          ));
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (captureSource == null)
            {
                captureSource = new CaptureSource();
                captureSource.CaptureImageCompleted += captureSource_CaptureImageCompleted;

                fileSink = new FileSink();
                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                if (videoCaptureDevice != null)
                {
                    videoBrush.SetSource(captureSource);
                    videoBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
                    captureSource.Start();
                }
            }
        }
Example #34
0
        public void Can_Write_To_Log()
        {
            var expected = "test write";

            var testTime = DateTime.Now - TimeSpan.FromDays(1);

            var fileSink = new FileSink(new TestDateTimeServer(testTime));

            using (var sut = new SimplerAsyncLog(fileSink))
            {
                sut.Write(expected);
                sut.StopWithFlush();
            }

            var result = File.ReadAllText(testTime.LogPath());

            Assert.Contains(expected, result);

            File.Delete(testTime.LogPath());
        }
Example #35
0
        private void DisposeVideoRecorder()
        {
            if (captureSource != null)
            {
                if (captureSource.VideoCaptureDevice != null &&
                    captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();
                }

                // Remove the event handler for captureSource.
                captureSource.CaptureFailed -= captureSource_CaptureFailed;

                // Remove the video recording objects.
                captureSource      = null;
                videoCaptureDevice = null;
                fileSink           = null;
                videoRecorderBrush = null;
            }
        }
Example #36
0
        private void InitializeVideoRecorder()
        {
            if (captureSource == null)
            {
                captureSource = new CaptureSource();
                fileSink      = new FileSink();

                var devices = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();
                captureSource.VideoCaptureDevice = devices[0];
                captureSource.CaptureFailed     += captureSource_CaptureFailed;

                if (videoCaptureDevice != null)
                {
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);

                    ViewfinderRectangle.Fill = videoRecorderBrush;
                    captureSource.Start();
                }
            }
        }
Example #37
0
        private void DisposeVideoRecorder()
        {
            if (_captureSource != null)
            {
                // Stop captureSource if it is running.
                if (_captureSource.VideoCaptureDevice != null &&
                    _captureSource.State == CaptureState.Started)
                {
                    _captureSource.Stop();
                }

                // Remove the event handler for captureSource.
                _captureSource.CaptureFailed -= OnCaptureFailed;

                // Remove the video recording objects.
                _captureSource      = null;
                _videoCaptureDevice = null;
                _fileSink           = null;
                _videoRecorderBrush = null;
            }
        }
        private void InitializeVideoRecorder()
        {
            if (_captureSource == null)
            {
                _captureSource = new CaptureSource();
                _fileSink = new FileSink();

                _videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
                _captureSource.CaptureFailed += OnCaptureSourceOnCaptureFailed;
                _captureSource.CaptureImageCompleted += CaptureSourceOnCaptureImageCompleted;

                if (_videoCaptureDevice != null)
                {
                    _videoBrush = new VideoBrush();
                    _videoBrush.SetSource(_captureSource);

                    ViewFinderRectangle.Fill = _videoBrush;
                    _captureSource.Start();
                }
            }
        }
        private void DisposeVideoRecorder()
        {
            if (_captureSource != null)
            {
                // Stop _captureSource if it is running.
                if (_captureSource.VideoCaptureDevice != null &&
                    _captureSource.State == CaptureState.Started)
                {
                    _captureSource.Stop();
                }

                // Remove the event handlers for capturesource and the shutter button.
                _captureSource.CaptureFailed         -= OnCaptureFailed;
                _captureSource.CaptureImageCompleted -= OnThumbCompleted;
                // Remove the video recording objects.
                _captureSource      = null;
                _videoCaptureDevice = null;
                _fileSink           = null;
                ViewfinderBrush     = null;
            }
        }
Example #40
0
        public void StopRecording()
        {
            if (captureSource != null)
              {
            // Stop captureSource if it is running.
            if (captureSource.VideoCaptureDevice != null
            && captureSource.State == CaptureState.Started)
            {
              captureSource.Stop();
            }

            // Remove the event handlers for capturesource and the shutter button.
            captureSource.CaptureFailed -= OnCaptureFailed;

            // Remove the video recording objects.
            captureSource = null;
            videoCaptureDevice = null;
            fileSink = null;
            videoRecorderBrush = null;
              }
        }
Example #41
0
        private void DisposeVideoRecorder()
        {
            if (captureSource != null)
            {
                // Stop captureSource if it is running.
                if (captureSource.VideoCaptureDevice != null &&
                    captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();
                }

                // Remove the event handlers for capturesource and the shutter button.
                captureSource.CaptureFailed -= OnCaptureFailed;

                // Remove the video recording objects.
                captureSource      = null;
                videoCaptureDevice = null;
                fileSink           = null;
                videoRecorderBrush = null;
            }
        }
Example #42
0
        /// <summary>
        /// Initialize the Capture Device
        /// </summary>
        private void InitializeCaptureDevice()
        {
            //set the video capture device
            if (captureSource == null)
            {
                captureSource = new CaptureSource();
               captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
                captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

                

                sink = new FileSink();
                sink.CaptureSource = captureSource;
                sink.IsolatedStorageFileName = m_capturedFileName;
            }

            //set the video preview
            var brush = new VideoBrush();
            brush.SetSource(captureSource);
            
            cameraPreview.Fill = brush;
        }
        public void InitializeVideoRecorder()
        {
            if (_captureSource == null)
            {
                // Create the VideoRecorder objects.
                _captureSource = new CaptureSource();
                _fileSink = new FileSink();

                _videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                // Add eventhandlers for captureSource.
                _captureSource.CaptureFailed += OnCaptureFailed;

                // Initialize the camera if it exists on the phone.
                if (_videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    _videoRecorderBrush = new VideoBrush();
                    _videoRecorderBrush.SetSource(_captureSource);

                    // Display the viewfinder image on the rectangle.
                    viewfinderRectangle.Fill = _videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    _captureSource.Start();

                    // Set the button state and the message.
                    UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
                }
                else
                {
                    // Disable buttons when the camera is not supported by the phone.
                    UpdateUI(ButtonState.NoChange, "Camera Not Supported.");
                }
            }
        }
        void TryArchive(FileSink sink, bool isStartup, long? messageSize = null)
        {
            try
            {
                using (var lockToken = sink.FileLockingStrategy.AcquireLock(sink.LogFile.FullName))
                {
                    // double check if archive is still needed now that we have lock
                    if (!CheckArchiveNeeded(sink, isStartup, messageSize))
                        return;

                    EnsureFreeSlotInArchive();

                    // todo: support different archive naming strategies (e.g. numeric prefix indicating slot number in the archive)

                    var newFileName =
                        "[{0}]  {1}"
                        .FormatWith(
                            DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss").ToValidFileName(),
                            sink.LogFile.Name);

                    var newFileFullPath = Path.Combine(ArchiveLocation.FullName, newFileName);

                    lockToken.CloseFileIfNeeded();

                    System.IO.File.Move(sink.LogFile.FullName, newFileFullPath);
                }
            }
            catch(Exception ex)
            {
                // todo: internal log warning
            }
        }
 void Host_BeforeWrite(object sender, FileSink.BeforeWriteEventArgs e)
 {
     ArchiveIfNeeded((FileSink)sender, isStartup: false, messageSize: e.MessageSize);
 }
        bool CheckArchiveNeeded(FileSink sink, bool isStartup, long? messageSize = null)
        {
            sink.LogFile.Refresh();

            if (!sink.LogFile.Exists)
                return false;

            if (isStartup && TriggerOnStartup && sink.LogFile.Length > 0)
            {
                return true;
            }

            if (TriggerOnFileSize.HasValue && messageSize.HasValue)
            {
                if (sink.LogFile.Length + messageSize.Value >= TriggerOnFileSize.Value)
                {
                    return true;
                }
            }

            if (TriggerOnFileAge.HasValue)
            {
                if ((sink.LogFile.CreationTimeUtc - DateTime.UtcNow) >= TriggerOnFileAge.Value)
                {
                    return true;
                }
            }

            // NOTE:    use current machine time, not UTC
            //          assumption is that local time is to be used always
            //          this may cause different behavior on days when local time changes
            //          Example:
            //          British Summer Time (BST) ends at 01:00 GMT when clock is moved back 1 hour.
            //          If TriggerOnTime is set to 01:00 then log can be archive twice within 1 hour period
            //          instead of expected once within 24 hour period
            if (TriggerOnTime.HasValue
                && DateTime.Now.TimeOfDay >= TriggerOnTime.Value
                && sink.LogFile.CreationTime.TimeOfDay < TriggerOnTime.Value)
            {
                return true;
            }

            return false;
        }
 void ArchiveIfNeeded(FileSink sink, bool isStartup, long? messageSize = null)
 {
     if(CheckArchiveNeeded(sink, isStartup, messageSize))
     {
         TryArchive(sink, isStartup, messageSize);
     }
 }
Example #48
0
        public void stop()
        {
            if (captureSource != null)
            {
                // Stop captureSource if it is running.
                if (captureSource.VideoCaptureDevice != null
                    && captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();
                }

                // Remove the event handler for captureSource.
                captureSource.CaptureFailed -= OnCaptureFailed;

                // Remove the video recording objects.
                captureSource = null;
                videoCaptureDevice = null;
                fileSink = null;
                videoRecorderBrush = null;
                System.Diagnostics.Debug.WriteLine("Stopped");
                _isRunning = false;

            }
        }
 private void stop_Click(object sender, EventArgs e)
 {
     if (videoRecorder != null && videoRecorder.State == CaptureState.Started)
     {
         videoRecorder.Stop();
         videoRecorder = null;
         fileWriter = null;
         videoContainer.Fill = new SolidColorBrush(Colors.Gray);
     }
 }
        private void StartCapture(VideoCaptureDevice videoDevice)
        {
            if (videoRecorder == null || videoRecorder.State != CaptureState.Started)
            {
                videoRecorder = new CaptureSource
                {
                    VideoCaptureDevice = videoDevice,
                    AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice()
                };

                var brush = new VideoBrush();
                brush.SetSource(videoRecorder);
                videoContainer.Fill = brush;

                fileWriter = new FileSink
                {
                    CaptureSource = videoRecorder,
                    IsolatedStorageFileName = "video-recording.mp4",
                };

                videoRecorder.Start();
            }
        }
        private void DisposeVideoRecorder()
        {
            try
            {
                if (captureSource != null)
                {
                    if (captureSource.VideoCaptureDevice != null
                        && captureSource.State == CaptureState.Started)
                    {
                        captureSource.Stop();
                    }

                    captureSource.CaptureFailed -= OnCaptureFailed;
                    captureSource = null;
                }
                videoCaptureDevice = null;
                fileSink = null;
                videoRecorderBrush = null;
                isoVideoFile = null;

                GC.Collect();
            }
            catch (Exception ex)
            {
                var test = ex.Message;
            }
        }
        public void InitializeVideoRecorder()
        {
            if (captureSource == null)
            {
                // Create the VideoRecorder objects.
                captureSource = new CaptureSource();
                fileSink = new FileSink();

                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                // Add eventhandlers for captureSource.
                captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);

                // Initialize the camera if it exists on the device.
                if (videoCaptureDevice != null)
                {
                    // Create the VideoBrush for the viewfinder.
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);

                    // Display the viewfinder image on the rectangle.
                    viewfinderRectangle.Fill = videoRecorderBrush;

                    // Start video capture and display it on the viewfinder.
                    captureSource.Start();

                    // Set the button state and the message.
                    UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
                }
                else
                {
                    // Disable buttons when the camera is not supported by the device.
                    UpdateUI(ButtonState.CameraNotSupported, "A camera is not supported on this device.");
                }
            }
        }
Example #53
0
        private void InitializeVideoRecorder()
        {
            if (captureSource == null)
            {
                captureSource = new CaptureSource();
                fileSink = new FileSink();

                var devices = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();
                captureSource.VideoCaptureDevice = devices[0];
                captureSource.CaptureFailed += captureSource_CaptureFailed;

                if (videoCaptureDevice != null)
                {
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);

                    ViewfinderRectangle.Fill = videoRecorderBrush;
                    captureSource.Start();
                }
            }
        }
        private void DisposeVideoRecorder()
        {
            if (_captureSource != null)
            {
                // Stop captureSource if it is running.
                if (_captureSource.VideoCaptureDevice != null
                    && _captureSource.State == CaptureState.Started)
                {
                    _captureSource.Stop();
                }

                // Remove the event handler for captureSource.
                _captureSource.CaptureFailed -= OnCaptureFailed;

                // Remove the video recording objects.
                _captureSource = null;
                _videoCaptureDevice = null;
                _fileSink = null;
                _videoRecorderBrush = null;
            }
        }
 /// <summary>
 /// Releases resources
 /// </summary>
 private void DisposeVideoRecorder()
 {
     if (captureSource != null)
     {
         if ((captureSource.VideoCaptureDevice != null) && (captureSource.State == CaptureState.Started))
         {
             captureSource.Stop();
         }
         captureSource = null;
         videoCaptureDevice = null;
         fileSink = null;
         videoRecorderBrush = null;
     }
 }
        /// <summary>
        /// Initializes VideoRecorder
        /// </summary>
        public void InitializeVideoRecorder()
        {
            if (captureSource == null)
            {
                captureSource = new CaptureSource();
                fileSink = new FileSink();
                videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                if (videoCaptureDevice != null)
                {
                    videoRecorderBrush = new VideoBrush();
                    videoRecorderBrush.SetSource(captureSource);
                    viewfinderRectangle.Fill = videoRecorderBrush;
                    captureSource.Start();
                    this.UpdateUI(VideoState.Initialized);
                }
                else
                {
                    this.UpdateUI(VideoState.CameraNotSupported);
                }
            }
        }
Example #57
0
 /// <summary>
 /// Create file sink
 /// </summary>
 private void createFile()
 {
     videoSink = new FileSink();
 }
Example #58
0
 /// <summary>
 ///  Save video capture to an MP4 file in order to play back at a later time, using FileSink
 /// </summary>
 /// <param name="fileName">The file name (without extention!)</param>
 /// <param name="captureSource">The video capture source</param>
 public static void SaveVideoCaptureFile(string fileName, CaptureSource captureSource)
 {
     var sink = new FileSink();
     sink.CaptureSource = captureSource;
     //TODO: Nitzo, pay attention that the captured file is mp4
     sink.IsolatedStorageFileName = fileName + ".mp4";
 }
Example #59
0
        private void DisposeVideoRecorder()
        {
            if (captureSource != null)
            {
                if (captureSource.VideoCaptureDevice != null
                    && captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();
                }

                // Remove the event handler for captureSource.
                captureSource.CaptureFailed -= captureSource_CaptureFailed;

                // Remove the video recording objects.
                captureSource = null;
                videoCaptureDevice = null;
                fileSink = null;
                videoRecorderBrush = null;
            }
        }