Пример #1
1
        private void ExtractAudio(string path)
        {
            FFMpegConverter converter = new FFMpegConverter();
            converter.ConvertProgress += (sender, args) =>
            {
                if (this.AudioExtractionProgressChanged != null)
                {

                    double progressPercent = args.Processed.TotalSeconds / args.TotalDuration.TotalSeconds * 100;
                    this.AudioExtractionProgressChanged(this, new ProgressEventArgs(progressPercent));
                }
            };
            //string filename = System.IO.Path.GetFileName(path); //testing
            //string dir = System.IO.Path.GetDirectoryName(this.SavePath); //testing
            //System.IO.File.Copy(path, System.IO.Path.Combine(dir, filename)); //testing
            string inputType;
            switch(Video.VideoType)
            {
                case VideoType.Mp4:
                    inputType = "mp4";
                    break;
                case VideoType.Flash:
                    inputType = "flv";
                    break;
                case VideoType.WebM:
                    inputType = "webm";
                    break;
                case VideoType.Mobile:
                    inputType = "3gp";
                    break;
                default:
                    throw new Exception("AudioDownloader.cs: VideoType unsupported");

            }
            NReco.VideoConverter.ConvertSettings cs = new ConvertSettings();
            switch(Video.AudioType)
            {
                case AudioType.Aac:
                    cs.CustomOutputArgs = "-vn -acodec copy ";
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp4", cs);
                    break;
                case AudioType.Mp3:
                    cs.CustomOutputArgs = "-vn -acodec copy ";
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp3", cs);
                    break;
                case AudioType.Vorbis:
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp3", cs);
                    break;
                case AudioType.Unknown:
                    throw new Exception("AudioDownloader.cs: AudioType Unknown");
            }

            //converter.ConvertMedia(path, this.SavePath, "mp3");
        }
Пример #2
0
        // Converts a folder of media files.
        //
        // \param path folder - The folder to be converted.
        // \param int toFormatcomboBoxIndex - The index of the format to be converted to.
        // \param int fromFormatcomboBoxIndex - The index of the format to be converted from.
        // \return bool - True if media file is converted correctly otherwise false.
        //
        public bool ConvertFolder(string folder, int toFormatcomboBoxIndex, int fromFormatcomboBoxIndex, bool deleteAll, bool subDir, ConvertSettings VideoSettings)
        {
            string[] mediaFiles = new string[1];
            bool result = false;
            if (subDir)
            {
                mediaFiles = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
            }
            else
            {
                mediaFiles = Directory.GetFiles(folder);
            }

            // For loop to go through each file.
            foreach (string file in mediaFiles)
            {
                // If the file is a media file and it is not already the correct format.
                if (((fromFormatcomboBoxIndex == 0 && IsMediaFile(file)) || (fromFormatcomboBoxIndex != 0 &&
                    Path.GetExtension(file) == mediaExtensions[fromFormatcomboBoxIndex - 1])) && Path.GetExtension(file) != mediaExtensions[toFormatcomboBoxIndex])
                {
                    result = ConvertFile(file, toFormatcomboBoxIndex, fromFormatcomboBoxIndex, deleteAll, VideoSettings);
                }
            }
            return result;
        }
Пример #3
0
        // Runs the process of conversion.
        //
        // \param path mediaFiles - The files to be converted.
        // \param int toFormatcomboBoxIndex - The index of the format to be converted to.
        // \param int fromFormatcomboBoxIndex - The index of the format to be converted from.
        //
        public void Process(string fileTextBox, string folderTextBox, int toFormatcomboBoxIndex, int fromFormatcomboBoxIndex, bool deleteAll, bool subDir, string VFramerate, string ASRate)
        {
            VideoConverterForm.threadStatus = true;

            // Determine how long is remaining and the current progress of the process.
            ffMpeg.ConvertProgress += (o, args) =>
            {
                VideoConverterForm.conversionProgress = (String.Format("Progress: {0:HH:mm:ss}/{1:HH:mm:ss}", new DateTime(args.Processed.Ticks), new DateTime(args.TotalDuration.Ticks)));
                VideoConverterForm.currentProgress = (int)((args.Processed.TotalSeconds / args.TotalDuration.TotalSeconds) * 100);
            };

            // Set the video settings for the conversion
            ConvertSettings VideoSettings = new ConvertSettings();
            if (VFramerate != "Default")
            {
                VideoSettings.VideoFrameRate = Convert.ToInt32(VFramerate);
            }
            if (ASRate != "Default")
            {
                VideoSettings.AudioSampleRate = Convert.ToInt32(ASRate);
            }

            // Determine if a folder or a file is to be converted
            if (!String.IsNullOrEmpty(folderTextBox))
            {
                ConvertFolder(folderTextBox, toFormatcomboBoxIndex, fromFormatcomboBoxIndex, deleteAll, subDir, VideoSettings);
            }
            else if(!String.IsNullOrEmpty(fileTextBox))
            {
                ConvertFile(fileTextBox, toFormatcomboBoxIndex, fromFormatcomboBoxIndex, deleteAll, VideoSettings);
            }

            VideoConverterForm.threadStatus = false;
        }
        private Task ConvertStream(HttpContent httpContent, Stream outputStream)
        {
            Task convertTask = new Task(() => {

                var convertSettings = new ConvertSettings {
                    CustomOutputArgs = "-map 0",
                    CustomInputArgs = "-vcodec h264"
                };

                var ffMpeg = new FFMpegConverter();
                ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                ffMpeg.LogReceived += FfMpeg_LogReceived;

                //var task = ffMpeg.ConvertLiveMedia(Format.h264, "C:\\Work\\Test\\converted.avi", Format.avi, convertSettings);
                var task = ffMpeg.ConvertLiveMedia(Format.h264, outputStream, Format.mpeg, convertSettings);

                task.Start();

                var ffmpegStream = new FFMPegStream(task);
                var copyTask = httpContent.CopyToAsync(ffmpegStream);
                copyTask.Wait();
                ffmpegStream.Close();

                task.Wait();

                //                ffMpeg.ConvertMedia(@"C:\Work\Test\MyHomeSecureNode\devices\test\video.h264", "C:\\Work\\Test\\converted.avi", Format.avi);

                outputStream.Close();
            });

            convertTask.Start();
            return convertTask;
        }
Пример #5
0
 public void TestWebmConversion()
 {
     Converter converter = new Converter();
     ConvertSettings VideoSettings = new ConvertSettings();
     bool result = converter.ConvertFile(currentPath + "\\SampleVideo.mp4", 7, 1, false, VideoSettings);
     Assert.AreEqual(true, result);
 }
Пример #6
0
        public void TestConversionFailure()
        {
            Converter       converter     = new Converter();
            ConvertSettings VideoSettings = new ConvertSettings();
            bool            result        = converter.ConvertFile(currentPath + "\\SampleVideo.docx", 1, 1, false, VideoSettings);

            Assert.AreEqual(false, result);
        }
Пример #7
0
        public static List <Panel> ToSAM_Panels(this Document document, ConvertSettings convertSettings)
        {
            if (document == null)
            {
                return(null);
            }

            return(ToSAM_Panels(document, null, convertSettings));
        }
Пример #8
0
        //FFMpegConverter conv = new FFMpegConverter();
        //ConvertSettings convSet = new ConvertSettings();

        private void ExeConv()
        {
            Debug.WriteLine(ConvertArgs);

            FFMpegConverter conv = new FFMpegConverter();

            conv.ConvertProgress += UpdateProgress;

            ConvertSettings convSet = new ConvertSettings();

            convSet.CustomOutputArgs = ConvertArgs;

            string outExtension = "";

            string outFormat = "";

            string inFormat = "";

            if (MkvOut)
            {
                outExtension = ".mkv";
                outFormat    = Format.matroska;
            }
            else if (Mp4Out)
            {
                outExtension = ".mp4";
                outFormat    = Format.mp4;
            }

            if (_filePathName.Contains("mkv"))
            {
                inFormat = Format.matroska;
            }
            else if (_filePathName.Contains("mp4"))
            {
                inFormat = Format.mp4;
            }

            string outName = OutFileName + outExtension;

            //ConsoleAllocator.ShowConsoleWindow();

            //ProgressVisible = Visibility.Visible;
            try
            {
                conv.ConvertMedia(_filePathName, inFormat, _filePathName.Remove(_filePathName.Length - FileName.Length) + outName, outFormat, convSet);
            }
            catch (FFMpegException e)
            {
                Debug.WriteLine(e.StackTrace);
            }

            StartVisible = Visibility.Visible;

            //ConsoleAllocator.HideConsoleWindow();
        }
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            int index = -1;
            int index_familyInstance = -1;

            index_familyInstance = Params.IndexOfOutputParam("familyInstance");
            if (index_familyInstance != -1)
            {
                dataAccess.SetData(index_familyInstance, null);
            }

            bool run = false;

            index = Params.IndexOfInputParam("_run");
            if (index == -1 || !dataAccess.GetData(index, ref run) || !run)
            {
                return;
            }

            ConvertSettings convertSettings = null;

            index = Params.IndexOfInputParam("_convertSettings_");
            if (index != -1)
            {
                dataAccess.GetData(index, ref convertSettings);
            }

            convertSettings = this.UpdateSolutionEndEventHandler(convertSettings);

            Aperture aperture = null;

            if (!dataAccess.GetData(0, ref aperture))
            {
                return;
            }

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            StartTransaction(document);

            Core.Revit.Modify.RemoveExisting(convertSettings, document, aperture);

            HostObject hostObject = Analytical.Revit.Query.HostObject(aperture, document);

            if (hostObject == null)
            {
                return;
            }

            FamilyInstance familyInstance_Revit = Analytical.Revit.Convert.ToRevit(aperture, document, hostObject, convertSettings);

            if (index_familyInstance != -1)
            {
                dataAccess.SetData(index_familyInstance, familyInstance_Revit);
            }
        }
Пример #10
0
        private void Init()
        {
            _age       = new FaceAge(AppId, AgeKey);
            _gender    = new FaceGender(AppId, GenderKey);
            _traking   = LocatorFactory.GetTrackingLocator(AppId, FtKey, _age, _gender) as FaceTracking;
            _detection = LocatorFactory.GetDetectionLocator(AppId, FdKey) as FaceDetection;
            _recognize = new FaceRecognize(AppId, FrKey);
            _processor = new FaceProcessor(_traking, _recognize);

            //init cache
            if (Directory.Exists(FaceLibraryPath))
            {
                var files = Directory.GetFiles(FaceLibraryPath);
                foreach (var file in files)
                {
                    var info = new FileInfo(file);
                    _cache.Add(info.Name.Replace(info.Extension, ""), File.ReadAllBytes(file));
                }
            }

            stride     = width * pixelSize;
            bufferSize = stride * height;

            _pImage = Marshal.AllocHGlobal(bufferSize);
            _image  = new Bitmap(width, height, stride, PixelFormat.Format24bppRgb, _pImage);

            var ffmpeg = new FFMpegConverter();

            outputStream = new MemoryStream();

            var setting =
                new ConvertSettings
            {
                CustomOutputArgs = "-s 1920x1080", //根据业务需求-r参数可以调整,取决于摄像机的FPS
            };                                     //-s 1920x1080 -q:v 2 -b:v 64k

            //-an -r 15 -pix_fmt bgr24 -updatefirst 1
            //task = ffmpeg.ConvertLiveMedia("rtsp://*****:*****@192.168.1.64:554/h264/ch1/main/av_stream", null,
            //    outputStream, Format.raw_video, setting);

            /*
             * USB摄像头捕获
             * 通过ffmpeg可以捕获USB摄像,如下代码所示。
             * 首先通过:ffmpeg -list_devices true -f dshow -i dummy命令,可以列出系统中存在的USB摄像设备(或通过控制面板的设备管理工具查看设备名称),例如在我电脑中叫USB2.0 PC CAMERA。
             * 然后根据捕获的分辨率,修改视频图形信息,包括width和height,一般像素大小不用修改,如果要参考设备支持的分辨率,可以使用:
             * ffmpeg -list_options true -f dshow -i video="USB2.0 PC CAMERA"命令
             */
            task = ffmpeg.ConvertLiveMedia("video=Logitech HD Webcam C270", "dshow",
                                           outputStream, Format.raw_video, setting);

            task.OutputDataReceived += DataReceived;
            task.Start();

            _renderTask = new Task(Render);
            _renderTask.Start();
        }
Пример #11
0
        public void TestConversionASRate()
        {
            Converter       converter     = new Converter();
            ConvertSettings VideoSettings = new ConvertSettings();

            VideoSettings.VideoFrameRate = Convert.ToInt32("8000");
            bool result = converter.ConvertFile(currentPath + "\\SampleVideo.mp4", 1, 1, false, VideoSettings);

            Assert.AreEqual(true, result);
        }
Пример #12
0
        public FFMPEGConvert()
        {
            ffMpeg         = new FFMpegConverter();
            ffMpegSettings = new ConvertSettings();
            ffMpegSettings.SetVideoFrameSize(880, 880);
            ffMpegSettings.VideoCodec       = "h264";
            ffMpegSettings.CustomOutputArgs = "-map 0:v -color_range 1 -preset fast -tune animation -profile:v high -vf \"format=yuv420p, setdar=4:3\"";
            ffMpegSettings.VideoFrameRate   = 30;

            //ffMpegSettings.CustomOutputArgs = "-c:v libx264rgb -preset veryslow -tune ssim -s 680x680 -vf setdar=1:1 -pix_fmt bgr0 -r 25";
        }
Пример #13
0
        private void Converter(string directory)
        {
            var             ffmpeg          = new FFMpegConverter();
            ConvertSettings convertSettings = new ConvertSettings()
            {
                CustomOutputArgs = "-s 320x240 -b:v 128k -bufsize 128k "
            };
            var fileOutput = String.Concat(System.IO.Path.GetDirectoryName(directory), "/", System.IO.Path.GetFileNameWithoutExtension(directory), "2.mp4");

            ffmpeg.ConvertMedia(directory, Format.mov, fileOutput, Format.mp4, convertSettings);
        }
Пример #14
0
        public void TestDeleteConversion()
        {
            Converter       converter     = new Converter();
            ConvertSettings VideoSettings = new ConvertSettings();

            converter.ConvertFile(currentPath + "//SampleVideo.mp4", 1, 1, false, VideoSettings);
            bool result = converter.ConvertFile(currentPath + "//SampleVideo.mkv", 0, 2, true, VideoSettings);

            Assert.AreEqual(true, result);
            Assert.AreEqual(false, File.Exists(currentPath + "//SampleVideo.mkv"));
        }
Пример #15
0
        static void ConvertMedia()
        {
            FFMpegConverter ffMpeg  = new FFMpegConverter();
            ConvertSettings setting = new ConvertSettings();

            setting.CustomOutputArgs = " -threads 2";   // 以两个线程进行运行,加快处理的速度
            for (int i = 0; i < 100; i++)
            {
                ffMpeg.ConvertMedia("1.amr", "2.mp3", "MP3");  // 将h5不支持的视频转换为支持的视频
                Console.WriteLine(i);
            }
        }
        public static void Run()
        {
            var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey);

            var apiInstance = new ConvertApi(configuration);

            try
            {
                // convert settings
                var settings = new ConvertSettings
                {
                    StorageName = Common.MyStorage,
                    FilePath    = "conversions/password-protected.docx",
                    Format      = "pdf",
                    LoadOptions = new DocxLoadOptions()
                    {
                        Password = "******"
                    },
                    ConvertOptions = new PdfConvertOptions()
                    {
                        BookmarksOutlineLevel = 1,
                        CenterWindow          = true,
                        CompressImages        = false,
                        DisplayDocTitle       = true,
                        Dpi = 1024,
                        ExpandedOutlineLevels = 1,
                        FitWindow             = false,
                        FromPage              = 1,
                        Grayscale             = false,
                        HeadingsOutlineLevels = 1,
                        ImageQuality          = 100,
                        Linearize             = false,
                        MarginTop             = 5,
                        MarginLeft            = 5,
                        Password              = "******",
                        UnembedFonts          = true,
                        RemoveUnusedStreams   = true,
                        RemoveUnusedObjects   = true,
                        RemovePdfaCompliance  = false,
                        Height = 1024
                    },
                    OutputPath = null                     // set OutputPath as null will result the output as document IOStream
                };

                // convert to specified format
                Stream response = apiInstance.ConvertDocumentDownload(new ConvertDocumentRequest(settings));
                Console.WriteLine("Document conveted successfully: " + response.Length.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling ConvertApi: " + e.Message);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="resolution">请使用FrameSize常量</param>
 /// <param name="maxDuration"></param>
 public FFMpegScreenCapture(string resolution, float maxDuration)
 {
     _converter = new FFMpegConverter();
     _settings  = new ConvertSettings();
     if (maxDuration > 0)
     {
         _settings.MaxDuration = maxDuration;
     }
     _settings.VideoFrameSize  = resolution;
     _settings.VideoFrameRate  = 30;
     _settings.CustomInputArgs = " -draw_mouse 1 "; //绘制鼠标
 }
Пример #18
0
        public static IRevitInstance ToSAM(this FamilyInstance familyInstance, ConvertSettings convertSettings)
        {
            if (familyInstance == null || !familyInstance.IsValidObject)
            {
                return(null);
            }

            IRevitInstance result = convertSettings?.GetObject <IRevitInstance>(familyInstance.Id);

            if (result != null)
            {
                return(result);
            }

            Document document = familyInstance.Document;

            if (document == null)
            {
                return(result);
            }

            ElementType elementType = document.GetElement(familyInstance.GetTypeId()) as ElementType;

            if (elementType == null)
            {
                return(null);
            }

            RevitType revitType = elementType.ToSAM(convertSettings);

            if (revitType == null)
            {
                return(null);
            }

            if (revitType is RevitType3D)
            {
                result = new RevitInstance3D((RevitType3D)revitType, familyInstance.ToSAM_Geometries <Spatial.ISAMGeometry3D>());
            }
            else if (revitType is RevitType2D)
            {
                result = new RevitInstance2D((RevitType2D)revitType, familyInstance.ToSAM_Geometries <Planar.ISAMGeometry2D>());
            }

            if (result != null)
            {
                result.UpdateParameterSets(familyInstance, ActiveSetting.Setting.GetValue <TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));
                convertSettings?.Add(familyInstance.Id, result);
            }

            return(result);
        }
Пример #19
0
        public static List <SAM.Analytical.Panel> FromRevitLinkInstance(Revit.Elements.Element revitLinkInstance)
        {
            RevitLinkInstance revitLinkInstance_Revit = revitLinkInstance.InternalElement as RevitLinkInstance;

            if (revitLinkInstance_Revit == null)
            {
                return(null);
            }

            ConvertSettings convertSettings = new ConvertSettings(true, true, true);

            return(SAM.Analytical.Revit.Convert.ToSAM_Panels(revitLinkInstance_Revit, convertSettings));
        }
Пример #20
0
        public static Material ToSAM(this Autodesk.Revit.DB.Material material, ConvertSettings convertSettings)
        {
            Material result = Core.Revit.Convert.ToSAM(material, convertSettings);

            if (result == null)
            {
                return(result);
            }

            result.UpdateParameterSets(material, ActiveSetting.Setting.GetValue <TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

            return(result);
        }
Пример #21
0
        public static FamilySymbol ToRevit(this TagType tagType, Document document, ConvertSettings convertSettings)
        {
            if (tagType == null || document == null)
            {
                return(null);
            }

            FamilySymbol result = null;

            result = Core.Revit.Query.Element <FamilySymbol>(document, tagType, true);

            return(result);
        }
Пример #22
0
        private Task ConvertStream(/*Stream input, */ Stream outputStream)
        {
            Task convertTask = new Task(() => {
                try
                {
                    var convertSettings = new ConvertSettings
                    {
                        CustomOutputArgs = "-map 0",
                        CustomInputArgs  = "-vcodec h264"
                    };
                    //convertSettings.SetVideoFrameSize(360, 360);
                    var ffMpeg              = new FFMpegConverter();
                    ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                    ffMpeg.LogReceived     += FfMpeg_LogReceived;

                    //task = ffMpeg.ConvertLiveMedia(Format.h264, outStream, Format.mjpeg, convertSettings);
                    //task = ffMpeg.ConvertLiveMedia(inStream, Format.h264, outStream, Format.mjpeg, convertSettings);
                    //            task = ffMpeg.ConvertLiveMedia(inStream, Format.h264, $@"Files\video2.mpeg", Format.mjpeg, convertSettings);
                    //            task.Start();
                    //ffMpeg.ConvertMedia($@"Files\video.mpeg4", Format.h264, $@"Files\video3.mpeg", Format.mjpeg, convertSettings);
                    //var task = ffMpeg.ConvertLiveMedia(Format.h264, "C:\\Work\\Test\\converted.avi", Format.avi, convertSettings);
                    //ffMpeg.ConvertMedia($@"Files\video.mpeg4", $@"Files\video2.flv", Format.flv);
                    //var setting = new NReco.VideoConverter.ConvertSettings();
                    //setting.SetVideoFrameSize(360, 360);
                    //setting.VideoCodec = "h264";
                    //ffMpeg.ConvertMedia($@"Files\video.mpeg4", Format.h264, $@"Files\video2.mjpeg", Format.mjpeg, setting);
                    //task.Stop();
                    var task = ffMpeg.ConvertLiveMedia(Format.h264, outputStream, Format.mjpeg, convertSettings);

                    task.Start();

                    ffinStream = new FFMPegStream(task);
                    //var copyTask = input.CopyToAsync(ffmpegStream);
                    //copyTask.Wait();
                    //ffmpegStream.Close();

                    task.Wait();
                    //ffMpeg.ConvertMedia(@"C:\Work\Test\MyHomeSecureNode\devices\test\video.h264", "C:\\Work\\Test\\converted.avi", Format.avi);

                    outputStream.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            });

            convertTask.Start();
            return(convertTask);
        }
        public AnimationViewModel(IAssetRepo assetRepo,
                                  IRegionManager regionManager, IEventAggregator eventAggregator,
                                  IDialogCoordinator dialogService, IGameConfigSvc gameConfig)
        {
            //< add key = "assets:AssetLocation" value = "..\asset" />
            var assetLocation = ConfigurationManager.AppSettings["assets:AssetLocation"].ToString();

            _regionManager   = regionManager;
            _dialogService   = dialogService;
            _gameConfig      = gameConfig;
            _assetRepo       = assetRepo;
            _eventAggregator = eventAggregator;

            ConvertSettings = new ConvertSettings();

            _assetRepo.DeserializeAssets(assetLocation);

            Animations = new ListCollectionView(_assetRepo.Animation.Animations);
            Animations.MoveCurrentTo("");
            Animations.CurrentChanged += Animations_CurrentChanged;

            Videos = new ListCollectionView(_assetRepo.Animation.Videos);
            Videos.MoveCurrentTo("");
            Videos.CurrentChanged += Videos_CurrentChanged;;

            NavigateCommand = new DelegateCommand <string>(x =>
            {
                _regionManager.RequestNavigate(RegionNames.ContentRegion, x);
            });

            CloseAllPendingFileDropCommand = new DelegateCommand(async() =>
            {
                //cancelPending = true;

                await _dialogService.HideMetroDialogAsync(this, customDialog);

                // cancelPending = false;
            });

            SaveCommand = new DelegateCommand(async() =>
            {
                await SaveDroppedFileAsync();
            });

            _eventAggregator.GetEvent <CloseCustomDialogAnimsEvent>().Subscribe(x =>
            {
                CloseDialogs();
            });
        }
Пример #24
0
        /// <summary>
        /// Creates Panel from Revit Element
        /// </summary>
        /// <param name="element">Revit Element</param>
        /// <search>FromRevit, SAM Analytical Panel</search>
        public static IEnumerable <object> FromRevit(Revit.Elements.Element element)
        {
            TransactionManager.Instance.ForceCloseTransaction();

            ConvertSettings convertSettings = new ConvertSettings(true, true, true);

            IEnumerable <SAM.Core.SAMObject> sAMObjects = SAM.Analytical.Revit.Convert.ToSAM(element.InternalElement, convertSettings);

            if (sAMObjects == null)
            {
                return(null);
            }

            return(sAMObjects);
        }
Пример #25
0
        public static IEnumerable <SAM.Analytical.Space> FromRevitLinkInstance(Revit.Elements.Element revitLinkInstance, bool fromRooms = true)
        {
            TransactionManager.Instance.ForceCloseTransaction();

            RevitLinkInstance revitLinkInstance_Revit = revitLinkInstance.InternalElement as RevitLinkInstance;

            if (revitLinkInstance_Revit == null)
            {
                return(null);
            }

            ConvertSettings convertSettings = new ConvertSettings(true, true, true);

            return(SAM.Analytical.Revit.Convert.ToSAM_Spaces(revitLinkInstance_Revit, convertSettings, fromRooms));
        }
Пример #26
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            dataAccess.SetData(1, false);

            bool run = false;

            if (!dataAccess.GetData(0, ref run) || !run)
            {
                return;
            }

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            AnalyticalModel analyticalModel = null;


            using (Transaction transaction = new Transaction(document, "GetAnalyticalModel"))
            {
                FailureHandlingOptions failureHandlingOptions = transaction.GetFailureHandlingOptions();
                failureHandlingOptions.SetFailuresPreprocessor(new WarningSwallower());
                transaction.SetFailureHandlingOptions(failureHandlingOptions);

                transaction.Start();

                ConvertSettings convertSettings = new ConvertSettings(true, true, true);
                try
                {
                    analyticalModel = Analytical.Revit.Convert.ToSAM_AnalyticalModel(document, convertSettings);
                }
                catch (Exception exception)
                {
                    if (exception.Message.Contains("spatial bounding elements"))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Check your setting in Export Category: Rooms/Spaces in Export gbXML settings");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, exception.Message);
                    }
                }


                transaction.RollBack();
            }

            dataAccess.SetData(0, new GooAnalyticalModel(analyticalModel));
            dataAccess.SetData(1, analyticalModel != null);
        }
Пример #27
0
        /// <summary>
        /// 截图指定秒数的一张图指定高宽的图片
        /// </summary>
        /// <param name="inputFilePath">文件路径</param>
        /// <param name="outputFilePath">图片保存路径</param>
        /// <param name="startScreenSecond">截图秒数</param>
        /// <param name="videoFrameSize">截图宽高 格式:200x300</param>
        public void Screenshot(string inputFilePath, string outputFilePath, double startScreenSecond, string videoFrameSize)
        {
            var setting = new ConvertSettings();

            setting.VideoFrameCount = new int?(1);
            setting.MaxDuration     = new float?(1f);
            setting.Seek            = (float)startScreenSecond;

            if (!string.IsNullOrEmpty(videoFrameSize))
            {
                setting.VideoFrameSize = videoFrameSize;
            }


            this._ffMpeg.ConvertMedia(inputFilePath, null, outputFilePath, Format.mjpeg, setting);
        }
Пример #28
0
        public static void Run()
        {
            try
            {
                // Create necessary API instances
                var apiInstance = new ConvertApi(Constants.GetConfig());

                // Prepare convert settings
                var settings = new ConvertSettings
                {
                    StorageName = Constants.MyStorage,
                    FilePath    = "WordProcessing/password-protected.docx",
                    Format      = "pdf",
                    LoadOptions = new DocxLoadOptions {
                        Password = "******"
                    },
                    ConvertOptions = new PdfConvertOptions
                    {
                        CenterWindow         = true,
                        CompressImages       = false,
                        DisplayDocTitle      = true,
                        Dpi                  = 1024,
                        FitWindow            = false,
                        FromPage             = 1,
                        Grayscale            = false,
                        ImageQuality         = 100,
                        Linearize            = false,
                        MarginTop            = 5,
                        MarginLeft           = 5,
                        Password             = "******",
                        UnembedFonts         = true,
                        RemoveUnusedStreams  = true,
                        RemoveUnusedObjects  = true,
                        RemovePdfaCompliance = false
                    },
                    OutputPath = "converted"
                };

                // Convert to specified format
                var response = apiInstance.ConvertDocument(new ConvertDocumentRequest(settings));
                Console.WriteLine("Document converted successfully: " + response[0].Url);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
Пример #29
0
        /// <summary>
        /// تبدیل فایل ویدیویی
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task ConvertVideoAsync(string filePath)
        {
            var ffMpegConverter = new FFMpegConverter();
            var convertSettings = new ConvertSettings
            {
                AudioCodec       = "copy", // or audio codec for re-encoding
                VideoCodec       = "copy", // or video codec for re-encoding
                CustomOutputArgs = " -map 0:v:0 -map 1:a:0 "
            };
            var input = new[]
            {
                new FFMpegInput($"{Path.GetFileName(filePath)}")
            };
            var output = $"{Path.GetFileNameWithoutExtension(filePath)}_Converted.mp4";

            ffMpegConverter.ConvertMedia(input, output, null, convertSettings);
        }
Пример #30
0
        private static void Main(string[] args)
        {
            //File.WriteAllBytes("bc",Convert.FromBase64String("vg23gr25u7ov2fjema8b0s5sb5as2ym5"));
            //var fvd=parseFlashVars(File.ReadAllText("phex0.js",Encoding.GetEncoding(1251)));
            vc = new FFMpegConverter();
            vc.FFMpegExeName  = "c:\\progra~1\\Audacity\\FFmpeg\\ffmpeg.exe";
            vc.FFMpegToolPath = "c:\\progra~1\\Audacity\\FFmpeg";
            vcs = new ConvertSettings();
            vc.ConvertProgress += new EventHandler <ConvertProgressEventArgs>(vc_ConvertProgress);
            System.Diagnostics.Debug.WriteLine(args[1]);
            string bufl = Path.GetExtension(args[1]);

            bufl = args[1].Replace(bufl, "_0" + bufl);
            if (File.Exists(bufl))
            {
                File.Delete(bufl);
            }
            File.Copy(args[1], bufl);
            string[] fnl = File.ReadAllLines(args[1], Encoding.GetEncoding(1251));
            fdI = Path.GetDirectoryName(fnl[0]);
            fdO = fdI;
            fnO = fdI + "\\" + Path.GetFileNameWithoutExtension(fnl[0]);
            fmt = "mp4";
            switch (args[0])
            {
            case "flv": xFLV(fnl); break;

            case "cbu": xCBU(fnl); break;

            case "ac3": vcs.VideoCodec = "copy";     vcs.AudioBitRate = "640k"; vcs.AudioCodec = "ac3"; xEnc(fnl); break;

            case "cat": xCAT(fnl); break;

            case "ogg": vcs.VideoBitRate = "2400k"; vcs.VideoCodec = "libtheora"; vcs.AudioBitRate = "192k"; vcs.AudioCodec = "libvorbis"; xEnc(fnl); break;

            case "av1": vcs.VideoBitRate = "2400k"; vcs.VideoCodec = "libaom_av1"; vcs.AudioBitRate = "192k"; vcs.AudioCodec = "libopus"; fmt = "ogv"; xEnc(fnl); break;

            case "m3v": vcs.VideoCodec = "mpeg4"; vcs.AudioCodec = "libmp3lame"; vcs.CustomOutputArgs = "-qscale 9"; xEnc(fnl); break;

            case "m4v": vcs.VideoCodec = "libx264"; vcs.AudioCodec = "aac"; vcs.CustomOutputArgs = "-crf 30"; xEnc(fnl); break;

            case "m5v": vcs.VideoCodec = "libx265"; vcs.AudioCodec = "aac"; vcs.CustomOutputArgs = "-crf 22"; xEnc(fnl); break;

            case "cpy": vcs.VideoCodec = "copy"; vcs.AudioCodec = "copy"; vcs.CustomInputArgs = "-allowed_extensions ALL"; xEnc(fnl); break;
            }
        }
Пример #31
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            int index = -1;

            bool run = false;

            index = Params.IndexOfInputParam("_run");
            if (index == -1 || !dataAccess.GetData(index, ref run) || !run)
            {
                return;
            }

            ConvertSettings convertSettings = null;

            index = Params.IndexOfInputParam("_convertSettings_");
            if (index != -1)
            {
                dataAccess.GetData(index, ref convertSettings);
            }

            if (convertSettings == null)
            {
                convertSettings = Core.Revit.Query.ConvertSettings();
            }

            Level level = null;

            index = Params.IndexOfInputParam("_level");
            if (index == -1 || !dataAccess.GetData(index, ref level))
            {
                return;
            }

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            StartTransaction(document);

            Autodesk.Revit.DB.Level level_Revit = Architectural.Revit.Convert.ToRevit(level, document, convertSettings);

            index = Params.IndexOfOutputParam("level");
            if (index != -1)
            {
                dataAccess.SetData(index, level_Revit);
            }
        }
Пример #32
0
        public static RevitInstance3D ToSAM(this WallSweep wallSweep, ConvertSettings convertSettings)
        {
            if (wallSweep == null || !wallSweep.IsValidObject)
            {
                return(null);
            }

            RevitInstance3D result = convertSettings?.GetObject <RevitInstance3D>(wallSweep.Id);

            if (result != null)
            {
                return(result);
            }

            Document document = wallSweep.Document;

            if (document == null)
            {
                return(result);
            }

            ElementType elementType = document.GetElement(wallSweep.GetTypeId()) as ElementType;

            if (elementType == null)
            {
                return(null);
            }

            RevitType3D revitType3D = elementType.ToSAM(convertSettings) as RevitType3D;

            if (revitType3D == null)
            {
                return(null);
            }

            result = new RevitInstance3D(revitType3D, wallSweep.ToSAM_Geometries <Spatial.ISAMGeometry3D>());

            if (result != null)
            {
                result.UpdateParameterSets(elementType, ActiveSetting.Setting.GetValue <TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));
                convertSettings?.Add(elementType.Id, result);
            }

            return(result);
        }
Пример #33
0
        public static Space ToSAM(this EnergyAnalysisSpace energyAnalysisSpace, ConvertSettings convertSettings)
        {
            if (energyAnalysisSpace == null)
            {
                return(null);
            }

            Document document = energyAnalysisSpace.Document;

            SpatialElement spatialElement = Core.Revit.Query.Element(document, energyAnalysisSpace.CADObjectUniqueId) as SpatialElement;

            if (spatialElement == null)
            {
                return(null);
            }

            return(ToSAM(spatialElement, convertSettings));
        }
Пример #34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resolution">请使用FrameSize常量</param>
        /// <param name="maxDuration"></param>
        /// <param name="quality">画质,值越小画质越好、体积越大,0的画质最高,但是体积也最大</param>
        public FLVScreenCapture(string resolution, float maxDuration, int quality, string audioDevice, string saveFileName)
        {
            _converter = new FFMpegConverter();
            _settings  = new ConvertSettings();

            if (maxDuration > 0)
            {
                _settings.MaxDuration = maxDuration;
            }

            _settings.VideoFrameSize   = resolution;
            _settings.VideoFrameRate   = 25;
            _settings.AudioDevice      = audioDevice;
            _settings.CustomInputArgs  = " -draw_mouse 1 ";
            _settings.CustomOutputArgs = " -qscale " + quality;

            _saveFileName = saveFileName;
        }
Пример #35
0
        public void ConvertDocumentDownloadTest(TestFile testFile, string targetFormat, ConvertOptions convertOptions)
        {
            var format   = targetFormat;
            var options  = convertOptions;
            var filePath = testFile.FullName;

            var settings = new ConvertSettings
            {
                FilePath       = filePath,
                Format         = format,
                ConvertOptions = options
            };

            var result = ConvertApi.ConvertDocumentDownload(new ConvertDocumentRequest(settings));

            Assert.IsNotNull(result);
            Assert.Greater(result.Length, 0);
        }
Пример #36
0
        // Converts a single media file.
        //
        // \param path file - The file to be converted.
        // \param int toFormatcomboBoxIndex - The index of the format to be converted to.
        // \param int fromFormatcomboBoxIndex - The index of the format to be converted from.
        // \return bool - True if media file is converted correctly otherwise false.
        //
        public bool ConvertFile(string file, int toFormatcomboBoxIndex, int fromFormatcomboBoxIndex, bool deleteAll, ConvertSettings VideoSettings)
        {
            // The array of supported file formats
            string[] formats = {
                                        Format.mp4, Format.matroska, Format.avi,
                                        Format.mov, Format.mpeg, Format.ogg,
                                        Format.flv,Format.webm
                                    };

            // If the file is a media file and it is not already the correct format.
            if (((fromFormatcomboBoxIndex == 0 && IsMediaFile(file)) || (fromFormatcomboBoxIndex != 0 &&
                Path.GetExtension(file) == mediaExtensions[fromFormatcomboBoxIndex - 1])) && Path.GetExtension(file) != mediaExtensions[toFormatcomboBoxIndex])
            {
                // Determine which file is currently being processed.
                VideoConverterForm.currentFile = "Currently Processing: " + Path.GetFileName(file);

                // Create the new file name.
                string newFile = file.Substring(0, file.Length - Path.GetExtension(file).Length) + mediaExtensions[toFormatcomboBoxIndex];
                string format = formats[toFormatcomboBoxIndex];
                string oldFormat = Path.GetExtension(file).Substring(1);
                if (oldFormat == "mkv")
                {
                    oldFormat = Format.matroska;
                }

                try
                {
                    // Converts the file to the selected format.
                    ffMpeg.ConvertMedia(file, oldFormat, newFile, format, VideoSettings);

                    // Deletes the files if the checkbox is checked.
                    if (deleteAll)
                    {
                        File.Delete(file);
                    }

                    return true;
                }
                catch
                {
                    MessageBox.Show("Error Detected in File " + Path.GetFileName(file) + " Skipping");
                    if (File.Exists(newFile))
                    {
                        File.Delete(newFile);
                    }
                    return false;
                }
            }
            return false;
        }
Пример #37
0
 public void TestConversionASRate()
 {
     Converter converter = new Converter();
     ConvertSettings VideoSettings = new ConvertSettings();
     VideoSettings.VideoFrameRate = Convert.ToInt32("8000");
     bool result = converter.ConvertFile(currentPath + "\\SampleVideo.mp4", 1, 1, false, VideoSettings);
     Assert.AreEqual(true, result);
 }
Пример #38
0
 public void TestSubdirConversion()
 {
     Converter converter = new Converter();
     ConvertSettings VideoSettings = new ConvertSettings();
     bool result = converter.ConvertFolder(currentPath + "../", 1, 1, false, true, VideoSettings);
     Assert.AreEqual(true, result);
 }
Пример #39
0
 public void TestDeleteConversion()
 {
     Converter converter = new Converter();
     ConvertSettings VideoSettings = new ConvertSettings();
     converter.ConvertFile(currentPath + "//SampleVideo.mp4", 1, 1, false, VideoSettings);
     bool result = converter.ConvertFile(currentPath + "//SampleVideo.mkv", 0, 2, true, VideoSettings);
     Assert.AreEqual(true, result);
     Assert.AreEqual(false, File.Exists(currentPath + "//SampleVideo.mkv"));
 }
Пример #40
0
 public void TestConversionFailure()
 {
     Converter converter = new Converter();
     ConvertSettings VideoSettings = new ConvertSettings();
     bool result = converter.ConvertFile(currentPath + "\\SampleVideo.docx", 1, 1, false, VideoSettings);
     Assert.AreEqual(false, result);
 }
Пример #41
-1
        /// <summary>
        /// Run Convert Worker
        /// </summary>
        /// <param name="inputPath">Input file path</param>
        /// <param name="outputPath">Output file path</param>
        /// <param name="format">Video file format</param>
        /// <param name="arguments">Arguments for ffmpeg</param>
        /// <param name="passNumber">Pass number</param>
        private void RunConvertWorker(string inputPath, string outputPath, string format, string[] arguments, int passNumber)
        {
            int passCount = arguments.Length;
            if (passNumber > passCount - 1) return;

            string currentPassArguments = arguments[passNumber];
            string currentOutputPath = outputPath;
            string toolTipText = "Выполняется конвертирование";

            if (passCount > 1)
            {
                toolTipText = string.Format("Выполняется проход {0} из {1}", (passNumber + 1), passCount);
                if (passNumber < (passCount - 1))
                    currentOutputPath = "NUL";
            }

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.ProgressChanged += new ProgressChangedEventHandler(delegate (object sender, ProgressChangedEventArgs e)
            {
                int progressPercentage = Math.Min(100, e.ProgressPercentage);
                if (progressPercentage > 0)
                {
                    ProgressBarPercentage(progressPercentage);
                }
                showToolTip(toolTipText);
            });
            bw.DoWork += delegate (object sender, DoWorkEventArgs e)
            {
                try
                {
                    FFMpegConverter ffMpeg = new FFMpegConverter();
                    ffMpeg.FFMpegProcessPriority = ProcessPriorityClass.Idle;
                    ffMpeg.FFMpegToolPath = Path.Combine(Environment.CurrentDirectory, "Binaries");

                    ConvertSettings settings = new ConvertSettings();
                    settings.CustomOutputArgs = currentPassArguments;

                    ffMpeg.ConvertProgress += delegate (object sendertwo, ConvertProgressEventArgs etwo)
                    {
                        int perc = (int)((etwo.Processed.TotalMilliseconds / etwo.TotalDuration.TotalMilliseconds) * 100);
                        bw.ReportProgress(perc);
                        if (bw.CancellationPending)
                            ffMpeg.Stop();
                    };

                    ffMpeg.ConvertMedia(inputPath, null, currentOutputPath, format, settings);
                }
                catch (Exception ex)
                {
                    if (!ex.Message.StartsWith("Exiting normally") && !closeApp)
                        MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                    return;
                }
            };
            bw.RunWorkerCompleted += delegate (object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    converting = false;

                    // reset pbar
                    ResetProgressBar();
                    toolStripProgressBar.Visible = false;

                    buttonGo.Text = buttonGoText;
                    buttonGo.Enabled = true;

                    showToolTip("Конвертирование отменено");

                    if (closeApp)
                        Application.Exit();

                    return;
                }

                // run next pass
                if (passCount > 1 && passNumber < (passCount - 1))
                {
                    RunConvertWorker(inputPath, outputPath, format, arguments, passNumber + 1);
                }
                else
                {
                    converting = false;

                    // 100% done!
                    ProgressBarPercentage(100);

                    buttonGo.Text = buttonGoText;
                    buttonGo.Enabled = true;

                    showToolTip("Готово");
                    if (MessageBox.Show("Открыть полученный файл?", "Конвертирование выполнено", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            Process.Start(outputPath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            };

            ResetProgressBar();
            toolStripProgressBar.Visible = true;

            buttonGo.Text = "Отменить";
            buttonGo.Enabled = true;

            converting = true;
            showToolTip(toolTipText);
            bw.RunWorkerAsync();
        }