Exemplo n.º 1
0
        private async Task ProcessFile(string file)
        {
            StreamReader stream = null;

            try
            {
                var tracking = new Host("FTP", IPAddress.Loopback);
                var header   = new VideoHeader(tracking, file);
                if (!destination.IsDownloaded(header))
                {
                    log.Info("Copy <{0}>", file);
                    stream = new StreamReader(file);
                    await destination.Transfer(header, stream.BaseStream).ConfigureAwait(false);
                }
                else
                {
                    log.Info("File is already copied <{0}", file);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            finally
            {
                stream?.Dispose();
            }
        }
Exemplo n.º 2
0
        public bool IsDownloaded(VideoHeader header)
        {
            Guard.NotNull(() => header, header);
            var fileDestination = header.GetPath(destination);

            return(File.Exists(fileDestination));
        }
Exemplo n.º 3
0
        public async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);

            var temp = Path.GetTempFileName();

            using (StreamWriter write = new StreamWriter(temp))
            {
                await source.CopyToAsync(write.BaseStream).ConfigureAwait(false);
            }

            try
            {
                using (VideoFileReader reader = new VideoFileReader())
                {
                    reader.Open(temp);
                    using (Bitmap videoFrame = reader.ReadVideoFrame())
                    {
                        videoFrame.Save(ResolveName(header), ImageFormat.Png);
                    }
                }
            }
            finally
            {
                File.Delete(temp);
            }
        }
        protected override bool GetLiveFrameInternal(TimeSpan timeout, out BaseDataHeader header, out byte[] data)
        {
            header = null;
            data   = null;

            // TODO: Implement request for fetching data from device

            if (data == null || data.Length == 0)
            {
                return(false);
            }
            DateTime dt = DateTime.UtcNow; // TODO: If a timestamp is provided by device, use that instead

            // TODO: Update to reflect actual data
            header = new VideoHeader()
            {
                CodecType      = VideoCodecType.JPEG,
                Length         = (ulong)data.Length,
                SequenceNumber = _sequence++,
                SyncFrame      = true,
                TimestampSync  = dt,
                TimestampFrame = dt
            };
            return(true);
        }
Exemplo n.º 5
0
        protected override bool GetLiveFrameInternal(TimeSpan timeout, out BaseDataHeader header, out byte[] data)
        {
            header = null;
            data   = _demoConnectionManager.GetLiveFrame(Channel, false);
            if (data.Length == 0)
            {
                return(false);
            }
            DateTime dt    = DateTime.UtcNow;
            var      codec = VideoCodecType.JPEG;

            // If you wanted to support multiple codecs, the commented code below demonstrates how this could be done (and also how to get stream settings for any other purpose)
            // var setting = _settingsManager.GetSetting(new StreamSetting(Constants.Codec, _deviceId, _streamId, ""));
            // if (setting.Value == VideoCodecType.H264.ToString())
            // {
            //     codec = VideoCodecType.H264;
            // }
            // For video codec types other than JPEG, an important thing to note here is that we always transfer the data out of the GetLiveFrame
            // call in single frame chunks. That is to say, regardless of what kind of frame it might be (P-frame, I-frame, etc.) it is sent as
            // one frame per message.
            header = new VideoHeader()
            {
                CodecType      = codec,
                Length         = (ulong)data.Length,
                SequenceNumber = _sequence++,
                SyncFrame      = true, // For codecs other than MJPEG, this should only be true for key frames.
                TimestampSync  = dt,   // If the video codec is e.g. H.264, this should be the time stamp of the most recent keyframe. On a keyframe, this will be the same as TimestampFrame.
                TimestampFrame = dt
            };
            return(true);
        }
Exemplo n.º 6
0
        public void GetPath(string fileName, string expected)
        {
            VideoHeader header = new VideoHeader(new Host("Camera", IPAddress.Any), fileName);
            var         result = header.GetPath(@"c:\out");

            Assert.AreEqual(expected, result);
        }
Exemplo n.º 7
0
 public void SetUp()
 {
     header          = new VideoHeader(new Host("Camera", IPAddress.Any), "test.mov");
     mockDestination = new Mock <IDestination>();
     mockAction      = new Mock <IPriorAction>();
     stream          = new Mock <Stream>();
     instance        = CreateChainedActionDestination();
 }
Exemplo n.º 8
0
        private void HandleSearchSelectedItem(object listBox, object selectedItem)
        {
            VideoHeader selected = selectedItem as VideoHeader;

            CurrentMediaSource.VideoSource  = StatisticsActionSource.search;
            CurrentMediaSource.VideoContext = this._searchQuery;
            this.ProcessSelectedVideoHeader(selected);
        }
 public void SetUp()
 {
     header          = new VideoHeader(new Host("Test", IPAddress.Any), "test.mov");
     mockDestination = new Mock <IDestination>();
     renameFunc      = name => "test";
     stream          = new Mock <Stream>();
     instance        = CreateTransformedDestination();
 }
Exemplo n.º 10
0
 private void ProcessSelectedVideoHeader(VideoHeader selected)
 {
     if (selected == null)
     {
         return;
     }
     Navigator.Current.NavigateToVideoWithComments(selected.VKVideo, selected.VKVideo.owner_id, selected.VKVideo.vid, "");
 }
Exemplo n.º 11
0
        public override async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);
            var transfer = next.Transfer(header, source);
            var name     = next.ResolveName(header);
            await transfer.ConfigureAwait(false);

            await postAction.AfterTransfer(name).ConfigureAwait(false);
        }
Exemplo n.º 12
0
        public async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);
            var fileDestination = ResolveName(header);

            using (StreamWriter write = new StreamWriter(fileDestination))
            {
                await source.CopyToAsync(write.BaseStream).ConfigureAwait(false);
            }
        }
        public override async Task Transfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);
            var result = await priorAction.BeforeTransfer(header, source).ConfigureAwait(false);

            using (result.source)
            {
                await next.Transfer(result.header, result.source).ConfigureAwait(false);
            }
        }
Exemplo n.º 14
0
        private void Video_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            VideoHeader selectedItem = this.videosListBox.SelectedItem as VideoHeader;

            if (selectedItem == null)
            {
                return;
            }
            this.videosListBox.SelectedItem = null;
            Navigator.Current.NavigateToVideoWithComments(selectedItem.VKVideo, selectedItem.VKVideo.owner_id, selectedItem.VKVideo.vid, selectedItem.VKVideo.access_key ?? "");
        }
        public async Task Transfer()
        {
            VideoHeader inpuParameter = null;

            mockDestination.Setup(item => item.Transfer(It.IsAny <VideoHeader>(), stream.Object)).Returns(Task.CompletedTask)
            .Callback <VideoHeader, Stream>(
                (parameter, inputStream) => { inpuParameter = parameter; });
            await instance.Transfer(header, stream.Object);

            Assert.AreEqual("test", inpuParameter.FileName);
        }
Exemplo n.º 16
0
        public void SetUp()
        {
            outPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "out");
            if (Directory.Exists(outPath))
            {
                Directory.Delete(outPath, true);
            }

            header   = new VideoHeader(new Host("Camera", IPAddress.Any), "test.mov");
            instance = CreatePictureFileDestination();
            stream   = File.OpenRead(Path.Combine(TestContext.CurrentContext.TestDirectory, "data", "centaur_1.mpg"));
        }
        public void ChangeExtension()
        {
            VideoHeader inpuParameter = null;

            mockDestination.Setup(item => item.ResolveName(It.IsAny <VideoHeader>())).Returns("test")
            .Callback <VideoHeader>(
                parameter => { inpuParameter = parameter; });
            var result = TransformedDestination.ChangeExtension(mockDestination.Object, "png");

            result.ResolveName(header);
            Assert.AreEqual("test.png", inpuParameter.FileName);
        }
        public void IsDownloaded()
        {
            VideoHeader inpuParameter = null;

            mockDestination.Setup(item => item.IsDownloaded(It.IsAny <VideoHeader>())).Returns(true)
            .Callback <VideoHeader>(
                parameter => { inpuParameter = parameter; });
            var result = instance.IsDownloaded(header);

            Assert.IsTrue(result);
            Assert.AreEqual("test", inpuParameter.FileName);
        }
        public void ResolveName()
        {
            VideoHeader inpuParameter = null;

            mockDestination.Setup(item => item.ResolveName(It.IsAny <VideoHeader>())).Returns("test")
            .Callback <VideoHeader>(
                parameter => { inpuParameter = parameter; });
            var name = instance.ResolveName(header);

            Assert.AreEqual("test", name);
            Assert.AreEqual("test", inpuParameter.FileName);
        }
Exemplo n.º 20
0
        public async Task Transfer()
        {
            Assert.IsFalse(File.Exists(outFile));
            VideoHeader header = new VideoHeader(new Host("Camera", IPAddress.Any), "test.txt");

            using (StreamReader reader = new StreamReader(Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "Test.txt")))
            {
                await instance.Transfer(header, reader.BaseStream).ConfigureAwait(false);
            }

            Assert.IsTrue(File.Exists(outFile));
        }
Exemplo n.º 21
0
        public void SetUp()
        {
            header  = new VideoHeader(new Host("Camera", IPAddress.Any), "test.mov");
            outPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Out");
            if (Directory.Exists(outPath))
            {
                Directory.Delete(outPath, true);
            }

            instance = CreateFileDestination();
            stream   = new MemoryStream(new byte[] { 1 });
        }
        public override PlaybackReadResponse ReadData(Guid playbackId)
        {
            DateTime cur;

            lock (_playbackLockObj)
            {
                if (!_playbackCursors.TryGetValue(playbackId, out cur))
                {
                    throw new KeyNotFoundException(nameof(playbackId));
                }
            }

            try
            {
                // TODO: request real data
                byte[] data = new byte[] { };
                if (data == null)
                {
                    Toolbox.Log.Trace("--- No data returned ");
                    return(null);
                }

                // TODO: Change to correct values - potentially different codec.
                VideoHeader jpegHeader = new VideoHeader();
                jpegHeader.CodecType = VideoCodecType.JPEG;
                jpegHeader.SyncFrame = true;

                PlaybackFrame frame = new PlaybackFrame()
                {
                    Data = data, Header = jpegHeader, AnyMotion = true
                };
                jpegHeader.SequenceNumber = 0;
                jpegHeader.Length         = (ulong)data.Length;
                jpegHeader.TimestampFrame = cur;
                jpegHeader.TimestampSync  = cur;
                DateTime prev = cur - TimeSpan.FromSeconds(1);
                DateTime next = cur + TimeSpan.FromSeconds(1);
                return(new PlaybackReadResponse()
                {
                    SequenceNumber = _sequenceNumbers[playbackId],
                    Next = next,
                    Previous = prev,
                    Frames = new[] { frame },
                });
            }
            catch (Exception e)
            {
                Toolbox.Log.Trace("{0}: Exception={1}", nameof(ReadData), e.Message + e.StackTrace);
                return(null);
            }
        }
Exemplo n.º 23
0
        private async Task ProcessFile(FtpClient client, FtpListItem item)
        {
            Stream stream = null;

            try
            {
                var header = new VideoHeader(tracking.Host, item.FullName);
                if (!destination.IsDownloaded(header))
                {
                    log.Info("Downloading <{0}> from [{1}]", item.FullName, tracking.Host.Name);
                    stream = await client.OpenReadAsync(item.FullName).ConfigureAwait(false);

                    await destination.Transfer(header, stream).ConfigureAwait(false);

                    var reply = await client.GetReplyAsync(CancellationToken.None).ConfigureAwait(false);

                    if (reply.Success)
                    {
                        log.Info(
                            "Download Success:{0} Message:{1}: Type:{2} Code:{3} From: [{4}]",
                            reply.Success,
                            reply.Message,
                            reply.Type,
                            reply.Code,
                            tracking.Host.Name);
                    }
                    else
                    {
                        log.Error(
                            "Download Error:{0} Type:{1}: Code:{2} From: [{3}]",
                            reply.ErrorMessage,
                            reply.Type,
                            reply.Code,
                            tracking.Host.Name);
                    }
                }
                else
                {
                    log.Info("File is already downloaded - <{0}> {1}", item.FullName, tracking.Host.Name);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            finally
            {
                stream?.Dispose();
            }
        }
Exemplo n.º 24
0
        public Task <(VideoHeader header, Stream source)> BeforeTransfer(VideoHeader header, Stream source)
        {
            Guard.NotNull(() => header, header);
            Guard.NotNull(() => source, source);
            var             memory      = new MemoryStream();
            ZipArchive      archive     = new ZipArchive(memory, ZipArchiveMode.Create, true);
            ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(header.FileName));

            using (Stream entryStream = readmeEntry.Open())
            {
                source.CopyTo(entryStream);
            }

            memory.Position = 0;
            return(Task.FromResult((header, (Stream)memory)));
        }
Exemplo n.º 25
0
        public THP_Parser(Stream stream)
        {
            using (var reader = new FileReader(stream, true))
            {
                reader.SetByteOrder(true);
                FileHeader = reader.ReadStruct <Header>();

                bool isVersion11 = FileHeader.Version == 0x00011000;

                reader.SeekBegin(FileHeader.ComponentsOffset);

                uint   numComponents = reader.ReadUInt32();
                byte[] components    = reader.ReadBytes(16);
                for (int i = 0; i < components.Length; i++)
                {
                    if (components[i] == (byte)ComponentType.Video)
                    {
                        Video = new VideoHeader(reader, isVersion11);
                    }
                    if (components[i] == (byte)ComponentType.Audio)
                    {
                        Audio = new AudioHeader(reader, isVersion11);
                    }
                }
                bool hasVideo = components.Any(x => x == (byte)ComponentType.Video);
                bool hasAudio = components.Any(x => x == (byte)ComponentType.Audio);

                reader.SeekBegin(FileHeader.FirstFrameOffset);
                for (int i = 0; i < FileHeader.FrameCount; i++)
                {
                    long startFrame = reader.Position;

                    var frame = new FrameHeader(reader, hasAudio ? Audio.NumChannels : 0);
                    Frames.Add(frame);

                    if (i == 0)
                    {
                        reader.SeekBegin(startFrame + FileHeader.FirstFrameLength);
                    }
                    else
                    {
                        reader.SeekBegin(startFrame + Frames[i - 1].NextFrameSize);
                    }
                }
            }
        }
        private void GoToMessage_OnClicked(object sender, RoutedEventArgs e)
        {
            long   message_id  = 0;
            object dataContext = ((FrameworkElement)sender).DataContext;

            switch (this.pivot.SelectedIndex)
            {
            case 0:
                AlbumPhoto albumPhoto = dataContext as AlbumPhoto;
                message_id = albumPhoto != null ? albumPhoto.MessageId : 0L;
                break;

            case 1:
                VideoHeader videoHeader = dataContext as VideoHeader;
                message_id = videoHeader != null ? videoHeader.MessageId : 0L;
                break;

            case 2:
                AudioHeader audioHeader = dataContext as AudioHeader;
                message_id = audioHeader != null ? audioHeader.MessageId : 0L;
                break;

            case 3:
                DocumentHeader documentHeader = dataContext as DocumentHeader;
                message_id = documentHeader != null ? documentHeader.MessageId : 0L;
                break;

            case 4:
                LinkHeader linkHeader = dataContext as LinkHeader;
                message_id = linkHeader != null ? linkHeader.MessageId : 0L;
                break;
            }
            if (message_id == 0L)
            {
                return;
            }
            long peerId = this.ViewModel.PeerId;

            if (this.ViewModel.IsChat)
            {
                peerId -= 2000000000L;
            }
            Navigator.Current.NavigateToConversation(peerId, this.ViewModel.IsChat, false, "", message_id, false);
        }
Exemplo n.º 27
0
 private void ProcessSelectedVideoHeader(VideoHeader selected)
 {
     if (selected == null)
     {
         return;
     }
     if (!this.CommonParameters.PickMode)
     {
         Navigator.Current.NavigateToVideoWithComments(selected.VKVideo, selected.VKVideo.owner_id, selected.VKVideo.vid, "");
     }
     else
     {
         ParametersRepository.SetParameterForId("PickedVideo", selected.VKVideo);
         if (this._albumId != 0L)
         {
             ((Page)this).NavigationService.RemoveBackEntrySafe();
         }
         Navigator.Current.GoBack();
     }
 }
Exemplo n.º 28
0
        protected override bool GetLiveFrameInternal(TimeSpan timeout, out BaseDataHeader header, out byte[] data)
        {
            header = null;
            data   = _connectionManager.PopFrame();

            if (data == null || data.Length == 0)
            {
                return(false);
            }
            DateTime dt = DateTime.UtcNow;

            header = new VideoHeader
            {
                CodecType      = VideoCodecType.JPEG,
                Length         = (ulong)data.Length,
                SequenceNumber = _sequence++,
                SyncFrame      = true,
                TimestampSync  = dt,
                TimestampFrame = dt
            };
            return(true);
        }
 public string ResolveName(VideoHeader header)
 {
     Guard.NotNull(() => header, header);
     return(next.ResolveName(header));
 }
 public bool IsDownloaded(VideoHeader header)
 {
     Guard.NotNull(() => header, header);
     return(next.IsDownloaded(header));
 }