-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
233 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
package handlers | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
"path" | ||
"strconv" | ||
"strings" | ||
|
||
"github.com/aws/aws-sdk-go/aws/awserr" | ||
"github.com/aws/aws-sdk-go/service/s3" | ||
"github.com/grafov/m3u8" | ||
"github.com/julienschmidt/httprouter" | ||
"github.com/livepeer/catalyst-api/clients" | ||
caterrs "github.com/livepeer/catalyst-api/errors" | ||
"github.com/livepeer/go-tools/drivers" | ||
ffmpeg "github.com/u2takey/ffmpeg-go" | ||
) | ||
|
||
type ImageHandler struct { | ||
PublicBucketURLs []*url.URL | ||
} | ||
|
||
func NewImageHandler(urls []*url.URL) *ImageHandler { | ||
return &ImageHandler{ | ||
PublicBucketURLs: urls, | ||
} | ||
} | ||
|
||
func (p *ImageHandler) Handle(w http.ResponseWriter, req *http.Request, params httprouter.Params) { | ||
timeString := req.URL.Query().Get("time") | ||
time, err := strconv.ParseFloat(timeString, 64) | ||
if err != nil { | ||
w.WriteHeader(http.StatusBadRequest) | ||
w.Write([]byte("failed to parse time")) | ||
return | ||
} | ||
|
||
playbackID := params.ByName("playbackID") | ||
if playbackID == "" { | ||
w.WriteHeader(http.StatusBadRequest) | ||
w.Write([]byte("playbackID was empty")) | ||
return | ||
} | ||
|
||
err = p.handle(w, playbackID, time) | ||
if err != nil { | ||
log.Println(err) | ||
// TODO convert err to status code | ||
w.WriteHeader(500) | ||
} | ||
} | ||
|
||
func (p *ImageHandler) handle(w http.ResponseWriter, playbackID string, time float64) error { | ||
var ( | ||
page drivers.PageInfo | ||
err error | ||
manifestFile string | ||
segmentFile string | ||
bucketLocation *url.URL | ||
) | ||
// list the contents of the playbackID folder in storage and check for an HLS manifest | ||
for _, bucket := range p.PublicBucketURLs { | ||
bucketLocation = bucket.JoinPath(playbackID, "/") | ||
page, err = clients.ListOSURL(context.Background(), bucketLocation.String()) | ||
if err == nil { | ||
break | ||
} | ||
// if this is the final bucket in the list then the error set here will be used in the final return | ||
var awsErr awserr.Error | ||
if errors.As(err, &awsErr) && awsErr.Code() == s3.ErrCodeNoSuchKey || | ||
strings.Contains(err.Error(), "no such file") { | ||
err = fmt.Errorf("invalid request: %w %w", caterrs.ObjectNotFoundError, err) | ||
} else { | ||
err = fmt.Errorf("failed to get file for playback: %w", err) | ||
} | ||
} | ||
if err != nil { | ||
return err | ||
} | ||
for _, file := range page.Files() { | ||
if strings.HasSuffix(file.Name, "m3u8") { | ||
manifestFile = file.Name | ||
break | ||
} | ||
} | ||
if manifestFile == "" { | ||
return fmt.Errorf("playbackID not found: %w", caterrs.ObjectNotFoundError) | ||
} | ||
|
||
// find the segment required | ||
fileInfoReader, err := clients.GetOSURL(bucketLocation.JoinPath(manifestFile).String(), "") | ||
if err != nil { | ||
return fmt.Errorf("failed to read manifest: %w", err) | ||
} | ||
manifest, _, err := m3u8.DecodeFrom(fileInfoReader.Body, true) | ||
if err != nil { | ||
return err | ||
} | ||
// TODO check if master playlist | ||
|
||
mediaPlaylist, ok := manifest.(*m3u8.MediaPlaylist) | ||
if !ok || mediaPlaylist == nil { | ||
return fmt.Errorf("failed to parse playlist as MediaPlaylist") | ||
} | ||
currentTime := 0.0 | ||
for _, segment := range mediaPlaylist.GetAllSegments() { | ||
currentTime += segment.Duration | ||
if currentTime > time { | ||
segmentFile = segment.URI | ||
break | ||
} | ||
} | ||
if segmentFile == "" { | ||
return fmt.Errorf("playbackID media not found: %w", caterrs.ObjectNotFoundError) | ||
} | ||
|
||
tmpDir, err := os.MkdirTemp(os.TempDir(), "image-api-*") | ||
if err != nil { | ||
return fmt.Errorf("temp file creation failed: %w", err) | ||
} | ||
defer os.RemoveAll(tmpDir) | ||
|
||
// download the segment | ||
fileInfoReader, err = clients.GetOSURL(bucketLocation.JoinPath(segmentFile).String(), "") | ||
if err != nil { | ||
return fmt.Errorf("failed to get media: %w", err) | ||
} | ||
segBytes, err := io.ReadAll(fileInfoReader.Body) | ||
if err != nil { | ||
return fmt.Errorf("failed to get bytes: %w", err) | ||
} | ||
|
||
inputFile := path.Join(tmpDir, "in.ts") | ||
if err = os.WriteFile(inputFile, segBytes, 0644); err != nil { | ||
return fmt.Errorf("failed to write input file: %w", err) | ||
} | ||
outputFile := path.Join(tmpDir, "out.jpg") | ||
|
||
err = ffmpeg. | ||
Input(inputFile). | ||
Output( | ||
outputFile, | ||
ffmpeg.KwArgs{ | ||
"ss": fmt.Sprintf("00:00:0%d", int64(currentTime-time)), | ||
"vframes": "1", | ||
"vf": "scale=320:240:force_original_aspect_ratio=decrease", | ||
}, | ||
).OverWriteOutput().ErrorToStdOut().Run() | ||
if err != nil { | ||
return fmt.Errorf("ffmpeg failed: %w", err) | ||
} | ||
|
||
bs, err := os.ReadFile(outputFile) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
w.WriteHeader(http.StatusOK) | ||
count, err := w.Write(bs) | ||
if err != nil { | ||
log.Println("image handler failed to write response", err) | ||
} else { | ||
log.Println("image handler wrote response", count) | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package handlers | ||
|
||
import ( | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/http/httptest" | ||
"net/url" | ||
"os" | ||
"testing" | ||
|
||
"github.com/julienschmidt/httprouter" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestImageHandler_Handle(t *testing.T) { | ||
wd, err := os.Getwd() | ||
require.NoError(t, err) | ||
handler := &ImageHandler{ | ||
PublicBucketURLs: []*url.URL{{Scheme: "file", Path: wd + "/../test"}}, | ||
} | ||
tests := []struct { | ||
name string | ||
}{ | ||
{ | ||
name: "happy", | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
w := httptest.NewRecorder() | ||
req, err := http.NewRequest(http.MethodGet, "?time=5", nil) | ||
require.NoError(t, err) | ||
handler.Handle(w, req, []httprouter.Param{{ | ||
Key: "playbackID", | ||
Value: "fixtures", // just use the fixtures directory for testing | ||
}}) | ||
resp := w.Result() | ||
log.Println(resp.StatusCode) | ||
respBytes, err := io.ReadAll(resp.Body) | ||
require.NoError(t, err) | ||
|
||
outfile, err := os.CreateTemp(os.TempDir(), "out*.jpg") | ||
require.NoError(t, err) | ||
defer os.Remove(outfile.Name()) | ||
_, err = outfile.Write(respBytes) | ||
require.NoError(t, err) | ||
log.Println(outfile.Name()) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters