-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.go
More file actions
214 lines (186 loc) · 6.01 KB
/
device.go
File metadata and controls
214 lines (186 loc) · 6.01 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
package camera
import (
"context"
"errors"
"fmt"
"time"
gfxCommon "github.com/AndroidGoLab/binder/android/hardware/graphics/common"
fwkDevice "github.com/AndroidGoLab/binder/android/frameworks/cameraservice/device"
fwkService "github.com/AndroidGoLab/binder/android/frameworks/cameraservice/service"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/igbp"
"github.com/AndroidGoLab/binder/gralloc"
"github.com/AndroidGoLab/binder/logger"
"github.com/AndroidGoLab/binder/servicemanager"
)
// Device represents a connected camera device with a configured capture
// stream. Use Connect to create, ConfigureStream to set up the stream,
// CaptureFrame to read frames, and Close to disconnect.
type Device struct {
sm *servicemanager.ServiceManager
transport binder.Transport
deviceUser fwkDevice.ICameraDeviceUser
callback *deviceCallback
cameraID string
// Set after ConfigureStream.
igbpStub *igbp.ProducerStub
grallocBufs [4]*gralloc.Buffer
streamID int32
metadata []byte
width int32
height int32
}
// Connect opens a connection to the camera device identified by cameraID
// (typically "0" for the back camera).
func Connect(
ctx context.Context,
sm *servicemanager.ServiceManager,
transport binder.Transport,
cameraID string,
) (_ *Device, _err error) {
svc, err := sm.GetService(ctx, "android.frameworks.cameraservice.service.ICameraService/default")
if err != nil {
return nil, fmt.Errorf("getting camera service: %w", err)
}
proxy := fwkService.NewCameraServiceProxy(svc)
cb := &deviceCallback{}
stub := fwkDevice.NewCameraDeviceCallbackStub(cb)
stubBinder := stub.AsBinder().(*binder.StubBinder)
stubBinder.RegisterWithTransport(ctx, transport)
time.Sleep(100 * time.Millisecond)
deviceUser, err := proxy.ConnectDevice(ctx, stub, cameraID)
if err != nil {
return nil, fmt.Errorf("ConnectDevice: %w", err)
}
dev := &Device{
sm: sm,
transport: transport,
deviceUser: deviceUser,
callback: cb,
cameraID: cameraID,
}
return dev, nil
}
// ConfigureStream sets up a capture stream with the given dimensions and
// pixel format. It allocates gralloc buffers, creates an IGBP surface
// stub, and configures the camera for streaming.
func (d *Device) ConfigureStream(
ctx context.Context,
width int32,
height int32,
format Format,
) error {
d.width = width
d.height = height
// Allocate gralloc buffers.
for i := range d.grallocBufs {
buf, err := gralloc.Allocate(
ctx,
d.sm,
width,
height,
format,
gfxCommon.BufferUsageCpuReadOften|gfxCommon.BufferUsageCpuWriteOften|gfxCommon.BufferUsageCameraOutput,
)
if err != nil {
return fmt.Errorf("allocating gralloc buffer %d: %w", i, err)
}
logger.Debugf(ctx, "gralloc buffer %d: fds=%v ints=%v stride=%d", i, buf.Handle.Fds, buf.Handle.Ints, buf.Stride)
if err := buf.Mmap(); err != nil {
// Goldfish gralloc buffers may fail mmap (EPERM) but the
// claimed region allows pread fallback in ReadPixels.
logger.Debugf(ctx, "mmap gralloc buffer %d: %v (will use pread fallback if goldfish)", i, err)
}
d.grallocBufs[i] = buf
}
// Begin configuration.
if err := d.deviceUser.BeginConfigure(ctx); err != nil {
return fmt.Errorf("BeginConfigure: %w", err)
}
// Get default request metadata.
metadata, err := CreateDefaultRequest(ctx, d.deviceUser, fwkDevice.TemplateIdPREVIEW)
if err != nil {
return fmt.Errorf("CreateDefaultRequest: %w", err)
}
d.metadata = metadata
// Create IGBP stub and stream.
d.igbpStub = igbp.NewProducerStub(uint32(width), uint32(height), d.grallocBufs)
igbpStubBinder := binder.NewStubBinder(d.igbpStub)
igbpStubBinder.RegisterWithTransport(ctx, d.transport)
streamID, err := CreateStreamWithSurface(ctx, d.deviceUser, d.transport, igbpStubBinder, width, height)
if err != nil {
return fmt.Errorf("CreateStream: %w", err)
}
d.streamID = streamID
// End configuration.
if err := d.deviceUser.EndConfigure(
ctx,
fwkDevice.StreamConfigurationModeNormalMode,
fwkDevice.CameraMetadata{Metadata: []byte{}},
0,
); err != nil {
return fmt.Errorf("EndConfigure: %w", err)
}
return nil
}
// CaptureFrame captures a single frame and returns the raw pixel data.
// The caller should have called ConfigureStream first. This method
// submits a repeating capture request on the first call, then reads
// from the IGBP queue channel on subsequent calls.
func (d *Device) CaptureFrame(
ctx context.Context,
) ([]byte, error) {
if d.igbpStub == nil {
return nil, fmt.Errorf("stream not configured; call ConfigureStream first")
}
// Submit a repeating capture request (only needs to happen once,
// but submitting again is harmless and simplifies the API).
captureReq := fwkDevice.CaptureRequest{
PhysicalCameraSettings: []fwkDevice.PhysicalCameraSettings{
{
Id: d.cameraID,
Settings: fwkDevice.CaptureMetadataInfo{
Tag: fwkDevice.CaptureMetadataInfoTagMetadata,
Metadata: fwkDevice.CameraMetadata{Metadata: d.metadata},
},
},
},
StreamAndWindowIds: []fwkDevice.StreamAndWindowId{
{StreamId: d.streamID, WindowId: 0},
},
}
_, err := SubmitRequest(ctx, d.deviceUser, captureReq, true)
if err != nil {
// Fallback to single shot.
_, err = SubmitRequest(ctx, d.deviceUser, captureReq, false)
if err != nil {
return nil, fmt.Errorf("SubmitRequestList: %w", err)
}
}
// Wait for a frame to be queued.
select {
case <-ctx.Done():
return nil, ctx.Err()
case slot := <-d.igbpStub.QueuedFrames():
buf := d.igbpStub.SlotBuffer(slot)
if buf == nil {
return nil, fmt.Errorf("slot %d: buffer not assigned (dequeue may not have been called for this slot)", slot)
}
return buf.ReadPixels(ctx)
}
}
// Close disconnects from the camera device and releases gralloc buffers.
func (d *Device) Close(ctx context.Context) error {
var errs []error
if d.deviceUser != nil {
if err := d.deviceUser.Disconnect(ctx); err != nil {
errs = append(errs, fmt.Errorf("disconnect: %w", err))
}
}
for _, buf := range d.grallocBufs {
if buf != nil {
buf.Munmap()
}
}
return errors.Join(errs...)
}