video.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package metadata
  2. import (
  3. "bytes"
  4. "errors"
  5. "image"
  6. "image/jpeg"
  7. "os/exec"
  8. "path/filepath"
  9. "github.com/oliamb/cutter"
  10. "imuslab.com/arozos/mod/apt"
  11. "imuslab.com/arozos/mod/filesystem"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. func generateThumbnailForVideo(fsh *filesystem.FileSystemHandler, cacheFolder string, file string, generateOnly bool) (string, error) {
  15. if fsh.RequireBuffer {
  16. return "", nil
  17. }
  18. fshAbs := fsh.FileSystemAbstraction
  19. if !fshAbs.FileExists(file) {
  20. //The user removed this file before the thumbnail is finished
  21. return "", errors.New("Source not exists")
  22. }
  23. if pkg_exists("ffmpeg") {
  24. outputFile := cacheFolder + filepath.Base(file) + ".jpg"
  25. //Get the first thumbnail using ffmpeg
  26. cmd := exec.Command("ffmpeg", "-i", file, "-ss", "00:00:05.000", "-vframes", "1", "-vf", "scale=-1:480", outputFile)
  27. //cmd := exec.Command("ffmpeg", "-i", file, "-vf", "thumbnail,scale=-1:480", "-frames:v", "1", cacheFolder+filepath.Base(file)+".jpg")
  28. _, err := cmd.CombinedOutput()
  29. if err != nil {
  30. //log.Println(err.Error())
  31. return "", err
  32. }
  33. //Resize and crop the output image
  34. if fshAbs.FileExists(outputFile) {
  35. imageBytes, _ := fshAbs.ReadFile(outputFile)
  36. fshAbs.Remove(outputFile)
  37. img, _, err := image.Decode(bytes.NewReader(imageBytes))
  38. if err != nil {
  39. //log.Println(err.Error())
  40. } else {
  41. //Crop out the center
  42. croppedImg, err := cutter.Crop(img, cutter.Config{
  43. Width: 480,
  44. Height: 480,
  45. Mode: cutter.Centered,
  46. })
  47. if err == nil {
  48. //Write it back to the original file
  49. out, _ := fshAbs.Create(outputFile)
  50. jpeg.Encode(out, croppedImg, nil)
  51. out.Close()
  52. } else {
  53. //log.Println(err)
  54. }
  55. }
  56. }
  57. //Finished
  58. if !generateOnly && fshAbs.FileExists(outputFile) {
  59. //return the image as well
  60. ctx, err := getImageAsBase64(fsh, outputFile)
  61. return ctx, err
  62. } else if !utils.FileExists(outputFile) {
  63. return "", errors.New("Image generation failed")
  64. }
  65. return "", nil
  66. } else {
  67. return "", errors.New("FFMpeg not installed. Skipping video thumbnail")
  68. }
  69. }
  70. func pkg_exists(pkgname string) bool {
  71. installed, _ := apt.PackageExists(pkgname)
  72. return installed
  73. }