Пример #1
0
        /// <summary>
        /// Converts object to a collection of key-value parameters
        /// where key is a property name and value is a property value.
        /// </summary>
        /// <param name="dto">Plain data transfer object to be converted.</param>
        /// <param name="convertOptions">
        /// Specific options applied during conversion. <seealso cref="ConvertOptions"/>.
        /// </param>
        /// <returns>Collection of <see cref="KeyValuePair"/> items.</returns>
        public static IEnumerable <KeyValuePair <string, object> > ConvertDtoToDictionaryOfParameters(
            this object dto,
            ConvertOptions convertOptions = ConvertOptions.All)
        {
            var parameters = dto.ConvertToKeyValuePairCollection();

            if ((convertOptions & ConvertOptions.ExcludeNulls) != 0)
            {
                parameters = parameters.Where(item => item.Value != null);
            }

            if ((convertOptions & ConvertOptions.ExcludeEmptyStrings) != 0)
            {
                parameters = parameters.Where(item => !(item.Value is string value && string.IsNullOrEmpty(value)));
            }

            var resultParams = new Dictionary <string, object>();

            foreach (var(key, value) in parameters)
            {
                var resultValue = value;
                if ((convertOptions & ConvertOptions.ConvertDatesToIso8601) != 0 && value is DateTime dateTime)
                {
                    resultValue = dateTime.ToString(Constants.WebFormats.Iso8601DateFormat);
                }

                resultParams[key] = resultValue;
            }

            return(resultParams);
        }
Пример #2
0
        public void TestVerifyConvertOptions()
        {
            Console.WriteLine("TESTING: A message about not using --portrait and --landscape together is expected.");
            var options = new ConvertOptions()
            {
                UsePortrait  = true,
                UseLandscape = true,
                // The next two merely prevent a spurious warning if the enviroment variables are not set.
                UploadUser     = "******",
                UploadPassword = "******"
            };
            var convert = new ConvertFromEpub(options);
            //SUT
            var result = convert.VerifyOptions();

            Assert.That(result, Is.False);

            convert._options.UsePortrait  = false;
            convert._options.UseLandscape = false;
            result = convert.VerifyOptions();
            Assert.That(result, Is.True);

            convert._options.UsePortrait  = true;
            convert._options.UseLandscape = false;
            result = convert.VerifyOptions();
            Assert.That(result, Is.True);

            convert._options.UsePortrait  = false;
            convert._options.UseLandscape = true;
            result = convert.VerifyOptions();
            Assert.That(result, Is.True);
        }
        public async Task <IActionResult> FooterTest()
        {
            var kv = new Dictionary <string, string>
            {
                { "username", "Veaer" },
                { "age", "20" },
                { "url", "google.com" }
            };

            var options = new ConvertOptions
            {
                FooterHtml   = "http://localhost/footer.html",
                Replacements = kv
            };

            _generatePdf.SetConvertOptions(options);

            var data = new TestData
            {
                Text   = "This is a test",
                Number = 123456
            };

            var pdf = await _generatePdf.GetByteArray("Views/Test.cshtml", data);

            var pdfStream = new System.IO.MemoryStream();

            pdfStream.Write(pdf, 0, pdf.Length);
            pdfStream.Position = 0;
            return(new FileStreamResult(pdfStream, "application/pdf"));
        }
Пример #4
0
        public static void Run(string convertToFormat, ConvertOptions convertOptions)
        {
            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/sample.docx",
                    Format         = convertToFormat,
                    ConvertOptions = convertOptions,
                    OutputPath     = "converted/" + convertToFormat
                };

                // convert to specified format
                List <StoredConvertedResult> response = apiInstance.ConvertDocument(new ConvertDocumentRequest(settings));
                Console.WriteLine("Document converted successfully: " + response[0].Url);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling ConvertApi.QuickConvert: " + e.Message);
            }
        }
Пример #5
0
        public IActionResult TestMarginAndPageSize()
        {
            string strHtmlTemplate = @"<!DOCTYPE html>
                        <html>
                        <head>
                        </head>
                        <body>
                            <header>
                                <h1>Zoe</h1>
                            </header>
                            <div>
                                <h2>欢迎关注Code综艺圈</h2>
                            </div>
                        </body>";
            var    options         = new ConvertOptions
            {
                PageMargins = new Wkhtmltopdf.NetCore.Options.Margins
                {
                    Bottom = 10, //下边距
                    Left   = 0,  //左边距
                    Right  = 0,  //右边距
                    Top    = 15  //上边距
                },
                PageSize = Wkhtmltopdf.NetCore.Options.Size.A5
            };

            _generatePdf.SetConvertOptions(options);
            var pdf           = _generatePdf.GetPDF(strHtmlTemplate);
            var pdfFileStream = new MemoryStream();

            pdfFileStream.Write(pdf, 0, pdf.Length);
            pdfFileStream.Position = 0;
            return(new FileStreamResult(pdfFileStream, "application/pdf"));
        }
Пример #6
0
        public string ConvertToWav(string fileName)
        {
            FileInfo outputFormat = new FileInfo
            {
                FileType         = FileType.Wav,
                Channels         = 1,
                SampleSizeInBits = 8,
                SamplingRate     = _samplingRate,
                EncodingType     = EncodingType.UnsignedInteger
            };

            var            fileNameExt    = Path.GetExtension(fileName);
            ConvertOptions convertOptions = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = Sox.GetFileTypeFromExtension(fileNameExt)
                },
                OutputFileInfo = outputFormat
            };

            using (Stream input = File.OpenRead(fileName))
            {
                string resultFileName = Path.GetTempFileName();
                _sox.Convert(input, convertOptions).WriteToFile(resultFileName);
                return(resultFileName);
            }
        }
Пример #7
0
        public void ConvertWavToMp3()
        {
            Sox sox = CreateSoxInstance();
            ConvertOptions options = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = FileType.Mp3,
                },
                OutputFileInfo = new FileInfo
                {
                    FileType = FileType.RawUnsignedInteger8,
                    Channels = 1,
                    SampleSizeInBits = 8,
                    SamplingRate = 8000,
                    EncodingType = EncodingType.UnsignedInteger
                }
            };

            int preRunTempDirFileCount = Directory.GetFiles(sox.TempDir).Length;
            using (Stream input = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh.mp3"))
            using (Stream expected = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh-mp3.u8"))
            using (Stream output = sox.Convert(input, options))
            {
                StreamTestHelper.AssertAreEqual(expected, output, 2);
            }
            Assert.AreEqual(preRunTempDirFileCount, Directory.GetFiles(sox.TempDir).Length);
        }
Пример #8
0
        public Stream Convert(string fileName)
        {
            FileInfo rawFileFormat = new FileInfo
            {
                FileType         = FileType.RawUnsignedInteger8,
                Channels         = 1,
                SampleSizeInBits = 8,
                SamplingRate     = _samplingRate,
                EncodingType     = EncodingType.UnsignedInteger
            };

            var            fileNameExt    = Path.GetExtension(fileName);
            ConvertOptions convertOptions = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = Sox.GetFileTypeFromExtension(fileNameExt)
                },
                OutputFileInfo = rawFileFormat
            };

            using (Stream input = File.OpenRead(fileName))
            {
                return(_sox.Convert(input, convertOptions));
            }
        }
Пример #9
0
        public async Task ConvertToPoint_MemoryTest()
        {
            var convertOptions = new ConvertOptions()
            {
                Colored   = true,
                ColorStep = ColorStep.VeryBig,
                Size      = 300
            };

            var logger        = new Mock <IActionLogger>().Object;
            var fileService   = new Mock <IFileService>().Object;
            var imagesService = new Mock <IGetImagesService>().Object;

            const int iterations = 10;

            for (var index = 0; index < iterations; index++)
            {
                using var imageConverter = new ImageConverter.ImageConverter();

                var imageToPointConverter = new ImageToPointService(imageConverter, imagesService, fileService);
                var controller            = new GenerateController(imageToPointConverter, logger);
                await using var stream = ImageGenerate.GenerateGradientImage();
                var formFile = new FormFile(stream, 0, stream.Length, "name", "test_image.jpg");

                var result = await controller.ConvertToPoints(formFile, convertOptions);

                Assert.NotNull(result);
            }
        }
Пример #10
0
        public static void Run(string convertToFormat, ConvertOptions convertOptions)
        {
            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/sample.docx",
                    Format         = convertToFormat,
                    ConvertOptions = convertOptions,
                    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 converted successfully: " + response.Length.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling ConvertApi.QuickConvert: " + e.Message);
            }
        }
Пример #11
0
        public IActionResult ConvertFromUrl([FromQuery] string url, [FromBody] ConvertOptions options)
        {
            var webClient      = new System.Net.WebClient();
            var downloadedHtml = webClient.DownloadString(url);

            var converter = new SynchronizedConverter(new PdfTools());
            var doc       = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize   = PaperKind.A4Plus,
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount     = true,
                        HtmlContent    = downloadedHtml,
                        WebSettings    = { DefaultEncoding = "utf-8" },
                        HeaderSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                    }
                }
            };

            byte[] pdf = converter.Convert(doc);

            var response = File(pdf, "application/octet-stream", "File.pdf"); // FileStreamResult

            return(response);
        }
        public async Task <IActionResult> MarginTest()
        {
            var options = new ConvertOptions
            {
                PageMargins = new Wkhtmltopdf.NetCore.Options.Margins()
                {
                    Left  = 0,
                    Right = 0
                }
            };

            _generatePdf.SetConvertOptions(options);

            var data = new TestData
            {
                Text   = "This is a test",
                Number = 123456
            };

            var pdf = await _generatePdf.GetByteArray("Views/Test.cshtml", data);

            var pdfStream = new System.IO.MemoryStream();

            pdfStream.Write(pdf, 0, pdf.Length);
            pdfStream.Position = 0;
            return(new FileStreamResult(pdfStream, "application/pdf"));
        }
Пример #13
0
        public void ConvertWavToRaw()
        {
            Sox sox = new Sox
            {
                SoxDirectory = Path.Combine(TestHelper.GetSolutionDirectory(), @"libs\sox-14.3.2\")
            };
            ConvertOptions options = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = FileType.Wav,
                },
                OutputFileInfo = new FileInfo
                {
                    FileType = FileType.RawUnsignedInteger8,
                    Channels = 1,
                    SampleSizeInBits = 8,
                    SamplingRate = 8000,
                    EncodingType = EncodingType.UnsignedInteger
                }
            };

            int preRunTempDirFileCount = Directory.GetFiles(sox.TempDir).Length;
            using (Stream input = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh.wav"))
            using (Stream expected = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh-wav.u8"))
            using (Stream output = sox.Convert(input, options))
            {
                StreamTestHelper.AssertAreEqual(expected, output, 2);
            }
            Assert.AreEqual(preRunTempDirFileCount, Directory.GetFiles(sox.TempDir).Length);
        }
Пример #14
0
        public string ConvertToWav(string sourceFileName, string destinationFileName, bool highQuality = false)
        {
            _log.Debug(string.Format("Atempting to convert '{0}' to '{1}'", sourceFileName, destinationFileName));
            FileInfo outputFormat = new FileInfo
            {
                FileType         = FileType.Wav,
                Channels         = 1,
                SampleSizeInBits = 8,
                SamplingRate     = highQuality ? SAMPLING_RATE * 2 : SAMPLING_RATE,
                EncodingType     = EncodingType.UnsignedInteger
            };

            var            fileNameExt    = Path.GetExtension(sourceFileName);
            ConvertOptions convertOptions = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = Sox.GetFileTypeFromExtension(fileNameExt)
                },
                OutputFileInfo = outputFormat
            };

            using (Stream input = File.OpenRead(sourceFileName))
            {
                string resultFileName = string.IsNullOrEmpty(destinationFileName) ? Path.GetTempFileName() : destinationFileName;
                using (var tempConvertedFileStream = _sox.Convert(input, convertOptions))
                {
                    tempConvertedFileStream.WriteToFile(resultFileName);
                };
                return(resultFileName);
            }
        }
Пример #15
0
        private static int ConvertPackage(ConvertOptions options)
        {
            try {
                string packageFolderPath = options.Path;
                var    packageDirectory  = new DirectoryInfo(packageFolderPath);
                var    existingProjects  = packageDirectory.GetFiles("*.csproj");
                string packageName       = packageDirectory.Name;
                if (existingProjects.Length > 0)
                {
                    throw new Exception($"Package {packageName} contains existing .proj file. Remove existing project from package folder and try again.");
                }
                Console.WriteLine("Start converting package '{0}'.", packageName);
                string packagePath = Path.Combine(options.Path, prefix);
                var    backupPath  = packageName + ".zip";
                if (File.Exists(backupPath))
                {
                    File.Delete(backupPath);
                }
                ZipFile.CreateFromDirectory(packagePath, backupPath);
                Console.WriteLine("Created backup package '{0}'.", packageName);

                var fileNames = MoveCsFiles(packagePath);
                CorrectingFiles(packagePath);
                CreateProjectInfo(packagePath, packageName, fileNames);
                Console.WriteLine("Package '{0}' converted.", packageName);
                return(0);
            } catch (Exception e) {
                Console.WriteLine(e);
                return(1);
            }
        }
Пример #16
0
        public async Task <IActionResult> GenerateCertificate(string ticket, string firstName, string lastName)
        {
            var connection = new Connection();
            var response   = connection.IsTicketNumberValid(ticket);

            if (response.IsValid)
            {
                var assembly = Assembly.GetEntryAssembly();
                using (var stream = assembly.GetManifestResourceStream("devfestcertapi.PDF.template.html"))
                    using (var reader = new StreamReader(stream))
                    {
                        string template = await reader.ReadToEndAsync();

                        var updatedtemplate = template
                                              .Replace("{attendee}", string.Format("{0} {1}", response.FirstName, response.LastName))
                                              .Replace("{ticketNumber}", ticket);
                        var options = new ConvertOptions();
                        options.IsLowQuality       = false;
                        options.PageMargins.Bottom = 0;
                        options.PageMargins.Left   = 0;
                        options.PageMargins.Right  = 0;
                        options.PageMargins.Top    = 0;
                        options.PageOrientation    = Wkhtmltopdf.NetCore.Options.Orientation.Landscape;

                        _generatePdf.SetConvertOptions(options);
                        var pdf = _generatePdf.GetPDF(updatedtemplate);
                        Response.Headers.Add("Content-Disposition", "inline; filename=GDGPH2020Certificate.pdf");
                        return(File(pdf.ToArray(), "application/pdf"));
                    }
            }
            return(new BadRequestResult());
        }
Пример #17
0
        public async Task <byte[]> GenerateExamplePdf(string userName)
        {
            var model = new CertificateModel
            {
                Name           = userName,
                Date           = DateTime.Now.ToShortDateString(),
                BackgroundPath = $"{AppContext.BaseDirectory}MustacheTemplates/Certificate/certificate_bg.jpg"
            };

            var certificateContent = await ProcessTemplate
                                         (model, @"./MustacheTemplates/Certificate/ExampleCertificateTemplate.html");

            var options = new ConvertOptions
            {
                PageOrientation = Orientation.Landscape,
                PageMargins     = new Margins(0, 0, 0, 0),
            };

            _generatePdf.SetConvertOptions(options);

            var bytes = _generatePdf.GetPDF(certificateContent);

            // If you want to save file on disc
            // await File.WriteAllBytesAsync("file.pdf", bytes);

            return(bytes);
        }
Пример #18
0
 public override void ProcessFile(OutputFile file, ConvertOptions options)
 {
     file = new OutputFile(Path.GetTempFileName(), file.Data);
     save.ProcessFile(file, options);
     dro_player.Arguments = "/c dro_player \""+file.Path+"\"";
     Process proc = Process.Start(dro_player);
     Process ctlProc = proc;
     ConsoleCancelEventHandler oncancel = (o,a) => {a.Cancel = true; ctlProc.Kill();};
     Console.CancelKeyPress += oncancel;
     try{
         int read;
         bool first = true;
         while((read = proc.StandardOutput.Read()) != -1)
         {
             if(first)
             {
                 ctlProc = GetChildProcesses(proc).FirstOrDefault() ?? proc;
                 first = false;
             }
             Console.Write((char)read);
         }
         proc.WaitForExit();
     }finally{
         Console.CancelKeyPress -= oncancel;
         if(!proc.HasExited) proc.Kill();
         File.Delete(file.Path);
     }
     Console.WriteLine();
 }
Пример #19
0
        public void ConvertWavToRaw()
        {
            Sox            sox     = CreateSoxInstance();
            ConvertOptions options = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = FileType.Wav,
                },
                OutputFileInfo = new FileInfo
                {
                    FileType         = FileType.RawUnsignedInteger8,
                    Channels         = 1,
                    SampleSizeInBits = 8,
                    SamplingRate     = 8000,
                    EncodingType     = EncodingType.UnsignedInteger
                }
            };

            int preRunTempDirFileCount = Directory.GetFiles(sox.TempDir).Length;

            using (Stream input = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh.wav"))
                using (Stream expected = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh-wav.u8"))
                    using (Stream output = sox.Convert(input, options))
                    {
                        StreamTestHelper.AssertAreEqual(expected, output, 2);
                    }
            Assert.AreEqual(preRunTempDirFileCount, Directory.GetFiles(sox.TempDir).Length);
        }
Пример #20
0
        public void ConvertWavToMp3()
        {
            Sox sox = new Sox
            {
                SoxDirectory = Path.Combine(TestHelper.GetSolutionDirectory(), @"libs\sox-14.3.2\")
            };
            ConvertOptions options = new ConvertOptions
            {
                InputFileInfo = new FileInfo
                {
                    FileType = FileType.Mp3,
                },
                OutputFileInfo = new FileInfo
                {
                    FileType         = FileType.RawUnsignedInteger8,
                    Channels         = 1,
                    SampleSizeInBits = 8,
                    SamplingRate     = 8000,
                    EncodingType     = EncodingType.UnsignedInteger
                }
            };

            int preRunTempDirFileCount = Directory.GetFiles(sox.TempDir).Length;

            using (Stream input = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh.mp3"))
                using (Stream expected = GetType().Assembly.GetManifestResourceStream("SoxLib.Test.Unit.doh-mp3.u8"))
                    using (Stream output = sox.Convert(input, options))
                    {
                        StreamTestHelper.AssertAreEqual(expected, output, 2);
                    }
            Assert.AreEqual(preRunTempDirFileCount, Directory.GetFiles(sox.TempDir).Length);
        }
Пример #21
0
 public virtual IList<OutputFile> ProcessFile(string file, ConvertOptions options)
 {
     using(FileStream stream = new FileStream(file, FileMode.Open))
     {
         return ProcessStream(stream, options);
     }
 }
Пример #22
0
        private static int ConvertPath(ConvertOptions opt)
        {
            var isDir = Directory.Exists(opt.SourcePath);

            if (!isDir)
            {
                if (!File.Exists(opt.SourcePath))
                {
                    Console.WriteLine("Source path not exists");
                    return(1);
                }
            }

            Directory.CreateDirectory(opt.TargetFolder);
            Studio.assemblyReferenceFolder = opt.AssemblyPath;
            Studio.exportSuffix            = opt.TargetSuffix;
            Studio.skipExists = opt.SkipExists;

            using (new CLIProgress())
            {
                if (isDir)
                {
                    Studio.assetsManager.LoadFolder(opt.SourcePath);
                }
                else
                {
                    if (Path.GetExtension(opt.SourcePath) == ".files")
                    {
                        var files = File.ReadAllLines(opt.SourcePath);
                        Studio.assetsManager.LoadFiles(files);
                    }
                    else
                    {
                        Studio.assetsManager.LoadFiles(opt.SourcePath);
                    }
                }

                Studio.BuildAssetData();

                if (!string.IsNullOrEmpty(opt.Makefile))
                {
                    var exportArgs = Proto.ExportArguments.Parser.ParseJson(File.ReadAllText(opt.Makefile));
                    foreach (var arg in exportArgs.Exports)
                    {
                        FilterWithArg(arg);
                        Enum.TryParse(arg.ExportType, out ExportType exportType);
                        Enum.TryParse(arg.ProcessType, out ProcessType processType);
                        Studio.ExportAssets(opt.TargetFolder, Studio.visibleAssets, exportType, processType);
                    }
                }
                else
                {
                    FilterWithOptions(opt);
                    Studio.ExportAssets(opt.TargetFolder, Studio.visibleAssets, ExportType.Convert, ProcessType.Async);
                }
            }

            return(0);
        }
Пример #23
0
        private void ReplaceAudio(SndAssetBankEntry entry, string inputFile)
        {
            // Begin conversion here.
            var options = new ConvertOptions {
                AudioChannels = entry.ChannelCount, SampleRate = entry.SampleRate
            };

            OnAudioReplaced(entry, ConvertProgressForm.Convert(inputFile, entry.Format, options));
        }
Пример #24
0
        private bool ConvertIsos(
            string[] srcIsos,
            string[] srcTocs,
            ProcessOptions processOptions,
            CancellationToken cancellationToken)
        {
            var appPath = ApplicationInfo.AppPath;
            var gameId  = FindGameId(srcIsos[0]);
            var game    = GetGameEntry(gameId, srcIsos[0], false);

            var options = new ConvertOptions()
            {
                DestinationPbp    = Path.Combine(processOptions.OutputPath, $"{game.SaveDescription}.PBP"),
                DiscInfos         = new List <DiscInfo>(),
                MainGameTitle     = game.SaveDescription,
                MainGameID        = game.SaveFolderName,
                MainGameRegion    = game.Format,
                SaveTitle         = game.SaveDescription,
                SaveID            = game.SaveFolderName,
                Pic0              = Path.Combine(appPath, "Resources", "PIC0.PNG"),
                Pic1              = Path.Combine(appPath, "Resources", "PIC1.PNG"),
                Icon0             = Path.Combine(appPath, "Resources", "ICON0.PNG"),
                BasePbp           = Path.Combine(appPath, "Resources", "BASE.PBP"),
                CompressionLevel  = processOptions.CompressionLevel,
                CheckIfFileExists = processOptions.CheckIfFileExists,
                FileNameFormat    = processOptions.FileNameFormat,
            };

            for (var i = 0; i < srcIsos.Length; i++)
            {
                gameId = FindGameId(srcIsos[i]);
                game   = GetGameEntry(gameId, srcIsos[i]);

                options.DiscInfos.Add(new DiscInfo()
                {
                    GameID     = game.ScannerID,
                    GameTitle  = game.SaveDescription,
                    GameName   = game.GameName,
                    Region     = game.Format,
                    MainGameID = game.SaveFolderName,
                    SourceIso  = srcIsos[i],
                    SourceToc  = i < srcTocs.Length ? srcTocs[i] : "",
                });
            }

            _notifier?.Notify(PopstationEventEnum.Info, $"Using Title '{game.SaveDescription}'");

            var popstation = new Popstation.Popstation
            {
                ActionIfFileExists = _eventHandler.ActionIfFileExists,
                Notify             = _notifier.Notify,
                TempFiles          = tempFiles
            };

            return(popstation.Convert(options, cancellationToken));
        }
Пример #25
0
 public override void ProcessFile(OutputFile file, ConvertOptions options)
 {
     using(StreamWriter writer = new StreamWriter(new FileStream(file.Path, FileMode.Create)))
     {
         foreach(var cmd in file.Data)
         {
             writer.WriteLine(cmd.ToString());
         }
     }
 }
Пример #26
0
        public async Task <RecColor> ConvertFromFile(IFormFile image, ConvertOptions options)
        {
            await using var memoryStream = new MemoryStream();

            await image.CopyToAsync(memoryStream)
            .ConfigureAwait(AsyncConstant.ContinueOnCapturedContext);

            var result = await _imageConverter.ConvertToChars(memoryStream, options)
                         .ConfigureAwait(AsyncConstant.ContinueOnCapturedContext);

            return(result);
        }
        internal static Stream Convert(string inputFile, AudioFormat format, ConvertOptions options)
        {
            if (options == null)
            {
                options = new ConvertOptions();
            }
            var form = new ConvertProgressForm();

            form.SetOptions(inputFile, format, options);
            form.ShowDialog();
            return(form.OutputStream);
        }
Пример #28
0
        internal string[] Parse(ConvertOptions options)
        {
            var intel = _missionFile.SubClasses["Intel"];

            ParseIntel(intel);

            var entities = _missionFile.SubClasses["Entities"];

            ParseEntities(entities, options);

            return(_sqf.ToArray());
        }
Пример #29
0
        static int Convert(ConvertOptions o)
        {
            if (!File.Exists(o.PathIn))
            {
                Console.WriteLine("Input path doesn't exist.");
                return(1);
            }

            SaveConvert.ConvertFile(o.PathIn, o.PathOut, o.Target);

            return(0);
        }
Пример #30
0
        private static string BasicConvert(string pattern, ConvertOptions options)
        {
            if (pattern == null)
            {
                throw new ArgumentNullException(nameof(pattern));
            }

            using (var context = new ConvertContext())
            {
                return(context.Convert(pattern, ImplicitOptions | options));
            }
        }
Пример #31
0
        private void ButtonConvert_Click(object sender, EventArgs e)
        {
            try
            {
                ButtonStatistics.Enabled = false;

                if (String.IsNullOrEmpty(LabelSelectFile.Text))
                {
                    throw new Exception("Invalid path");
                }

                if (String.IsNullOrEmpty(LabelSaveFile.Text))
                {
                    throw new Exception("Invalid save path");
                }

                var options = new ConvertOptions()
                {
                    AddToGlobalArray      = CheckBoxAddToGlobalArray.Checked,
                    AutoDeleteEmptyGroups = CheckBoxAutoDeleteEmptyGroups.Checked
                };

                var reader      = new Reader(LabelSelectFile.Text);
                var missionFile = reader.ReadMissionFile();
                if (missionFile == null)
                {
                    throw new Exception("Failed to extract mission data");
                }

                var parser = new Parser(missionFile);
                var sqf    = parser.Parse(options);

                Debug.WriteLine("=================================");
                Debug.WriteLine("Translated SQF:");
                foreach (var line in sqf)
                {
                    Debug.WriteLine(line);
                }

                File.WriteAllLines(LabelSaveFile.Text, sqf);

                ButtonStatistics.Enabled = true;
            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show($"[ERROR]: {ex}");
#else
                MessageBox.Show($"[ERROR]: {ex.Message}");
#endif
            }
        }
Пример #32
0
        /// <summary>Creates the template output</summary>
        /// <param name="parameters">Parameter passed to the template.</param>
        public static string TransformText(Controller controller, ConvertOptions options)
        {
            var template = new Service()
            {
                Session = new Dictionary <string, object>()
                {
                    { "controller", controller },
                    { "options", options }
                }
            };

            template.Initialize();
            return(template.TransformText());
        }
Пример #33
0
        /// <summary>Creates the template output</summary>
        /// <param name="parameters">Parameter passed to the template.</param>
        public static string TransformText(Models.Model model, ConvertOptions options)
        {
            var template = new Model()
            {
                Session = new Dictionary <string, object>()
                {
                    { "model", model },
                    { "options", options }
                }
            };

            template.Initialize();
            return(template.TransformText());
        }
Пример #34
0
        private static int Convert(ConvertOptions opts)
        {
            Console.WriteLine($"Read WRP from '{opts.Source}'");
            var source = StreamHelper.Read <AnyWrp>(opts.Source);

            Console.WriteLine("Convert");
            var editable = source.GetEditableWrp();

            Console.WriteLine($"Write to '{opts.Target}'");
            editable.Write(opts.Target);

            Console.WriteLine("Done");
            return(0);
        }
Пример #35
0
 public override IList<OutputFile> ProcessStream(Stream input, ConvertOptions options)
 {
     List<RPCCommand> rpc = new List<RPCCommand>();
     StreamReader reader = new StreamReader(input);
     string line;
     while((line = reader.ReadLine()) != null)
     {
         string[] split = line.Split(new[]{": "}, 0);
         RPCCommandType cmd = (RPCCommandType)Enum.Parse(typeof(RPCCommandType), split[0]);
         int value = Int32.Parse(split[1]);
         rpc.Add(new RPCCommand(cmd, value));
     }
     return LoadPCS.ProcessRPC(rpc, options);
 }
        public void TestPostConvertVideo()
        {
            var            localName  = "sample.avi";
            var            remoteName = "toconvert.avi";
            var            fullName   = Path.Combine(this.dataFolder, remoteName);
            var            resultPath = Path.Combine(this.dataFolder, "converted.mp4");
            ConvertOptions options    = new ConvertOptions();

            this.StorageApi.PutCreate(fullName, null, null, File.ReadAllBytes(BaseTestContext.GetDataDir() + localName));

            var request = new PostConvertVideoRequest(remoteName, "mp4", resultPath, options, this.dataFolder);
            var actual  = this.VideoApi.PostConvertVideo(request);

            Assert.AreEqual(200, System.Convert.ToInt32(actual.Code.ToString()));
        }
Пример #37
0
 public override void ProcessFile(OutputFile file, ConvertOptions options)
 {
     Console.WriteLine(file.Path);
     Console.WriteLine(TimeSpan.FromMilliseconds(file.Data.Sum(cmd => cmd.DelayValue)));
     Console.WriteLine("Creating WAV...");
     var song = SaveWAV.CreateSong(file.Data, SaveWAV.GetWaveform(options), options.Wave_Volume??1.0, options.Wave_Clip??false, options.Wave_Frequency??44100, options.ClickLength);
     Console.WriteLine("Playing...");
     using(var buffer = new MemoryStream())
     {
         SaveWAV.Writer.WriteWave(buffer, song);
         buffer.Position = 0;
         var player = new SoundPlayer(buffer);
         player.PlaySync();
     }
 }
Пример #38
0
 public override void ProcessFile(OutputFile file, ConvertOptions options)
 {
     Console.WriteLine(file.Path);
     Console.WriteLine(TimeSpan.FromMilliseconds(file.Data.Sum(cmd => cmd.DelayValue)));
     Stopwatch sw = new Stopwatch();
     var rpc = file.Data;
     sw.Start();
     for(int i = 0; i < rpc.Count; i++)
     {
         var cmd = rpc[i];
         if(cmd.Type == RPCCommandType.SetCountdown || cmd.Type == RPCCommandType.ClearCountdown)
         {
             int delay = 0;
             for(int j = i+1; j < rpc.Count; j++)
             {
                 var cmd2 = rpc[j];
                 if(cmd2.Type == RPCCommandType.Delay)
                 {
                     delay += cmd2.Data;
                 }else{
                     i = j-1;
                     break;
                 }
             }
             if(cmd.Type == RPCCommandType.SetCountdown)
             {
                 int freq = 1193180/cmd.Data;
                 if(freq >= 37 && freq <= 32767 && delay > 0)
                 {
                     Console.Beep(freq, delay);
                 }else if(delay > 0)
                 {
                     Console.WriteLine("Bad frequency "+freq);
                     Thread.Sleep(delay);
                 }
             }else if(cmd.Type == RPCCommandType.ClearCountdown)
             {
                 Thread.Sleep(delay);
             }
         }else if(cmd.Type == RPCCommandType.Delay)
         {
             Thread.Sleep(cmd.Data);
         }
         Console.Write(sw.Elapsed+"\r");
     }
     sw.Stop();
     Console.WriteLine();
 }
Пример #39
0
        public override void ProcessFile(OutputFile file, ConvertOptions options)
        {
            using(BinaryWriter writer = new BinaryWriter(new FileStream(file.Path, FileMode.Create), Encoding.ASCII))
            {
                writer.Write((byte)0x08);
                writer.Write("MONOTONE".ToCharArray());
                writer.Write(new byte[82]);
                writer.Write(new byte[]{1,1,1,2,0});
                writer.Write(Enumerable.Repeat((byte)0xFF, 255).ToArray());

                byte lastb = 0;
                foreach(var cmd in file.Data)
                {
                    switch(cmd.Type)
                    {
                        case RPCCommandType.SetCountdown:
                            double freq = LoadMDT.CountdownToFrequency(cmd.Data);
                            var bval = freq/15;
                            if(bval > 255)
                            {
                                lastb = 0;
                            }else{
                                lastb = (byte)bval;
                            }
                            break;
                        case RPCCommandType.ClearCountdown:
                            lastb = 0;
                            break;
                        case RPCCommandType.Delay:
                            for(int i = 0; i < cmd.DelayValue*60/1000.0; i++)
                            {
                                writer.Write((byte)0);
                                writer.Write(lastb);
                            }
                            break;
                    }
                }
            }
        }
Пример #40
0
 public virtual void ProcessFile(OutputFile file, ConvertOptions options)
 {
     using(var stream = new FileStream(file.Path, FileMode.Create))
     {
         var writer = new BinaryWriter(stream);
         writer.Write(0);
         byte lastb = 0;
         foreach(var cmd in file.Data)
         {
             switch(cmd.Type)
             {
                 case RPCCommandType.SetCountdown:
                     double freq = LoadMDT.CountdownToFrequency(cmd.Data);
                     var bval = freq/15;
                     if(bval > 255)
                     {
                         lastb = 0;
                     }else{
                         lastb = (byte)bval;
                     }
                     break;
                 case RPCCommandType.ClearCountdown:
                     lastb = 0;
                     break;
                 case RPCCommandType.Delay:
                     for(int i = 0; i < cmd.DelayValue*140/1000.0; i++)
                     {
                         writer.Write(lastb);
                     }
                     break;
             }
         }
         stream.Position = 2;
         writer.Write((short)(stream.Length-4));
     }
 }
Пример #41
0
        public virtual IList<OutputFile> ProcessStream(Stream input, ConvertOptions options)
        {
            List<RPCCommand> rpc = new List<RPCCommand>();

            using(BinaryReader reader = new BinaryReader(input))
            {
                reader.ReadInt16();
                int length = reader.ReadInt16();
                byte lastb = 0;
                int delay = 0;
                for(int i = 0; i < length; i++)
                {
                    byte b = reader.ReadByte();
                    if(b != lastb)
                    {
                        rpc.Add(RPCCommand.Delay(delay*1000/140));
                        delay = 0;
                    }
                    if(b == 0)
                    {
                        rpc.Add(RPCCommand.ClearCountdown());
                    }else{
                        double freq = b*15;//frequencies[b];
                        rpc.Add(RPCCommand.SetCountdown(LoadMDT.FrequencyToCountdown(freq)));
                    }
                    delay += 1;
                    lastb = b;
                }
                rpc.Add(RPCCommand.Delay(delay*1000/140));
            }
            return LoadPCS.ProcessRPC(rpc, options);
        }
Пример #42
0
 public static WaveFunction GetWaveform(ConvertOptions options)
 {
     if(options.Waveform.HasValue)
     {
         switch(options.Waveform.Value)
         {
             case 0:
                 return WaveFunction.Sine;
             case 1:
                 return WaveFunction.HalfSine;
             case 2:
                 return WaveFunction.AbsSine;
             case 3:
                 return WaveFunction.HalfAbsSine;
             case 4:default:
                 return WaveFunction.Square;
             case 5:
                 return WaveFunction.Triangle;
             case 6:
                 return WaveFunction.Circle;
             case 7:
                 return WaveFunction.AbsCircle;
             case 8:
                 return WaveFunction.Sawtooth;
             case 9:
                 return WaveFunction.Clausen;
             case 10:
                 return WaveFunction.SineDouble;
         }
     }else{
         return WaveFunction.Square;
     }
 }
Пример #43
0
        public static IList<OutputFile> ProcessRPC(List<RPCCommand> rpc, ConvertOptions options)
        {
            bool informed = false;

            for(int i = 0; i < rpc.Count; i++)
            {
                var cmd = rpc[i];
                if(cmd.Type == RPCCommandType.SetCountdown)
                {
                    if(cmd.Data <= 36 || cmd.Data > 32248)
                    {
                        if(options.PCS_Sanitize)
                        {
                            rpc.RemoveAt(i);
                            i -= 1;
                        }else if(!informed)
                        {
                            informed = true;
                            Console.WriteLine("Input contains frequencies outside the hearing range, use --sanitize to remove them.");
                        }
                    }
                }
                if(cmd.Type == RPCCommandType.Delay && cmd.Data == 0)
                {
                    rpc.RemoveAt(i);
                    i -= 1;
                }else if(cmd.Type == RPCCommandType.Delay)
                {
                    if(i+1 < rpc.Count && rpc[i+1].Type == RPCCommandType.Delay)
                    {
                        int delay = cmd.Data + rpc[i+1].Data;
                        rpc[i] = new RPCCommand(RPCCommandType.Delay, delay);
                        rpc.RemoveAt(i+1);
                        i -= 1;
                    }
                }else{
                    if(i+1 < rpc.Count && rpc[i+1].Type == cmd.Type && rpc[i+1].Data == cmd.Data)
                    {
                        rpc.RemoveAt(i);
                        i -= 1;
                    }
                }
            }

            if(options.PCS_Trim)
            {
                for(int i = 0; i < rpc.Count; i++)
                {
                    var cmd = rpc[i];
                    if(cmd.Type == RPCCommandType.SetCountdown)
                    {
                        break;
                    }else{
                        rpc.RemoveAt(i);
                        i -= 1;
                    }
                }
                for(int i = rpc.Count-1; i >= 0; i--)
                {
                    var cmd = rpc[i];
                    if(cmd.Type == RPCCommandType.SetCountdown)
                    {
                        break;
                    }else{
                        rpc.RemoveAt(i);
                    }
                }
            }

            IList<OutputFile> files;
            if(options.PCS_Split)
            {
                bool playing = false;
                files = rpc.Split(
                    c => c.Type == RPCCommandType.SetCountdown ? (playing = true) && false : c.Type == RPCCommandType.ClearCountdown ? (playing = false) && false : c.Type == RPCCommandType.Delay ? c.Data >= options.PCS_SplitDelay*1000 && !playing : false
                ).Select((d,i) => new OutputFile(Path.ChangeExtension(Path.ChangeExtension(options.OutputPath, null)+i.ToString("000"), options.Extension), d)).ToList();
            }else{
                files = new[]{new OutputFile(options.OutputPath, rpc)};
            }

            if(options.PCS_Crop)
            {
                foreach(var file in files)
                {
                    var data = file.Data;
                    int start = 0;
                    for(int i = 0; i < data.Count; i++)
                    {
                        var cmd = data[i];
                        if(cmd.Type == RPCCommandType.SetCountdown)
                        {
                            start = i; break;
                        }
                    }
                    for(int i = start+1; i < data.Count; i++)
                    {
                        var cmd = data[i];
                        if(cmd.Type == RPCCommandType.Delay) continue;
                        for(int j = i; j < data.Count; j++)
                        {
                            var left = data[start+j-i];
                            var right = data[j];
                            if(left.Type != right.Type) break;
                            if(left.Type == RPCCommandType.SetCountdown ? left.Data != right.Data : false) break;
                            if(left.Type == RPCCommandType.Delay ? right.Data < left.Data-2 || right.Data > left.Data+2 : false) break;
                            if(j-i > options.PCS_CropSimilarity || (j == data.Count-3 && j-i > 5))
                            {
                                data.RemoveRange(i, data.Count-i);
                            }
                        }
                    }
                }
            }

            if(options.PCS_TrimLength)
            {
                foreach(var file in files)
                {
                    var data = new List<RPCCommand>(file.Data);
                    int time = 0;
                    for(int i = 0; i < data.Count; i++)
                    {
                        var cmd = data[i];
                        if(cmd.Type == RPCCommandType.Delay)
                        {
                            time += cmd.Data;
                            if(time > options.PCS_NewLength)
                            {
                                data[i] = new RPCCommand(cmd.Type, cmd.Channel, cmd.DelayValue-(time-options.PCS_NewLength));
                                data.RemoveRange(i+1, data.Count-(i+1));
                                data.Add(RPCCommand.ClearCountdown());
                            }
                        }
                    }
                }
            }

            if(options.PCS_Repeat)
            {
                foreach(var file in files)
                {
                    var data = new List<RPCCommand>(file.Data);
                    for(int i = 0; i < options.PCS_RepeatCount-1; i++)
                    {
                        file.Data.AddRange(data);
                    }
                }
            }

            if(options.Optimize)
            {
                foreach(var file in files)
                {
                    var data = file.Data;

                    int? lastfreq = null;
                    for(int i = 0; i < data.Count; i++)
                    {
                        var cmd = data[i];
                        if(cmd.Type == RPCCommandType.SetCountdown)
                        {
                            if(lastfreq != null && Math.Abs(lastfreq.Value-cmd.Data) <= 1)
                            {
                                lastfreq = cmd.Data;
                                data.RemoveAt(i);
                                i -= 1;
                            }else{
                                lastfreq = cmd.Data;
                            }
                        }else if(cmd.Type == RPCCommandType.ClearCountdown)
                        {
                            lastfreq = null;
                        }
                    }
                }
            }

            if(options.OutputType == "dro")
            {
                //Separates pairs of SetCountdown/ClearCountdown by a Delay: 0
                //Required for DRO rendering

                foreach(var file in files)
                {
                    var data = file.Data;

                    bool isclick = false;
                    for(int i = 0; i < data.Count; i++)
                    {
                        var cmd = data[i];
                        if(cmd.Type == RPCCommandType.SetCountdown)
                        {
                            isclick = true;
                        }else if(cmd.Type == RPCCommandType.Delay)
                        {
                            isclick = false;
                        }else if(cmd.Type == RPCCommandType.ClearCountdown)
                        {
                            if(isclick)
                            {
                                data.Insert(i, RPCCommand.Delay(0));
                                i += 1;
                            }
                            isclick = false;
                        }
                    }
                }
            }

            return files;
        }
Пример #44
0
 public override void ProcessFile(OutputFile file, ConvertOptions options)
 {
     using(var stream = new FileStream(file.Path, FileMode.Create))
     {
         Writer.SampleRate = options.Wave_Frequency??44100;
         Writer.WriteWave(stream, CreateSong(file.Data, GetWaveform(options), options.Wave_Volume??1.0, options.Wave_Clip??false, options.Wave_Frequency??44100, options.ClickLength));
     }
 }
Пример #45
0
        public override IList<OutputFile> ProcessStream(Stream input, ConvertOptions options)
        {
            List<Command> commands = new List<Command>();
            int linenum = 0;
            using(StreamReader reader = new StreamReader(input))
            {
                string line;
                while((line = reader.ReadLine()) != null)
                {
                    linenum += 1;
                    if(line.StartsWith("$"))
                    {
                        var match = Regex.Match(line, @"^\$(?<port>.+?)(:(?<state>.+?))?=(?<value>.+?)@(?<time>.+?)$");
                        if(match.Success)
                        {
                            int port = Convert.ToInt32(match.Groups["port"].Value, 16);
                            string sstate = match.Groups["state"].Value;
                            int state = String.IsNullOrEmpty(sstate)?-1:Convert.ToInt32(sstate, 16);
                            byte value = Convert.ToByte(match.Groups["value"].Value, 16);
                            int time = Convert.ToInt32(match.Groups["time"].Value);
                            switch(port)
                            {
                                case 0x42:
                                    if(state == 3)
                                    {
                                        commands.Add(new FrequencyByte1Command(value, time));
                                    }else if(state == 0)
                                    {
                                        commands.Add(new FrequencyByte2Command(value, time));
                                    }else{
                                        Program.Warning("{0}: Unknown port state ({1:x}).", linenum, state);
                                    }
                                    break;
                                case 0x43:
                                    commands.Add(new FrequencyModeCommand((value & 0x0E) >> 1, time));
                                    break;
                                case 0x61:
                                    if(value != state)
                                    {
                                        int diff = value ^ state;
                                        if(diff == 3)
                                        {
                                            commands.Add(new EnableCommand((value & 3) == 3, time));
                                        }else if(diff == 51)
                                        {
                                            commands.Add(new EnableCommand(false, time));
                                        }
                                    }
                                    break;
                                default:
                                    Program.Warning("{0}: Undefined port {1:x}.", linenum, port);
                                    break;
                            }
                        }else{
                            Program.Warning("{0}: Undefined line format.", linenum);
                        }
                    }
                }
            }

            return ProcessRPC(ProcessPCS(commands, options), options);
        }
Пример #46
0
        public static List<RPCCommand> ProcessPCS(IList<Command> commands, ConvertOptions options)
        {
            List<RPCCommand> rpc = new List<RPCCommand>();

            bool enabled = false;
            int starttime = -1;
            int lasttime = 0;
            FrequencyMode freqmode = 0;

            int? setcountdown = null;

            var e = commands.GetEnumerator();
            while(e.MoveNext())
            {
                if(starttime == -1)
                {
                    starttime = e.Current.Time;
                }else{
                    int timedelta  = e.Current.Time-lasttime;
                    if(timedelta > 0)
                    {
                        rpc.Add(RPCCommand.Delay(timedelta));
                    }
                }
                lasttime = e.Current.Time;
                if(e.Current is EnableCommand)
                {
                    enabled = ((EnableCommand)e.Current).Enable;
                    if(enabled == false)
                    {
                        rpc.Add(RPCCommand.ClearCountdown());
                    }else if(setcountdown != null)
                    {
                        rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, setcountdown.Value));
                        setcountdown = null;
                    }
                }else if(e.Current is FrequencyModeCommand)
                {
                    freqmode = ((FrequencyModeCommand)e.Current).Mode;
                }else if(e.Current is FrequencyByte1Command && freqmode != 0)
                {
                    if(freqmode == FrequencyMode.Countdown || freqmode == FrequencyMode.FrequencyDivider)
                    {
                        int countdown = ((FrequencyByte1Command)e.Current).Value;
                        e.MoveNext();
                        try{
                            countdown |= ((FrequencyByte2Command)e.Current).Value << 8;
                            //if(countdown != 0)
                                // /*if(enabled) */rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, countdown));
                            if(enabled)
                            {
                                rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, countdown));
                            }else{
                                setcountdown = countdown;
                            }
                        }catch(InvalidCastException)
                        {
                            Program.Error("Missing countdown pair for $42.");
                        }
                    }else{
                        Program.Warning("Unknown value {0:x} for port $42.", freqmode);
                    }
                }else{
                    Program.Warning("Unknown port ${0:x}.", e.Current.Port);
                }
            }

            return rpc;
        }
Пример #47
0
        public override void ProcessFile(OutputFile file, ConvertOptions options)
        {
            List<DROCommand> dro = new List<DROCommand>();
            if(options.MultiChannel)
            {
                for(int i = 0; i < 9; i++)
                {
                    dro.Add(new DROCommand(0x20 + oper1[i], 0x01));
                    dro.Add(new DROCommand(0x20 + oper1[i] + 3, 0x01));
                    dro.Add(new DROCommand(0x40 + oper1[i], 0x10));
                    dro.Add(new DROCommand(0x40 + oper1[i] + 3, 0x07));
                    dro.Add(new DROCommand(0x60 + oper1[i], 0xF0));
                    dro.Add(new DROCommand(0x60 + oper1[i] + 3, 0xF0));
                    dro.Add(new DROCommand(0x80 + oper1[i], 0x77));
                    dro.Add(new DROCommand(0x80 + oper1[i] + 3, 0x77));
                    dro.Add(new DROCommand(0xE0 + oper1[i], options.Waveform ?? 2));
                }
            }else{
                dro.Add(new DROCommand(0x20, 0x01));
                dro.Add(new DROCommand(0x23, 0x01));
                dro.Add(new DROCommand(0x40, 0x10));
                dro.Add(new DROCommand(0x43, 0x07));
                dro.Add(new DROCommand(0x60, 0xF0));
                dro.Add(new DROCommand(0x63, 0xF0));
                dro.Add(new DROCommand(0x80, 0x77));
                dro.Add(new DROCommand(0x83, 0x77));
                dro.Add(new DROCommand(0xE0, options.Waveform ?? 2));
            }
            if(options.DRO_PrefixCommands != null) dro.AddRange(options.DRO_PrefixCommands);

            bool informed = false;
            foreach(var cmd in file.Data)
            {
                if(cmd.Channel > 8)
                {
                    throw new ArgumentException("Only 9 channels are supported.");
                }
                switch(cmd.Type)
                {
                    case RPCCommandType.Delay:
                        if(cmd.Data == 0)
                        {
                            if(options.ClickLength != null)
                            {
                                dro.AddRange(DROCommand.Delay(Math.Max(1, (int)Math.Round(options.ClickLength.Value))));
                            }else{
                                if(!informed)
                                {
                                    Console.WriteLine("Song contains zero-length waves. Use --clicks 1 to render them as clicks.");
                                    informed = true;
                                }
                                dro.AddRange(DROCommand.Delay(cmd.Data));
                            }
                        }else{
                            dro.AddRange(DROCommand.Delay(cmd.Data));
                        }
                        break;
                    case RPCCommandType.SetCountdown:
                        double frequency = 1193180.0/cmd.Data;
                        int octave = 4;
                        while(frequency > 780.0375) //0x03FF * 0.7625
                        {
                            frequency /= 2;
                            octave += 1;
                            if(octave > 7) break;
                        }
                        if(octave > 7)
                        {
                            dro.Add(new DROCommand(0xB0 | cmd.Channel, 0x10));
                        }else{
                            int fnum = (int)(frequency/0.7625);
                            dro.Add(new DROCommand(0xA0 | cmd.Channel,  fnum & 0x00FF));
                            dro.Add(new DROCommand(0xB0 | cmd.Channel,((fnum & 0x0300) >> 8) | 0x20 | ((octave & 7) << 2)));
                        }
                        break;
                    case RPCCommandType.ClearCountdown:
                        dro.Add(new DROCommand(0xB0 | cmd.Channel, 0x10));
                        break;
                }
            }

            if(options.DRO_EndDelay > 0) dro.AddRange(DROCommand.Delay(options.DRO_EndDelay));

            if(options.Optimize)
            {
                byte?[] registers = new byte?[0xFF];
                for(int i = 0; i < dro.Count; i++)
                {
                    DROCommand cmd = dro[i];
                    if(cmd.IsOPL)
                    {
                        if(registers[cmd.OPLRegister] == cmd.OPLValue)
                        {
                            dro.RemoveAt(i);
                            i -= 1;
                        }
                        registers[cmd.OPLRegister] = cmd.OPLValue;
                    }
                }
                for(int i = 0; i < dro.Count; i++)
                {
                    DROCommand cmd = dro[i];
                    if(cmd.IsDelay)
                    {
                        if(i+1 < dro.Count && dro[i+1].IsDelay)
                        {
                            int delay = cmd.DelayValue + dro[i+1].DelayValue;
                            dro[i] = DROCommand.Delay(delay).First();
                            dro.RemoveAt(i+1);
                            i -= 1;
                        }
                    }
                }
            }

            int bytesize = dro.Sum(cmd => cmd.Length);
            int timesize = dro.Sum(cmd => cmd.DelayValue);
            using(BinaryWriter writer = new BinaryWriter(new FileStream(file.Path, FileMode.Create), Encoding.ASCII))
            {
                writer.Write("DBRAWOPL".ToCharArray());
                writer.Write((short)0);
                writer.Write((short)1);
                writer.Write(timesize);
                writer.Write(bytesize);
                writer.Write((byte)0);
                writer.Write(new byte[3]);
                foreach(var cmd in dro)
                {
                    writer.Write((byte)cmd.Register);
                    writer.Write(cmd.Data);
                }
            }
        }
Пример #48
0
 public abstract IList<OutputFile> ProcessStream(Stream input, ConvertOptions options);
Пример #49
0
        public override IList<OutputFile> ProcessStream(Stream input, ConvertOptions options)
        {
            List<RPCCommand> rpc = new List<RPCCommand>();

            Channel[] channels = new Channel[16];
            int lastchannel = -1;
            int time = 0;

            using(BinaryReader reader = new BinaryReader(input))
            {
                try{
                    if(options.MultiChannel)
                    {
                        while(true)
                        {
                            byte command = reader.ReadByte();
                            if((command & 0x80) != 0)
                            {
                                switch(command & 0xF0)
                                {
                                    case 0x90: //Play
                                        int channel = command & 0x0F;
                                        int note = reader.ReadByte();
                                        double freq = NoteToFrequency(note);
                                        rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, channel, FrequencyToCountdown(freq)));
                                        break;
                                    case 0x80: //Stop
                                        channel = command & 0x0F;
                                        rpc.Add(RPCCommand.ClearCountdown(channel));
                                        break;
                                    case 0xF0: case 0xE0: //End
                                        throw new EndOfStreamException();
                                }
                            }else{ //Delay
                                byte next = reader.ReadByte();
                                int delay = (command<<8)|next;
                                time += delay;
                                rpc.Add(RPCCommand.Delay(delay));
                            }
                        }
                    }else{
                        while(true)
                        {
                            byte command = reader.ReadByte();
                            if((command & 0x80) != 0)
                            {
                                switch(command & 0xF0)
                                {
                                    case 0x90: //Play
                                        int channel = command & 0x0F;
                                        lastchannel = channel;
                                        int note = reader.ReadByte();
                                        channels[channel].Frequency = NoteToFrequency(note);
                                        channels[channel].StartTime = time;
                                        double freq = FinalFrequency(channels);
                                        rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, FrequencyToCountdown(freq)));
                                        break;
                                    case 0x80: //Stop
                                        channel = command & 0x0F;
                                        channels[channel].Frequency = 0;
                                        if(channels.All(p => p.Frequency == 0))
                                        {
                                            rpc.Add(RPCCommand.ClearCountdown());
                                        }else{
                                            freq = FinalFrequency(channels);
                                            rpc.Add(new RPCCommand(RPCCommandType.SetCountdown, FrequencyToCountdown(freq)));
                                        }
                                        break;
                                    case 0xF0: case 0xE0: //End
                                        throw new EndOfStreamException();
                                }
                            }else{ //Delay
                                byte next = reader.ReadByte();
                                int delay = (command<<8)|next;
                                //if(delay == 0) delay = 50;
                                time += delay;
                                rpc.Add(RPCCommand.Delay(delay));
                            }
                        }
                    }
                }catch(EndOfStreamException)
                {

                }
            }

            return new[]{new OutputFile(options.OutputPath, rpc)};
        }
Пример #50
0
 public virtual void ProcessFiles(IEnumerable<OutputFile> files, ConvertOptions options)
 {
     foreach(var file in files) ProcessFile(file, options);
 }
Пример #51
0
 public abstract void ProcessFile(OutputFile file, ConvertOptions options);