-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.go
More file actions
464 lines (420 loc) · 11.1 KB
/
Copy pathcontroller.go
File metadata and controls
464 lines (420 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package main
import (
"bytes"
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
type CaptureStatus struct {
Running bool `json:"running"`
SessionID string `json:"session_id,omitempty"`
StartedAt time.Time `json:"started_at,omitzero"`
FramesThisRun int `json:"frames_this_run"`
LastFrameNumber int `json:"last_frame_number"`
LastFrameAt time.Time `json:"last_frame_at,omitzero"`
LastError string `json:"last_error,omitempty"`
}
type CompileStatus struct {
Running bool `json:"running"`
StartedAt time.Time `json:"started_at,omitzero"`
Output string `json:"output,omitempty"`
LastError string `json:"last_error,omitempty"`
Warning string `json:"warning,omitempty"`
Encoder string `json:"encoder,omitempty"`
}
type Controller struct {
mu sync.Mutex
cfg *Config
store *SessionStore
capturer Capturer
// capture state
running bool
sessionID string
startedAt time.Time
framesThisRun int
lastFrameNumber int
lastFrameAt time.Time
lastErr string
cancel context.CancelFunc
done chan struct{}
// viewfinder state (shares c.mu with capture state so Start can sequence
// teardown deterministically)
viewfinderRunning bool
viewfinderCancel context.CancelFunc
viewfinderDone chan struct{}
viewfinderLastErr string
// compile state, keyed by session id
compileMu sync.Mutex
compileStates map[string]*CompileStatus
}
func NewController(cfg *Config, store *SessionStore, capturer Capturer) *Controller {
return &Controller{
cfg: cfg,
store: store,
capturer: capturer,
compileStates: map[string]*CompileStatus{},
}
}
func (c *Controller) Status() CaptureStatus {
c.mu.Lock()
defer c.mu.Unlock()
return CaptureStatus{
Running: c.running,
SessionID: c.sessionID,
StartedAt: c.startedAt,
FramesThisRun: c.framesThisRun,
LastFrameNumber: c.lastFrameNumber,
LastFrameAt: c.lastFrameAt,
LastError: c.lastErr,
}
}
func (c *Controller) ActiveSession() (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
return c.sessionID, c.running
}
func (c *Controller) Start(sessionID string) error {
c.mu.Lock()
// If the viewfinder is open, tear it down and wait for ffmpeg to actually
// exit before opening /dev/video0 from the capture loop — otherwise we'd
// rely on captureWithRetry to paper over an EBUSY race.
if c.viewfinderRunning {
cancel := c.viewfinderCancel
done := c.viewfinderDone
c.mu.Unlock()
if cancel != nil {
cancel()
}
if done != nil {
<-done
}
c.mu.Lock()
}
if c.running {
active := c.sessionID
c.mu.Unlock()
if active == sessionID {
return errors.New("this session is already capturing")
}
return fmt.Errorf("another session (%s) is already capturing", active)
}
sess, err := c.store.Get(sessionID)
if err != nil {
c.mu.Unlock()
return err
}
if err := sess.Settings.Validate(); err != nil {
c.mu.Unlock()
return err
}
startFrom, err := c.store.ScanLastFrameNumber(sessionID)
if err != nil {
c.mu.Unlock()
return err
}
ctx, cancel := context.WithCancel(context.Background())
c.running = true
c.sessionID = sessionID
c.startedAt = time.Now()
c.framesThisRun = 0
c.lastFrameNumber = startFrom
c.lastFrameAt = time.Time{}
c.lastErr = ""
c.cancel = cancel
c.done = make(chan struct{})
c.mu.Unlock()
go c.run(ctx, sessionID, startFrom)
return nil
}
func (c *Controller) run(ctx context.Context, sessionID string, startFrom int) {
defer func() {
c.mu.Lock()
c.running = false
done := c.done
c.done = nil
c.cancel = nil
c.mu.Unlock()
if done != nil {
close(done)
}
}()
sess, err := c.store.Get(sessionID)
if err != nil {
c.setLastErr(err.Error())
return
}
interval := max(time.Duration(sess.Settings.IntervalSec)*time.Second, time.Second)
framesDir := c.store.FramesDir(sessionID)
if err := os.MkdirAll(framesDir, 0o755); err != nil {
c.setLastErr(err.Error())
return
}
current := startFrom
persistEvery := 10
lastPersist := time.Now()
maxPersistInterval := 30 * time.Second
// Capture one frame immediately, then on each tick.
tick := func() {
current++
framePath := filepath.Join(framesDir, fmt.Sprintf("frame_%06d.jpg", current))
err := c.captureWithRetry(ctx, sess, framePath)
if err != nil {
current-- // free the number; retry on next tick
c.setLastErr(err.Error())
log.Printf("capture error (session=%s): %v", sessionID, err)
return
}
now := time.Now()
sess.LastFrameNumber = current
sess.LastFrameAt = now
c.mu.Lock()
c.framesThisRun++
c.lastFrameNumber = current
c.lastFrameAt = now
c.mu.Unlock()
if c.framesThisRun%persistEvery == 0 || time.Since(lastPersist) > maxPersistInterval {
if err := c.store.Save(sess); err != nil {
log.Printf("session save error: %v", err)
}
lastPersist = time.Now()
}
}
tick()
if ctx.Err() != nil {
_ = c.store.Save(sess)
return
}
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
_ = c.store.Save(sess)
return
case <-t.C:
tick()
}
}
}
func (c *Controller) Stop() error {
c.mu.Lock()
if !c.running {
c.mu.Unlock()
return errors.New("no session is currently capturing")
}
cancel := c.cancel
done := c.done
c.mu.Unlock()
if cancel != nil {
cancel()
}
if done != nil {
<-done
}
return nil
}
// captureWithRetry handles the V4L2 quirk where the kernel briefly keeps
// /dev/video0 marked busy after the previous ffmpeg child exits. We retry
// only on that specific error (otherwise a real failure should surface
// immediately on the next tick).
func (c *Controller) captureWithRetry(ctx context.Context, sess *Session, framePath string) error {
const maxAttempts = 4
backoff := 200 * time.Millisecond
var err error
for attempt := 1; attempt <= maxAttempts; attempt++ {
captureCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
err = c.capturer.Capture(captureCtx, sess, framePath)
cancel()
if err == nil {
return nil
}
if ctx.Err() != nil {
return err
}
if attempt == maxAttempts || !isDeviceBusyErr(err) {
return err
}
select {
case <-ctx.Done():
return err
case <-time.After(backoff):
}
backoff *= 2
}
return err
}
func isDeviceBusyErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "device or resource busy") ||
strings.Contains(s, "resource busy") ||
strings.Contains(s, "ebusy")
}
func (c *Controller) setLastErr(msg string) {
c.mu.Lock()
c.lastErr = msg
c.mu.Unlock()
}
// AcquireViewfinder reserves the camera for a viewfinder stream. Returns a
// derived context (cancelled when the viewer disconnects OR when a capture
// session starts) and a release callback the handler must defer.
func (c *Controller) AcquireViewfinder(parent context.Context) (context.Context, func(), error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.running {
return nil, nil, errors.New("cannot start viewfinder while a session is capturing")
}
if c.viewfinderRunning {
return nil, nil, errors.New("viewfinder is already running")
}
ctx, cancel := context.WithCancel(parent)
done := make(chan struct{})
c.viewfinderRunning = true
c.viewfinderCancel = cancel
c.viewfinderDone = done
c.viewfinderLastErr = ""
release := func() {
c.mu.Lock()
c.viewfinderRunning = false
c.viewfinderCancel = nil
c.viewfinderDone = nil
c.mu.Unlock()
cancel()
close(done)
}
return ctx, release, nil
}
func (c *Controller) StopViewfinder() {
c.mu.Lock()
cancel := c.viewfinderCancel
c.mu.Unlock()
if cancel != nil {
cancel()
}
}
func (c *Controller) SetViewfinderError(msg string) {
c.mu.Lock()
c.viewfinderLastErr = msg
c.mu.Unlock()
}
func (c *Controller) ViewfinderStatus() (running, capturing bool, lastErr string) {
c.mu.Lock()
defer c.mu.Unlock()
return c.viewfinderRunning, c.running, c.viewfinderLastErr
}
func (c *Controller) CompileStatus(sessionID string) CompileStatus {
c.compileMu.Lock()
defer c.compileMu.Unlock()
if st, ok := c.compileStates[sessionID]; ok {
return *st
}
return CompileStatus{}
}
func (c *Controller) AnyCompileRunning() (string, bool) {
c.compileMu.Lock()
defer c.compileMu.Unlock()
for id, st := range c.compileStates {
if st.Running {
return id, true
}
}
return "", false
}
func (c *Controller) Compile(sessionID string) error {
if active, running := c.ActiveSession(); running && active == sessionID {
return errors.New("cannot compile while this session is capturing")
}
if id, busy := c.AnyCompileRunning(); busy {
return fmt.Errorf("another compile is already running (session %s)", id)
}
sess, err := c.store.Get(sessionID)
if err != nil {
return err
}
if sess.LastFrameNumber == 0 {
// Double-check by scanning disk, in case state is out of sync.
n, _ := c.store.ScanLastFrameNumber(sessionID)
if n == 0 {
return errors.New("no frames to compile")
}
}
first, err := c.store.FirstFrameNumber(sessionID)
if err != nil {
return err
}
if first == 0 {
return errors.New("no frames to compile")
}
framesDir := c.store.FramesDir(sessionID)
videosDir := c.store.VideosDir(sessionID)
if err := os.MkdirAll(videosDir, 0o755); err != nil {
return err
}
outName := fmt.Sprintf("timelapse-%s.mp4", time.Now().Format("20060102-150405"))
outPath := filepath.Join(videosDir, outName)
c.compileMu.Lock()
c.compileStates[sessionID] = &CompileStatus{
Running: true,
StartedAt: time.Now(),
}
c.compileMu.Unlock()
go c.runCompile(sessionID, framesDir, outPath, outName, sess.Settings.FPS, first)
return nil
}
func (c *Controller) runCompile(sessionID, framesDir, outPath, outName string, fps, startNumber int) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Hour)
defer cancel()
hwEnabled, hwAvailable, bitrate := c.cfg.EncodeSettings()
tryHW := hwEnabled && hwAvailable
encoderUsed := "libx264"
var warning string
var runErr error
var stderr bytes.Buffer
if tryHW {
encoderUsed = "h264_v4l2m2m"
args := compileArgsHW(framesDir, outPath, fps, startNumber, bitrate)
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
cmd.Stderr = &stderr
runErr = cmd.Run()
if runErr != nil && ctx.Err() == nil {
// Hardware path failed — fall back to libx264 and keep a warning.
warning = fmt.Sprintf("hardware encoder (h264_v4l2m2m) failed; falling back to libx264: %s", strings.TrimSpace(stderr.String()))
log.Printf("compile (session=%s): %s", sessionID, warning)
_ = os.Remove(outPath)
stderr.Reset()
encoderUsed = "libx264"
args = compileArgs(framesDir, outPath, fps, startNumber)
cmd = exec.CommandContext(ctx, "ffmpeg", args...)
cmd.Stderr = &stderr
runErr = cmd.Run()
}
} else {
args := compileArgs(framesDir, outPath, fps, startNumber)
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
cmd.Stderr = &stderr
runErr = cmd.Run()
}
c.compileMu.Lock()
st := c.compileStates[sessionID]
st.Running = false
st.Encoder = encoderUsed
st.Warning = warning
if runErr != nil {
_ = os.Remove(outPath)
st.LastError = fmt.Sprintf("compile failed: %v: %s", runErr, stderr.String())
st.Output = ""
} else {
st.LastError = ""
st.Output = outName
}
c.compileMu.Unlock()
}