@@ -3,6 +3,7 @@ package ffmpeg
3
3
import (
4
4
"bufio"
5
5
"bytes"
6
+ "context"
6
7
"encoding/json"
7
8
"errors"
8
9
"fmt"
@@ -29,6 +30,7 @@ type Transcoder struct {
29
30
outputPipeReader io.ReadCloser
30
31
inputPipeWriter io.WriteCloser
31
32
outputPipeWriter io.WriteCloser
33
+ commandContext context.Context
32
34
}
33
35
34
36
// New ...
@@ -90,7 +92,15 @@ func (t *Transcoder) Start(opts transcoder.Options) (<-chan transcoder.Progress,
90
92
}
91
93
92
94
// Initialize command
93
- cmd := exec .Command (t .config .FfmpegBinPath , args ... )
95
+ // If a context object was supplied to this Transcoder before
96
+ // starting, use this context when creating the command to allow
97
+ // the command to be killed when the context expires
98
+ var cmd * exec.Cmd
99
+ if t .commandContext == nil {
100
+ cmd = exec .Command (t .config .FfmpegBinPath , args ... )
101
+ } else {
102
+ cmd = exec .CommandContext (t .commandContext , t .config .FfmpegBinPath , args ... )
103
+ }
94
104
cmd .Env = append (t .config .Env , os .Environ ()... )
95
105
cmd .Dir = t .config .Dir
96
106
@@ -177,6 +187,14 @@ func (t *Transcoder) WithAdditionalOptions(opts transcoder.Options) transcoder.T
177
187
return t
178
188
}
179
189
190
+ // WithContext is to be used on a Transcoder *before Starting* to
191
+ // pass in a context.Context object that can be used to kill
192
+ // a running transcoder process. Usage of this method is optional
193
+ func (t * Transcoder ) WithContext (ctx context.Context ) transcoder.Transcoder {
194
+ t .commandContext = ctx
195
+ return t
196
+ }
197
+
180
198
// validate ...
181
199
func (t * Transcoder ) validate () error {
182
200
if t .config .FfmpegBinPath == "" {
@@ -222,7 +240,12 @@ func (t *Transcoder) GetMetadata() (transcoder.Metadata, error) {
222
240
223
241
args := []string {"-i" , input , "-print_format" , "json" , "-show_format" , "-show_streams" , "-show_error" }
224
242
225
- cmd := exec .Command (t .config .FfprobeBinPath , args ... )
243
+ var cmd * exec.Cmd
244
+ if t .commandContext == nil {
245
+ cmd = exec .Command (t .config .FfprobeBinPath , args ... )
246
+ } else {
247
+ cmd = exec .CommandContext (t .commandContext , t .config .FfprobeBinPath , args ... )
248
+ }
226
249
cmd .Stdout = & outb
227
250
cmd .Stderr = & errb
228
251
cmd .Env = append (t .config .Env , os .Environ ()... )
0 commit comments