video.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. "runtime"
  12. "github.com/oliamb/cutter"
  13. )
  14. func generateThumbnailForVideo(cacheFolder string, file string, generateOnly bool) (string, error) {
  15. if !fileExists(file) {
  16. //The user removed this file before the thumbnail is finished
  17. return "", errors.New("Source not exists")
  18. }
  19. if pkg_exists("ffmpeg") {
  20. outputFile := cacheFolder + filepath.Base(file) + ".jpg"
  21. //Get the first thumbnail using ffmpeg
  22. cmd := exec.Command("ffmpeg", "-i", file, "-ss", "00:00:05.000", "-vframes", "1", "-vf", "scale=-1:480", outputFile)
  23. //cmd := exec.Command("ffmpeg", "-i", file, "-vf", "thumbnail,scale=-1:480", "-frames:v", "1", cacheFolder+filepath.Base(file)+".jpg")
  24. _, err := cmd.CombinedOutput()
  25. if err != nil {
  26. //log.Println(err.Error())
  27. return "", err
  28. }
  29. //Resize and crop the output image
  30. if fileExists(outputFile) {
  31. imageBytes, _ := ioutil.ReadFile(outputFile)
  32. os.Remove(outputFile)
  33. img, _, err := image.Decode(bytes.NewReader(imageBytes))
  34. if err != nil {
  35. //log.Println(err.Error())
  36. } else {
  37. //Crop out the center
  38. croppedImg, err := cutter.Crop(img, cutter.Config{
  39. Width: 480,
  40. Height: 480,
  41. Mode: cutter.Centered,
  42. })
  43. if err == nil {
  44. //Write it back to the original file
  45. out, _ := os.Create(outputFile)
  46. jpeg.Encode(out, croppedImg, nil)
  47. out.Close()
  48. } else {
  49. //log.Println(err)
  50. }
  51. }
  52. }
  53. //Finished
  54. if !generateOnly && fileExists(outputFile) {
  55. //return the image as well
  56. ctx, err := getImageAsBase64(outputFile)
  57. return ctx, err
  58. } else if !fileExists(outputFile) {
  59. return "", errors.New("Image generation failed")
  60. }
  61. return "", nil
  62. } else {
  63. return "", errors.New("FFMpeg not installed. Skipping video thumbnail")
  64. }
  65. }
  66. func pkg_exists(pkgname string) bool {
  67. if runtime.GOOS == "windows" {
  68. //Check if the command already exists in windows path paramters.
  69. cmd := exec.Command("where", pkgname, "2>", "nul")
  70. _, err := cmd.CombinedOutput()
  71. if err != nil {
  72. return false
  73. }
  74. return true
  75. } else if runtime.GOOS == "linux" {
  76. cmd := exec.Command("which", pkgname)
  77. out, _ := cmd.CombinedOutput()
  78. if len(string(out)) > 1 {
  79. return true
  80. } else {
  81. return false
  82. }
  83. }
  84. return false
  85. }