Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping raw []byte video to ffmpeg - Go

Tags:

go

ffmpeg

I have a video directly from the http body in a [] byte format:

//Parsing video
videoData, err := ioutil.ReadAll(r.Body)
if err != nil {
    w.WriteHeader(UPLOAD_ERROR)
    w.Write([]byte("Error uploading the file"))
    return
}

and I need a single frame of the video and convert it to a png. This is how someone would do it with a static and encoded file using ffmpeg:

        filename := "test.mp4"
        width := 640
        height := 360
        cmd := exec.Command("ffmpeg", "-i", filename, "-vframes", "1", "-s", fmt.Sprintf("%dx%d", width, height), "-f", "singlejpeg", "-")
        var buffer bytes.Buffer
        cmd.Stdout = &buffer
        if cmd.Run() != nil {
            panic("could not generate frame")
        }

How can I achieve the same with a raw video?

A user from reddit told me that I might achieve this with https://ffmpeg.org/ffmpeg-protocols.html#pipe but I was unable to find any resources.

Any help is appreciated, thanks.

(EDIT: I tried to pipe the []byte array to ffmpeg now, but ffmpeg does not fill in my buffer:

width := 640
height := 360
log.Print("Size of the video: ", len(videoData))


cmd := exec.Command("ffmpeg", "-i", "pipe:0", "-vframes", "1", "-s", fmt.Sprintf("%dx%d", width, height), "-f", "singlejpeg", "-")
cmd.Stdin = bytes.NewReader(videoData)

var imageBuffer bytes.Buffer
cmd.Stdout = &imageBuffer
err := cmd.Run()

if err != nil {
    log.Panic("ERROR")
}

imageBytes := imageBuffer.Bytes()
log.Print("Size of the image: ", len(imageBytes))

But I get following error:

[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7ff05d002600]stream 0, offset 0x5ded: partial file

pipe:0: Invalid data found when processing input

Finishing stream 0:0 without any data written to it.

frame= 0 fps=0.0 q=0.0 Lsize= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s speed=N/A video:0kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)

like image 307
thelearner Avatar asked Apr 12 '18 15:04

thelearner


1 Answers

I need a single frame of the video and convert it to a png. This is how someone would do it with ffmpeg.

There is a popular go library that is exactly made for what you search for: https://github.com/bakape/thumbnailer

thumbnailDimensions := thumbnailer.Dims{Width: 320, Height: 130}

thumbnailOptions := thumbnailer.Options{JPEGQuality:100, MaxSourceDims:thumbnailer.Dims{}, ThumbDims:thumbnailDimensions, AcceptedMimeTypes: nil}

sourceData, thumbnail, err := thumbnailer.ProcessBuffer(videoData, thumbnailOptions)

imageBytes := thumbnail.Image.Data

They use ffmpeg under the hood, but removes the abstraction for you.

like image 119
thelearner Avatar answered Nov 17 '22 14:11

thelearner