BarcodeGenerator.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MovieBarcodeGenerator {
  9. public class BarcodeGenerator {
  10. public static string imagickPath;
  11. private static log4net.ILog log = log4net.LogManager.GetLogger("Generator");
  12. public static string ffmpegPath {
  13. get {
  14. return SharpFF.ffmpegPath;
  15. }
  16. set {
  17. SharpFF.ffmpegPath = value;
  18. }
  19. }
  20. public static void Generate(string inputFile, string outputFile, int height, int width) {
  21. Generate(inputFile, outputFile, height, 1, width);
  22. }
  23. public static void Generate(string inputFile, string outputFile, int height, int barWidth, int iterations) {
  24. log.Debug("Generate()");
  25. if (!Directory.Exists(imagickPath)) {
  26. log.ErrorFormat("ImageMagick was not found at '{0}'.", imagickPath);
  27. throw new Exception("ImageMagick was not found.");
  28. }
  29. if (File.Exists(outputFile)) {
  30. log.InfoFormat("Output file '{0}' exists. Deleting file.", outputFile);
  31. File.Delete(outputFile);
  32. }
  33. // set the path because .Net uses the "convert" utility on Windows by default
  34. System.Environment.SetEnvironmentVariable("Path", imagickPath);
  35. decimal videoLength = SharpFF.GetDuration(inputFile);
  36. // run these in parallel to save time
  37. // TODO: do all this work in a temp folder, then move the finished file to the destination
  38. Parallel.For(0, iterations, i => {
  39. string timecodeAt = SharpFF.SecondsToTimecode(i * (videoLength / iterations));
  40. SharpFF.ExecuteCommand(string.Format("-hide_banner -loglevel panic -nostats -y -ss {1} -i \"{0}\" -vframes 1 -an -f rawvideo -vcodec png -vf scale={4}:{5} \"{2}\\out_{3:000}.png\"", inputFile, timecodeAt, Path.GetDirectoryName(outputFile), i, barWidth, height));
  41. });
  42. log.Debug("Scrunching PNGs together.");
  43. // use ImageMagick to crush the generated PNGs together
  44. Process p = new Process();
  45. p.StartInfo.FileName = Path.Combine(imagickPath, "convert.exe");
  46. p.StartInfo.WorkingDirectory = Path.GetDirectoryName(outputFile);
  47. p.StartInfo.Arguments = String.Format("out_*.png +append \"{0}\"", outputFile);
  48. p.StartInfo.UseShellExecute = false;
  49. p.Start();
  50. p.WaitForExit();
  51. log.Debug("Deleting temporary work files.");
  52. // clean up the work files
  53. string[] files = Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png");
  54. foreach (string file in files) {
  55. File.Delete(file);
  56. }
  57. }
  58. }
  59. }