From 4b93d4d9f576a5820e8bc0e734f046a69412573f Mon Sep 17 00:00:00 2001 From: Harry Felton Date: Wed, 7 Jul 2021 16:45:58 +1200 Subject: [PATCH] feat(context): added WithContext method for Transcoder --- ffmpeg/ffmpeg.go | 22 ++++++++++++++++++++-- transcoder.go | 2 ++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/ffmpeg/ffmpeg.go b/ffmpeg/ffmpeg.go index d67b2e9..ce262f8 100644 --- a/ffmpeg/ffmpeg.go +++ b/ffmpeg/ffmpeg.go @@ -3,6 +3,7 @@ package ffmpeg import ( "bufio" "bytes" + "context" "encoding/json" "errors" "fmt" @@ -28,6 +29,7 @@ type Transcoder struct { outputPipeReader *io.ReadCloser inputPipeWriter *io.WriteCloser outputPipeWriter *io.WriteCloser + commandContext *context.Context } // New ... @@ -82,7 +84,15 @@ func (t *Transcoder) Start(opts transcoder.Options) (<-chan transcoder.Progress, } // Initialize command - cmd := exec.Command(t.config.FfmpegBinPath, args...) + // If a context object was supplied to this Transcoder before + // starting, use this context when creating the command to allow + // the command to be killed when the context expires + var cmd *exec.Cmd + if t.commandContext == nil { + cmd = exec.Command(t.config.FfmpegBinPath, args...) + } else { + cmd = exec.CommandContext(*t.commandContext, t.config.FfmpegBinPath, args...) + } // If progresss enabled, get stderr pipe and start progress process if t.config.ProgressEnabled && !t.config.Verbose { @@ -160,6 +170,14 @@ func (t *Transcoder) WithAdditionalOptions(opts transcoder.Options) transcoder.T return t } +// WithContext is to be used on a Transcoder *before Starting* to +// pass in a context.Context object that can be used to kill +// a running transcoder process. Usage of this method is optional +func (t *Transcoder) WithContext(ctx *context.Context) transcoder.Transcoder { + t.commandContext = ctx + return t +} + // validate ... func (t *Transcoder) validate() error { if t.config.FfmpegBinPath == "" { @@ -192,7 +210,7 @@ func (t *Transcoder) validate() error { } // GetMetadata Returns metadata for the specified input file -func (t *Transcoder) GetMetadata() ( transcoder.Metadata, error) { +func (t *Transcoder) GetMetadata() (transcoder.Metadata, error) { if t.config.FfprobeBinPath != "" { var outb, errb bytes.Buffer diff --git a/transcoder.go b/transcoder.go index 9e58206..c93bc4a 100644 --- a/transcoder.go +++ b/transcoder.go @@ -1,6 +1,7 @@ package transcoder import ( + "context" "io" ) @@ -13,5 +14,6 @@ type Transcoder interface { OutputPipe(w *io.WriteCloser, r *io.ReadCloser) Transcoder WithOptions(opts Options) Transcoder WithAdditionalOptions(opts Options) Transcoder + WithContext(ctx *context.Context) Transcoder GetMetadata() (Metadata, error) }