From 3c1305611168ba06b50501cf5380b30d2a7c9e0b Mon Sep 17 00:00:00 2001 From: Darius Rapalis Date: Sun, 16 Mar 2025 10:24:09 +0200 Subject: [PATCH] video aspect ratios categorized --- handler_upload_video.go | 22 +++++++++++++++++++++- main.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/handler_upload_video.go b/handler_upload_video.go index 7265c12..acb6174 100644 --- a/handler_upload_video.go +++ b/handler_upload_video.go @@ -113,9 +113,29 @@ func (cfg *apiConfig) handlerUploadVideo(w http.ResponseWriter, r *http.Request) return } + ratio, err := getVideoAspectRatio(tempFile.Name()) + if err != nil { + respondWithError(w, http.StatusInternalServerError, "Couldn't get aspect ratio", err) + return + } + + var prefix string + + switch ratio { + case "16:9": + prefix = "landscape" + break + case "9:16": + prefix = "portrait" + break + default: + prefix = "other" + break + } + tempFile.Seek(0, io.SeekStart) - fileName := videoPathName + extension + fileName := prefix + "/" + videoPathName + extension _, err = cfg.s3Client.PutObject(context.Background(), &s3.PutObjectInput{ Bucket: &cfg.s3Bucket, diff --git a/main.go b/main.go index 1dbc93d..dc835bf 100644 --- a/main.go +++ b/main.go @@ -1,12 +1,16 @@ package main import ( + "bytes" "context" + "encoding/json" + "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" "log" "net/http" "os" + "os/exec" "github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/database" @@ -32,6 +36,38 @@ type thumbnail struct { mediaType string } +func getVideoAspectRatio(filePath string) (string, error) { + cmd := exec.Command("ffprobe", "-v", "error", "-print_format", "json", "-show_streams", filePath) + var buffer bytes.Buffer + cmd.Stdout = &buffer + err := cmd.Run() + if err != nil { + return "", err + } + + type Stream struct { + Index int `json:"index"` + Width int `json:"width"` + Height int `json:"height"` + DisplayAspectRatio string `json:"display_aspect_ratio"` + } + + type VideoInfo struct { + Streams []Stream `json:"streams"` + } + + var videoInfo VideoInfo + + err = json.Unmarshal(buffer.Bytes(), &videoInfo) + if err != nil { + fmt.Println(err) + return "", err + } + + return videoInfo.Streams[0].DisplayAspectRatio, nil + +} + func main() { godotenv.Load(".env")