-
Notifications
You must be signed in to change notification settings - Fork 60
feat(runner): VOD upload handling #1719
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
joschahenningsen
wants to merge
4
commits into
dev
Choose a base branch
from
feat/better-vod
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d6c7b66
feat(runner/spec): Add vod handling gRPC
joschahenningsen 8ecb1cd
feat(runner): Add action to determine if reencoding is required in mkvod
joschahenningsen 92724c3
fix(runner/vod): Apply suggestions from comments
joschahenningsen 1a6faeb
feat(api): Migrate VOD upload to runner
joschahenningsen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -38,7 +38,7 @@ func ConfigGinRouter( | |
|
|
||
| configGinStreamRestRouter(router, daoWrapper) | ||
| configGinUsersRouter(router, daoWrapper) | ||
| configGinCourseRouter(router, daoWrapper) | ||
| configGinCourseRouter(router, daoWrapper, manager) | ||
| configGinDownloadRouter(router, daoWrapper) | ||
| configGinDownloadICSRouter(router, daoWrapper) | ||
| configGinLectureHallApiRouter(router, daoWrapper, camService, tools.Cfg.Paths.Static) | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ import ( | |
|
|
||
| //go:generate go tool mockgen -source=upload_key.go -destination ../mock_dao/upload_key.go | ||
|
|
||
| // deprecated: delete with worker | ||
| type UploadKeyDao interface { | ||
| GetUploadKey(key string) (model.UploadKey, error) | ||
| CreateUploadKey(key string, stream uint, videoType model.VideoType) error | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -14,6 +14,7 @@ func (v VideoType) Valid() bool { | |
| return v == VideoTypeCombined || v == VideoTypePresentation || v == VideoTypeCamera | ||
| } | ||
|
|
||
| // deprecated: delete with worker | ||
| // UploadKey represents a key that is created when a user uploads a file, | ||
| // sent to the worker with the upload request and back to TUM-Live to authenticate the request. | ||
| type UploadKey struct { | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -237,6 +237,27 @@ func (m *Manager) getClient(ctx context.Context) (protobuf.RunnerServiceClient, | |
| return protobuf.NewRunnerServiceClient(conn), nil | ||
| } | ||
|
|
||
| // SendVODJob sends a VOD processing job to an available runner | ||
| func (m *Manager) SendVODJob(ctx context.Context, streamID uint, version protobuf.StreamVersion, recordingDir string) error { | ||
| client, err := m.getClient(ctx) | ||
| if err != nil { | ||
| return fmt.Errorf("get runner client: %w", err) | ||
| } | ||
|
|
||
| streamIDUint64 := uint64(streamID) | ||
| _, err = client.HandleVOD(ctx, &protobuf.HandleVODRequest{ | ||
| StreamId: &streamIDUint64, | ||
| Version: &version, | ||
| Filepath: &recordingDir, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("send HandleVOD request: %w", err) | ||
| } | ||
|
|
||
| m.logger.Info("VOD job sent to runner", "streamID", streamID, "version", version) | ||
| return nil | ||
| } | ||
|
|
||
| func (m *Manager) streamStarted(ctx context.Context, req *protobuf.StreamStartNotification) error { | ||
| // This is usually called in bursts, which introduces a chance for race conditions, | ||
| // where a stream is fetched and overwrites the url that the other requests added. | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -45,3 +45,23 @@ func (r *Runner) RequestStreamEnd(_ context.Context, req *protobuf.StreamEndRequ | |
| } | ||
| return nil, status.Errorf(codes.NotFound, "stream not found") | ||
| } | ||
|
|
||
| func (r *Runner) HandleVOD(_ context.Context, req *protobuf.HandleVODRequest) (*protobuf.HandleVODResponse, error) { | ||
| data := map[string]any{ | ||
| "streamID": req.GetStreamId(), | ||
| "streamVersion": req.GetVersion().String(), | ||
| "recordingDir": req.GetFilepath(), | ||
| } | ||
| r.log.Info("HandleVOD data constructed", "data", data) | ||
| a := []actions.Action{ | ||
| actions.CheckCodec, | ||
| actions.MkVOD, | ||
| actions.CheckVoD, | ||
| actions.MkThumb, | ||
| } | ||
|
|
||
| jID := r.RunAction(a, data, r.log.With("stream_id", req.GetStreamId(), "stream_version", req.GetVersion(), "input", req.GetFilepath())) | ||
| r.log.Info("job added", "ID", jID) | ||
|
|
||
| return &protobuf.HandleVODResponse{JobId: ptr.Take(jID)}, nil | ||
| } | ||
This file contains hidden or 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,58 @@ | ||
| package actions | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log/slog" | ||
| "path" | ||
|
|
||
| "github.com/tum-dev/gocast/runner/pkg/ffmpeg" | ||
| "github.com/tum-dev/gocast/runner/pkg/metrics" | ||
| "github.com/tum-dev/gocast/runner/protobuf" | ||
| ) | ||
|
|
||
| // CheckCodec probes the recording file and checks if it needs re-encoding. | ||
| // Sets "needsReencode" to true if the video is not h264 or exceeds 3Mbit/s bitrate, | ||
| // or if audio is not AAC. | ||
| func CheckCodec(ctx context.Context, logger *slog.Logger, _ chan *protobuf.Notification, d map[string]any, _ *metrics.Broker) error { | ||
| recordingDir, ok := d["recordingDir"].(string) | ||
| if !ok { | ||
| return AbortingError(fmt.Errorf("no recordingDir in context")) | ||
| } | ||
| recording := path.Join(recordingDir, "playlist.m3u8") | ||
|
|
||
| probe, err := ffmpeg.Probe(ctx, recording) | ||
| if err != nil { | ||
| return AbortingError(fmt.Errorf("ffprobe failed: %w", err)) | ||
| } | ||
|
|
||
| needsReencode := false | ||
| for _, stream := range probe.Streams() { | ||
| if stream.CodecType == "video" { | ||
| if stream.CodecName != "h264" { | ||
| needsReencode = true | ||
| logger.Info("video codec requires re-encoding", "codec", stream.CodecName) | ||
| break | ||
| } | ||
|
|
||
| if stream.BitRate > 3000000 { // 3 Mbit/s in bits/s | ||
| needsReencode = true | ||
| logger.Info("video bitrate exceeds 3Mbit/s", "bitrate", stream.BitRate) | ||
| break | ||
| } | ||
| } | ||
|
|
||
| if stream.CodecType == "audio" { | ||
| if stream.CodecName != "aac" { | ||
| needsReencode = true | ||
| logger.Info("audio codec requires re-encoding", "codec", stream.CodecName) | ||
| break | ||
| } | ||
| } | ||
| } | ||
|
|
||
| d["needsReencode"] = needsReencode | ||
| logger.Info("codec check completed", "needsReencode", needsReencode) | ||
|
|
||
| return nil | ||
| } |
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -47,13 +47,12 @@ func MkThumb(_ context.Context, logger *slog.Logger, notify chan *protobuf.Notif | |
| return nil | ||
| } | ||
|
|
||
| // createVideoThumbnail creates a thumbnail from the given video file | ||
|
|
||
| const ( | ||
| thumbnailWidth = 720 // Width of the generated thumbnail in pixels | ||
| jpegCompressionQuality = 90 // JPEG compression quality (0-100) | ||
| ) | ||
|
|
||
| // createVideoThumbnail creates a thumbnail from the given video file | ||
| func createVideoThumbnail(source string) ([]byte, error) { | ||
| g, err := thumbgen.New(source, thumbnailWidth, 1, "", thumbgen.WithJpegCompression(jpegCompressionQuality)) | ||
| if err != nil { | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -31,9 +31,21 @@ func MkVOD(ctx context.Context, logger *slog.Logger, notify chan *protobuf.Notif | |
| if !ok { | ||
| return AbortingError(fmt.Errorf("no stream version in context")) | ||
| } | ||
| recordingDir, ok := d["recordingDir"].(string) | ||
| if !ok { | ||
| return AbortingError(fmt.Errorf("no recordingDir in context")) | ||
| var recording string | ||
| if rec, ok := d["recording"]; ok { | ||
| if recStr, ok := rec.(string); ok { | ||
| recording = recStr | ||
| } else { | ||
| return AbortingError(fmt.Errorf("recording value is not a string")) | ||
| } | ||
| } else if dir, ok := d["recordingDir"]; ok { | ||
| if dirStr, ok := dir.(string); ok { | ||
| recording = path.Join(dirStr, "playlist.m3u8") | ||
| } else { | ||
| return AbortingError(fmt.Errorf("recordingDir value is not a string")) | ||
| } | ||
| } else { | ||
| return AbortingError(fmt.Errorf("no recording or recordingDir in context")) | ||
| } | ||
|
|
||
| metrics.ConvertingProgresses.With(metrics.With().Stream(streamID).L()).Inc() | ||
|
|
@@ -45,7 +57,28 @@ func MkVOD(ctx context.Context, logger *slog.Logger, notify chan *protobuf.Notif | |
| return AbortingError(fmt.Errorf("create VOD directory: %w", err)) | ||
| } | ||
|
|
||
| err = convertStream(ctx, logger, streamID, path.Join(recordingDir, "playlist.m3u8"), vodDir, "playlist.m3u8") | ||
| // Check if re-encoding is needed | ||
| var reencode bool | ||
| if needsReencode, ok := d["needsReencode"]; ok { | ||
| if reencodeVal, ok := needsReencode.(bool); ok { | ||
| reencode = reencodeVal | ||
| } else { | ||
| return AbortingError(fmt.Errorf("needsReencode is not a bool")) | ||
| } | ||
| } | ||
|
|
||
| var videoCodec, audioCodec string | ||
| if reencode { | ||
| logger.Info("re-encoding required, transcoding video") | ||
| videoCodec = "libx264" | ||
| audioCodec = "aac" | ||
| } else { | ||
| logger.Info("no re-encoding needed, using copy codec") | ||
| videoCodec = "copy" | ||
| audioCodec = "copy" | ||
| } | ||
|
|
||
| err = convertStream(ctx, logger, streamID, recording, vodDir, "playlist.m3u8", videoCodec, audioCodec) | ||
| if err != nil { | ||
| return AbortingError(fmt.Errorf("convert stream: %w", err)) | ||
| } | ||
|
|
@@ -67,9 +100,18 @@ func MkVOD(ctx context.Context, logger *slog.Logger, notify chan *protobuf.Notif | |
| return nil | ||
| } | ||
|
|
||
| func convertStream(ctx context.Context, logger *slog.Logger, streamID uint64, streamPath, vodDir string, playlistName string) error { | ||
| func convertStream(ctx context.Context, logger *slog.Logger, streamID uint64, streamPath, vodDir string, playlistName string, videoCodec string, audioCodec string) error { | ||
| input := "-i " + streamPath | ||
| options := "-c copy -f hls -hls_time 20 -hls_playlist_type vod -hls_flags append_list -hls_segment_filename " + path.Join(vodDir, "%05d.ts") + " " + path.Join(vodDir, playlistName) | ||
|
|
||
| // Build codec options based on parameters | ||
| codecOpts := fmt.Sprintf("-c:v %s -c:a %s", videoCodec, audioCodec) | ||
|
|
||
| // Add bitrate limit if re-encoding video | ||
| if videoCodec != "copy" { | ||
| codecOpts += " -b:v 3M" | ||
| } | ||
|
|
||
| options := codecOpts + " -f hls -hls_time 20 -hls_playlist_type vod -hls_flags append_list -hls_segment_filename " + path.Join(vodDir, "%05d.ts") + " " + path.Join(vodDir, playlistName) | ||
|
|
||
| args := strings.Split(input, " ") | ||
| args = append(args, strings.Split(options, " ")...) | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Uncontrolled data used in path expression High
Copilot Autofix
AI 8 months ago
To fix the vulnerability, ensure that user-controlled data (
req.VideoType) cannot contain directory traversals or path separators when used in file paths. The safest way is to only allow known-safe values: either check that the input matches an allow list, or sanitize it by validating against a regular expression that permits only expected characters (such as alphanumerics and underscores). In this case, sincereq.VideoTypeappears to be an enum-like field with aValid()check, we should also ensure that its string representation does not contain path separators or"..". Thus, before constructingstreamDir, check ifstring(req.VideoType)contains'/','\\', or"..". If so, return an error. This edit should be added just after theValid()check and before constructingstreamDiron line 491. No additional imports are necessary (we already import"strings"), and no modifications to files other thanapi/courses.goare required.