Beispiel #1
0
        static void Main(string[] args)
        {
            var options = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Display the default usage information
                //Console.WriteLine(options.GetUsage());
                return;
            }

            if (!File.Exists(options.FragmentFile))
            {
                Console.WriteLine("Fragment file not found: " + options.FragmentFile + ".");
                return;
            }

            if (!File.Exists(options.MainFile))
            {
                Console.WriteLine("Main file not found: " + options.MainFile + ".");
                return;
            }

            VFPAnalyzer.SetLicenseKey(options.LicenseKey);

            Console.WriteLine("Starting analyze.");

            var time = DateTime.Now;

            var fragment = VFPFingerPrint.Load(options.FragmentFile);
            var main     = VFPFingerPrint.Load(options.MainFile);

            double difference;
            var    res = VFPSearch.Search(fragment, 0, main, 0, out difference, options.MaxDifference);

            var elapsed = DateTime.Now - time;

            Console.WriteLine("Analyze finished. Elapsed time: " + elapsed.ToString("g"));

            if (res > 0)
            {
                TimeSpan ts = new TimeSpan(res * TimeSpan.TicksPerSecond);
                Console.WriteLine($"Detected fragment file at {ts:g}, difference level is {difference}");
            }
            else
            {
                Console.WriteLine("Fragment file not found.");
            }
        }
        private void StopVideoDelegateMethod()
        {
            // done. searching for fingerprints.
            VideoCapture1.Stop();

            long   n;
            IntPtr p = VFPSearch.Build(out n, ref searchLiveData);

            VFPFingerPrint fvp = new VFPFingerPrint()
            {
                Data             = new byte[n],
                OriginalFilename = string.Empty
            };

            Marshal.Copy(p, fvp.Data, 0, (int)n);

            searchLiveData.Free();


            foreach (var ad in adVFPList)
            {
                List <int> positions;
                bool       found = VFPAnalyzer.Search(ad, fvp, ad.Duration, (int)slDifference.Value, out positions, true);

                if (found)
                {
                    foreach (var pos in positions)
                    {
                        results.Add(
                            new ResultsViewModel()
                        {
                            Sample    = ad.OriginalFilename,
                            TimeStamp = DateTime.Now.ToString(CultureInfo.InvariantCulture)
                                        // minutes + ":" + seconds
                        });
                    }
                }
            }

            MessageBox.Show("Analyze completed!");
        }
        private void VideoCapture1_OnVideoFrameBuffer(object sender, VideoFrameBufferEventArgs e)
        {
            try
            {
                if (tempBuffer == IntPtr.Zero)
                {
                    tempBuffer = Marshal.AllocCoTaskMem(e.Width * e.Height * 3);
                }

                if (e.StartTime < fragmentDuration)
                {
                    Marshal.Copy(e.Buffer, 0, tempBuffer, e.Buffer.Length);
                    VFPSearch.Process(tempBuffer, e.Width, e.Height, e.Width * 3, e.StartTime, ref searchLiveData);
                }
                else
                {
                    Dispatcher.BeginInvoke(new StopVideoDelegate(StopVideoDelegateMethod));
                }
            }
            catch
            {
            }
        }
        private void VideoCapture1_OnVideoFrameBuffer(object sender, VideoFrameBufferEventArgs e)
        {
            try
            {
                if (_tempBuffer == IntPtr.Zero)
                {
                    _tempBuffer = Marshal.AllocCoTaskMem(e.Frame.Stride * e.Frame.Height);
                }

                // live
                if (_searchLiveData == null)
                {
                    _searchLiveData = new FingerprintLiveData((int)(_fragmentDuration / 1000), DateTime.Now);
                    _fragmentCount++;
                }

                if (e.StartTime < _fragmentDuration * _fragmentCount)
                {
                    ImageHelper.CopyMemory(_tempBuffer, e.Frame.Data, e.Frame.DataSize);

                    // process frame to remove ignored areas
                    if (_ignoredAreas.Count > 0)
                    {
                        foreach (var area in _ignoredAreas)
                        {
                            if (area.Right > e.Frame.Width || area.Bottom > e.Frame.Height)
                            {
                                continue;
                            }

                            MFP.FillColor(_tempBuffer, e.Frame.Width, e.Frame.Height, area, 0);
                        }
                    }

                    VFPSearch.Process(_tempBuffer, e.Frame.Width, e.Frame.Height, e.Frame.Stride, e.StartTime, ref _searchLiveData.Data);
                }
                else
                {
                    _fingerprintQueue.Enqueue(_searchLiveData);

                    _searchLiveData = null;

                    Dispatcher.BeginInvoke(new ProcessVideoDelegate(ProcessVideoDelegateMethod));
                }

                // overlap
                if (e.StartTime < _fragmentDuration / 2)
                {
                    return;
                }

                if (_searchLiveOverlapData == null)
                {
                    _searchLiveOverlapData = new FingerprintLiveData((int)(_fragmentDuration / 1000), DateTime.Now);
                    _overlapFragmentCount++;
                }

                if (e.StartTime < _fragmentDuration * _overlapFragmentCount + _fragmentDuration / 2)
                {
                    ImageHelper.CopyMemory(_tempBuffer, e.Frame.Data, e.Frame.DataSize);
                    VFPSearch.Process(_tempBuffer, e.Frame.Width, e.Frame.Height, e.Frame.Stride, e.StartTime, ref _searchLiveOverlapData.Data);
                }
                else
                {
                    _fingerprintQueue.Enqueue(_searchLiveOverlapData);

                    _searchLiveOverlapData = null;

                    Dispatcher.BeginInvoke(new ProcessVideoDelegate(ProcessVideoDelegateMethod));
                }
            }
            catch
            {
            }
        }
        private void ProcessVideoDelegateMethod()
        {
            lock (_processingLock)
            {
                //if (VideoCapture1.Status == VFVideoCaptureStatus.Free)
                //{
                //    return;
                //}

                //// done. searching for fingerprints.
                //VideoCapture1.Stop();

                long n;
                FingerprintLiveData fingerprint = null;

                if (_fingerprintQueue.TryDequeue(out fingerprint))
                {
                    IntPtr p = VFPSearch.Build(out n, ref fingerprint.Data);

                    VFPFingerPrint fvp = new VFPFingerPrint()
                    {
                        Data             = new byte[n],
                        OriginalFilename = string.Empty
                    };

                    Marshal.Copy(p, fvp.Data, 0, (int)n);

                    foreach (var ad in _adVFPList)
                    {
                        List <int> positions;
                        bool       found = VFPAnalyzer.Search(ad, fvp, ad.Duration, (int)slDifference.Value, out positions, true);

                        if (found)
                        {
                            foreach (var pos in positions)
                            {
                                DateTime tm = fingerprint.StartTime.AddMilliseconds(pos * 1000);

                                bool duplicate = false;
                                foreach (var detectedAd in _results)
                                {
                                    long time = 0;

                                    if (detectedAd.Timestamp > tm)
                                    {
                                        time = (long)(detectedAd.Timestamp - tm).TotalMilliseconds;
                                    }
                                    else
                                    {
                                        time = (long)(tm - detectedAd.Timestamp).TotalMilliseconds;
                                    }

                                    if (time < 1000)
                                    {
                                        // duplicate
                                        duplicate = true;
                                        break;
                                    }
                                }

                                if (duplicate)
                                {
                                    break;
                                }

                                _results.Add(new DetectedAd(tm));
                                resultsView.Add(
                                    new ResultsViewModel()
                                {
                                    Sample      = ad.OriginalFilename,
                                    TimeStamp   = tm.ToString("HH:mm:ss.fff"),
                                    TimeStampMS = tm - new DateTime(1970, 1, 1)
                                });
                            }
                        }
                    }

                    fingerprint.Data.Free();
                    fingerprint.Dispose();
                }
            }
        }
        static void Main(string[] args)
        {
            var options = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Display the default usage information
                //Console.WriteLine(options.GetUsage());
                return;
            }

            if (!File.Exists(options.InputFile))
            {
                Console.WriteLine("Source file not found: " + options.InputFile + ".");
                return;
            }

            VFPAnalyzer.SetLicenseKey(options.LicenseKey);

            var engine = VFSimplePlayerEngine.LAV;

            if (!string.IsNullOrEmpty(options.Engine))
            {
                switch (options.Engine.Trim())
                {
                case "directshow":
                    engine = VFSimplePlayerEngine.DirectShow;
                    break;

                case "ffmpeg":
                    engine = VFSimplePlayerEngine.FFMPEG;
                    break;

                case "lav":
                    engine = VFSimplePlayerEngine.LAV;
                    break;
                }
            }

            Console.WriteLine("Analyzing...");

            var time        = DateTime.Now;
            var mediaPlayer = new SimplePlayer(null)
            {
                Filename       = options.InputFile,
                Video_Renderer = VFVideoRendererInternal.None
            };

            if (Path.GetExtension(options.InputFile)?.ToLowerInvariant() == ".wmv")
            {
                engine = VFSimplePlayerEngine.DirectShow;
            }

            mediaPlayer.Engine = engine;
            mediaPlayer.MaximalSpeedPlayback = true;

            //if (!string.IsNullOrEmpty(DebugDir))
            //{
            //    mediaPlayer.Debug_Dir = DebugDir;
            //    mediaPlayer.Debug_Mode = true;
            //}

            var mediaInfo = new MediaInfoReader
            {
                Filename = options.InputFile
            };

            mediaInfo.ReadFileInfo(true);


            VFPSearchData[] dataList = new VFPSearchData[options.Count];

            string error1 = string.Empty;
            bool   inUse  = true;
            bool   error  = false;

            // check for hang or something
            long frameNumber = 0;

            int sourceWidth  = 0;
            int sourceHeight = 0;

            int  index     = 0;
            long minusTime = 0;

            mediaPlayer.OnVideoFrame += delegate(object sender, SampleGrabberBufferCBEventArgs e)
            {
                if (!inUse)
                {
                    return;
                }

                long timestamp = (long)(e.SampleTime * 1000);
                timestamp -= minusTime;

                if (timestamp >= options.Duration)
                {
                    Console.WriteLine($"Started new fragment at {minusTime}");
                    index++;
                    minusTime  = (long)(e.SampleTime * 1000);
                    timestamp -= minusTime;
                }

                if (index >= options.Count)
                {
                    inUse = false;
                    return;
                }

                if (e.SampleTime < options.Duration * options.Count)
                {
                    frameNumber++;

                    sourceWidth  = e.Width;
                    sourceHeight = e.Height;

                    if (dataList[index] == null)
                    {
                        dataList[index] = new VFPSearchData(TimeSpan.FromMilliseconds(options.Duration));
                    }

                    VFPSearch.Process(
                        e.Buffer,
                        e.Width,
                        e.Height,
                        ImageHelper.GetStrideRGB24(e.Width),
                        TimeSpan.FromMilliseconds(timestamp),
                        ref dataList[index]);
                }
                else
                {
                    inUse = false;
                }
            };

            mediaPlayer.OnStop += delegate
            {
                inUse = false;
            };

            mediaPlayer.OnError += delegate(object sender, ErrorsEventArgs e)
            {
                if (e.Message.Contains("FULL"))
                {
                    return;
                }

                if (e.Level == DebugLevel.Error)
                {
                    error = true;
                    inUse = false;

                    error1 = e.Message + " | " + e.CallSite;
                }
            };

            mediaPlayer.Start();

            while (inUse && !error)
            {
                Thread.Sleep(100);
                Application.DoEvents();
            }

            mediaPlayer.Stop();

            Debug.WriteLine($"Processed {frameNumber} frame for file {options.InputFile}.");

            if (!error)
            {
                for (var i = 0; i < dataList.Length; i++)
                {
                    var data = dataList[i];
                    if (data == null)
                    {
                        break;
                    }

                    IntPtr p = VFPSearch.Build(out var n, ref data);

                    VFPFingerPrint fvp = new VFPFingerPrint()
                    {
                        // ReSharper disable once ExceptionNotDocumented
                        Data             = new byte[n],
                        OriginalFilename = options.InputFile,
                        OriginalDuration = TimeSpan.FromMilliseconds(options.Duration),
                        Duration         = TimeSpan.FromMilliseconds(options.Duration),
                        ID        = Guid.NewGuid(),
                        Width     = sourceWidth,
                        Height    = sourceHeight,
                        FrameRate = mediaInfo.Video_FrameRate(0)
                    };

                    Marshal.Copy(p, fvp.Data, 0, (int)n);

                    data.Free();

                    var newFilename = $"{options.InputFile}_segment{i}.vfsigx";
                    fvp.Save(newFilename);
                }
            }
            else
            {
                Debug.WriteLine($"Error: {error1}.");
            }

            mediaPlayer.Dispose();

            var elapsed = DateTime.Now - time;

            Console.WriteLine("Analyze finished. Elapsed time: " + elapsed.ToString("g"));
        }
        private void VideoCapture1_OnVideoFrameBuffer(object sender, SampleGrabberBufferCBEventArgs e)
        {
            try
            {
                if (_stopFlag)
                {
                    return;
                }

                Dispatcher.BeginInvoke(new NewFrameDelegate(NewFrameDelegateMethod), e);

                if (_tempBuffer == IntPtr.Zero)
                {
                    _tempBuffer = Marshal.AllocCoTaskMem(ImageHelper.GetStrideRGB24(e.Width) * e.Height);
                }

                // live
                if (_searchLiveData == null)
                {
                    _searchLiveData = new FingerprintLiveData(TimeSpan.FromMilliseconds(_fragmentDuration), DateTime.Now);
                    _fragmentCount++;
                }

                long timestamp = (long)(e.SampleTime * 1000);
                if (timestamp < _fragmentDuration * _fragmentCount)
                {
                    ImageHelper.CopyMemory(_tempBuffer, e.Buffer, e.BufferLen);

                    // process frame to remove ignored areas
                    if (_ignoredAreas.Count > 0)
                    {
                        foreach (var area in _ignoredAreas)
                        {
                            if (area.Right > e.Width || area.Bottom > e.Height)
                            {
                                continue;
                            }

                            MFP.FillColor(_tempBuffer, e.Width, e.Height, area, 0);
                        }
                    }

                    VFPSearch.Process(_tempBuffer, e.Width, e.Height, ImageHelper.GetStrideRGB24(e.Width), TimeSpan.FromMilliseconds(timestamp), ref _searchLiveData.Data);
                }
                else
                {
                    _fingerprintQueue.Enqueue(_searchLiveData);

                    _searchLiveData = null;

                    Dispatcher.BeginInvoke(new ProcessVideoDelegate(ProcessVideoDelegateMethod));
                }

                // overlap
                if (timestamp < _fragmentDuration / 2)
                {
                    return;
                }

                if (_searchLiveOverlapData == null)
                {
                    _searchLiveOverlapData = new FingerprintLiveData(TimeSpan.FromSeconds(_fragmentDuration), DateTime.Now);
                    _overlapFragmentCount++;
                }

                if (timestamp < _fragmentDuration * _overlapFragmentCount + _fragmentDuration / 2)
                {
                    ImageHelper.CopyMemory(_tempBuffer, e.Buffer, e.BufferLen);
                    VFPSearch.Process(_tempBuffer, e.Width, e.Height, ImageHelper.GetStrideRGB24(e.Width), TimeSpan.FromMilliseconds(timestamp), ref _searchLiveOverlapData.Data);
                }
                else
                {
                    _fingerprintQueue.Enqueue(_searchLiveOverlapData);

                    _searchLiveOverlapData = null;

                    Dispatcher.BeginInvoke(new ProcessVideoDelegate(ProcessVideoDelegateMethod));
                }
            }
            catch
            {
            }
        }