video.go 2.1 KB

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