-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.go
More file actions
498 lines (466 loc) · 12 KB
/
Copy pathstream.go
File metadata and controls
498 lines (466 loc) · 12 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package gogige
import (
"context"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/aaronmurniadi/gogige/gvcp"
"github.com/aaronmurniadi/gogige/gvsp"
"github.com/aaronmurniadi/gogige/internal/color"
)
var errStreamNotOpen = errors.New("gige: stream not open")
// Session is a persistent GVSP stream session. It implements Grabber.
type Session struct {
cam *Camera
stream *gvsp.Stream
opened atomic.Bool
mu sync.Mutex
ownCam bool // if true, Close() closes cam
ip string
packetSize int
component Component
hb *gvcp.Heartbeat
}
// NewSession returns an empty GVSP session (Connects on Open if no camera set).
func NewSession() *Session { return &Session{component: ComponentColor} }
// NewFromCamera returns a Session that streams using cam without taking ownership.
func NewFromCamera(cam *Camera) *Session {
return &Session{cam: cam, component: ComponentColor}
}
// SetComponent selects which BSCF/SFNC component Grab returns (color/depth/mono).
func (s *Session) SetComponent(c Component) {
if s == nil || c == ComponentUnknown {
return
}
s.mu.Lock()
s.component = c
s.mu.Unlock()
}
// Open connects (if needed), starts GVSP, and begins acquisition.
func (s *Session) Open(ip string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.opened.Load() {
return nil
}
s.ip = ip
if s.cam == nil {
cam, err := Connect(ip)
if err != nil {
return err
}
s.cam = cam
s.ownCam = true
}
stream, err := gvsp.ListenStream(0)
if err != nil {
return err
}
s.stream = stream
if g := s.cam.GVCP(); g != nil {
stream.SetResender(func(blockID uint64, first, last uint32, extended bool) {
_ = g.RequestResend(0, blockID, first, last, extended)
})
}
if got := stream.RecvBuffer(); got > 0 && got < gvsp.MinRecvBufSize {
s.cam.Logger().Warn("gvsp SO_RCVBUF below recommended",
"got", got, "min", gvsp.MinRecvBufSize, "want", gvsp.DefaultRecvBufSize)
}
local := s.cam.GVCP().LocalAddr()
if local == nil || local.IP == nil {
stream.Close()
s.stream = nil
return errors.New("gige: no local address for stream destination")
}
destIP := local.IP
if destIP.IsUnspecified() {
destIP = firstIPv4()
}
camIP := net.ParseIP(ip)
if camIP == nil {
camIP = net.ParseIP(s.cam.IP)
}
mtu := gvsp.PathMTU(camIP)
want := gvsp.PacketSizeForMTU(mtu)
actual, err := gvcp.StartAcquisition(s.cam.GVCP(), s.cam, destIP, stream.Port(), want)
if err != nil {
stream.Close()
s.stream = nil
return err
}
s.packetSize = actual
if actual < want {
s.cam.Logger().Warn("GevSCPSPacketSize negotiated lower than path MTU",
"want", want, "actual", actual, "path_mtu", mtu)
}
s.cam.Logger().Info("gvsp stream setup",
"mtu", mtu, "scps", s.packetSize, "rcvbuf", stream.RecvBuffer())
s.startHeartbeatLocked()
s.opened.Store(true)
return nil
}
func firstIPv4() net.IP {
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, _ := iface.Addrs()
for _, a := range addrs {
var ip net.IP
switch v := a.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip4 := ip.To4(); ip4 != nil {
return ip4
}
}
}
return net.IPv4(127, 0, 0, 1)
}
// Close stops acquisition and releases stream resources.
// The Camera is closed only when the Session owns it (not when Device owns it).
func (s *Session) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.opened.Store(false)
s.stopHeartbeatLocked()
if s.cam != nil {
_ = gvcp.StopAcquisition(s.cam)
}
if s.stream != nil {
_ = s.stream.Close()
s.stream = nil
}
if s.ownCam && s.cam != nil {
s.cam.Close()
s.cam = nil
}
return nil
}
// PauseStreaming stops image transfer but keeps CCP, heartbeat, and GVSP socket.
func (s *Session) PauseStreaming() error {
s.mu.Lock()
defer s.mu.Unlock()
if !s.opened.Load() {
return nil
}
if s.cam != nil {
_ = gvcp.StopAcquisition(s.cam)
if g := s.cam.GVCP(); g != nil {
_ = g.WriteReg(gvcp.Stream0Port, 0)
}
}
return nil
}
// ResumeStreaming re-programs the stream channel and starts acquisition again.
func (s *Session) ResumeStreaming() error {
s.mu.Lock()
defer s.mu.Unlock()
if !s.opened.Load() {
return errors.New("gige: stream not open")
}
if s.cam == nil || s.stream == nil {
return errors.New("gige: stream not open")
}
local := s.cam.GVCP().LocalAddr()
if local == nil || local.IP == nil {
return errors.New("gige: no local address for stream destination")
}
destIP := local.IP
if destIP.IsUnspecified() {
destIP = firstIPv4()
}
ps := s.packetSize
if ps <= 0 {
ps = gvsp.PacketSizeForMTU(gvsp.PathMTU(net.ParseIP(s.ip)))
s.packetSize = ps
}
actual, err := gvcp.StartAcquisition(s.cam.GVCP(), s.cam, destIP, s.stream.Port(), ps)
if err != nil {
return err
}
s.packetSize = actual
return nil
}
// Pause implements Grabber.
func (s *Session) Pause(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
return s.PauseStreaming()
}
// Resume implements Grabber.
func (s *Session) Resume(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
return s.ResumeStreaming()
}
func (s *Session) startHeartbeatLocked() {
s.stopHeartbeatLocked()
if s.cam == nil || s.cam.GVCP() == nil {
return
}
s.hb = s.cam.GVCP().StartHeartbeat()
}
func (s *Session) stopHeartbeatLocked() {
if s.hb == nil {
return
}
s.hb.Stop()
s.hb = nil
}
// Opened reports whether the session is open.
func (s *Session) Opened() bool { return s.opened.Load() }
// Grab implements Grabber: receives one GVSP frame, parses BSCF, returns JPEG Sample.
func (s *Session) Grab(ctx context.Context) (Sample, error) {
sample := Sample{PackCount: -1}
data, meta, err := s.recvFrame(ctx)
if err != nil {
return sample, err
}
s.mu.Lock()
kind := s.component
s.mu.Unlock()
if kind == ComponentUnknown {
kind = ComponentColor
}
sample, err = SampleFromBSCFComponent(data, kind)
if err != nil {
if gvsp.IsBSCF(data) {
return sample, err
}
// Non-BSCF payload.
sample.RawColor = data
sample.PixelWidth = meta.width
sample.PixelHeight = meta.height
sample.PixelFormat = meta.pixelFormat
sample.Component = kind
if sample.PixelWidth == 0 || sample.PixelHeight == 0 {
return sample, fmt.Errorf("gige: grab: %w", err)
}
}
jpeg, jerr := color.EncodeJPEG(sample.RawColor, sample.PixelWidth, sample.PixelHeight, sample.PixelFormat, 60)
if jerr != nil {
return sample, jerr
}
sample.JPEG = jpeg
return sample, nil
}
// GrabAll receives one GVSP frame and returns a JPEG Sample for every BSCF component
// (color, depth, mono, …). Non-BSCF payloads yield a single sample.
func (s *Session) GrabAll(ctx context.Context) ([]Sample, error) {
data, meta, err := s.recvFrame(ctx)
if err != nil {
return nil, err
}
var samples []Sample
if gvsp.IsBSCF(data) {
samples, err = SampleAllFromBSCF(data)
if err != nil {
return nil, err
}
} else {
samples = []Sample{{
RawColor: data,
PixelWidth: meta.width,
PixelHeight: meta.height,
PixelFormat: meta.pixelFormat,
Component: ComponentUnknown,
PackCount: -1,
}}
}
out := make([]Sample, 0, len(samples))
var errs []error
for _, sample := range samples {
if sample.PixelWidth <= 0 || sample.PixelHeight <= 0 || len(sample.RawColor) == 0 {
continue
}
jpeg, jerr := color.EncodeJPEG(sample.RawColor, sample.PixelWidth, sample.PixelHeight, sample.PixelFormat, 60)
if jerr != nil {
errs = append(errs, fmt.Errorf("%s: %w", sample.Component, jerr))
continue
}
sample.JPEG = jpeg
out = append(out, sample)
}
if len(out) == 0 {
if len(errs) > 0 {
return nil, fmt.Errorf("gige: grab all: %w", errors.Join(errs...))
}
return nil, errors.New("gige: grab all: no usable components")
}
return out, nil
}
// GrabComponents receives one GVSP frame and returns its BSCF components without
// JPEG encoding (raw Data, dimensions, pixel format). Non-BSCF payloads yield a
// single Sample with ComponentUnknown and no JPEG. Useful to probe what a camera
// is actually streaming beyond the JPEG color path.
func (s *Session) GrabComponents(ctx context.Context) ([]Sample, error) {
data, meta, err := s.recvFrame(ctx)
if err != nil {
return nil, err
}
if gvsp.IsBSCF(data) {
return gvsp.SampleAllFromBSCF(data)
}
return []Sample{{
RawColor: data,
PixelWidth: meta.width,
PixelHeight: meta.height,
PixelFormat: meta.pixelFormat,
Component: ComponentUnknown,
PackCount: -1,
}}, nil
}
type frameMeta struct {
width, height int
pixelFormat uint32
}
// recvFrame takes one GVSP frame and returns an owned copy of the payload.
func (s *Session) recvFrame(ctx context.Context) ([]byte, frameMeta, error) {
var meta frameMeta
if err := ctx.Err(); err != nil {
return nil, meta, err
}
timeout := time.Second
if dl, ok := ctx.Deadline(); ok {
timeout = time.Until(dl)
if timeout <= 0 {
return nil, meta, context.DeadlineExceeded
}
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.opened.Load() || s.stream == nil {
return nil, meta, errStreamNotOpen
}
frame, err := s.stream.Recv(timeout)
if err != nil {
return nil, meta, err
}
defer frame.Release()
meta = frameMeta{
width: int(frame.Width),
height: int(frame.Height),
pixelFormat: frame.PixelFormat,
}
return append([]byte(nil), frame.Data...), meta, nil
}
// recvFramePtr returns the pooled GVSP frame directly (no copy). Caller owns it
// and must Release() it. Used by the channel-based Stream API.
func (s *Session) recvFramePtr(ctx context.Context) (*gvsp.Frame, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
timeout := time.Second
if dl, ok := ctx.Deadline(); ok {
timeout = time.Until(dl)
if timeout <= 0 {
return nil, context.DeadlineExceeded
}
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.opened.Load() || s.stream == nil {
return nil, errStreamNotOpen
}
return s.stream.Recv(timeout)
}
// Stream is a live GVSP acquisition channel (Phase 4). Create one via
// Camera.StartStream, consume pooled frames from Frames(), and Release() each
// frame back to the pre-allocated buffer pool.
type Stream struct {
s *Session
cancel context.CancelFunc
done chan struct{}
frames chan *Frame
once sync.Once
}
// StartStream opens a GVSP channel on c and begins acquisition. Frames are
// delivered over Stream.Frames() until the context is cancelled or Stop is
// called. The Camera stays open; close it separately when done.
func (c *Camera) StartStream(ctx context.Context) (*Stream, error) {
if c == nil || c.GVCP() == nil {
return nil, errStreamNotOpen
}
s := NewFromCamera(c)
if err := s.Open(c.IP); err != nil {
return nil, err
}
if ctx == nil {
ctx = context.Background()
}
child, cancel := context.WithCancel(ctx)
st := &Stream{
s: s,
cancel: cancel,
done: make(chan struct{}),
frames: make(chan *Frame, 4),
}
go st.loop(child)
return st, nil
}
// Frames returns the channel of pooled frames. The channel closes when the
// stream ends (context cancelled, Stop called, or the session goes away).
func (st *Stream) Frames() <-chan *Frame {
if st == nil {
return nil
}
return st.frames
}
// Stop ends acquisition, closes the stream socket, and stops the background
// goroutine. Safe to call more than once.
func (st *Stream) Stop() {
if st == nil {
return
}
st.once.Do(func() {
st.cancel()
<-st.done
_ = st.s.Close()
})
}
// Pause stops image transfer but keeps the control channel and socket open.
func (st *Stream) Pause() error {
if st == nil {
return nil
}
return st.s.PauseStreaming()
}
// Resume re-programs the stream channel and restarts acquisition.
func (st *Stream) Resume() error {
if st == nil {
return errStreamNotOpen
}
return st.s.ResumeStreaming()
}
func (st *Stream) loop(ctx context.Context) {
defer close(st.done)
defer close(st.frames)
for {
frame, err := st.s.recvFramePtr(ctx)
if err != nil {
if ctx.Err() != nil {
return
}
if err == errStreamNotOpen {
return
}
continue
}
select {
case st.frames <- frame:
case <-ctx.Done():
frame.Release()
return
}
}
}