video.go 2.1 KB

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