-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms.txt
More file actions
1278 lines (991 loc) · 37.8 KB
/
llms.txt
File metadata and controls
1278 lines (991 loc) · 37.8 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Android Go NDK
> Idiomatic Go bindings for the Android NDK, auto-generated from C headers. Covers 34 modules: camera, audio, sensors, EGL, OpenGL ES, Vulkan, media codecs, input, looper, window, assets, thermal, permissions, and more. All types have nil-safe Close() methods, error types wrap NDK status codes, and builder types support method chaining. No runtime.SetFinalizer — all resource cleanup is explicit via Close() and defer.
## Idiomatic vs capi Packages
Always import the idiomatic top-level packages (`github.com/AndroidGoLab/ndk/{module}`) — not the `capi/` packages. The `capi/` layer is a raw CGo binding with C-style names and unsafe types; it is intended only for power users who need NDK functions not yet wrapped by the idiomatic layer. All commonly used functions — including `hwbuf.Allocate`, `buf.Lock`, `codec.DequeueInputBuffer`, `codec.DequeueOutputBuffer`, and `hwbuf.RecvHandleFromUnixSocket` — are available in the idiomatic layer.
## Resource Lifecycle and Memory Management
Native NDK resources (camera devices, audio streams, media codecs, etc.) are wrapped in Go structs that hold a C pointer. The project does NOT use `runtime.SetFinalizer` — all cleanup is explicit:
### Close Pattern
Every closeable type follows this pattern:
```go
func (h *Device) Close() error {
if h.ptr == nil {
return nil // nil-safe, idempotent
}
err := result(capi.ACameraDevice_close(h.ptr))
h.ptr = nil // prevent double-free
return err
}
```
Key properties:
- **Nil-safe**: Calling Close() on a nil receiver or already-closed handle is a no-op.
- **Idempotent**: Multiple Close() calls are safe.
- **Sets pointer to nil**: Prevents use-after-free and double-free.
### Defer-Based Cleanup
Always use `defer` to ensure cleanup in reverse creation order:
```go
mgr := camera.NewManager()
defer func() {
if err := mgr.Close(); err != nil {
log.Printf("manager close: %v", err)
}
}()
dev, err := mgr.OpenCamera(camID, callbacks)
if err != nil {
log.Fatal(err)
}
defer dev.Close()
req, err := dev.CreateCaptureRequest(camera.Preview)
if err != nil {
log.Fatal(err)
}
defer req.Close()
// Cleanup order: req -> dev -> mgr (reverse creation order)
```
### Framework-Owned vs Application-Owned Resources
Some resources are singletons owned by the Android framework and must NOT be closed:
- `sensor.GetInstance()` — returns the singleton ASensorManager. No Close().
- `activity.AssetManager` — the AAssetManager from ANativeActivity. No Close().
Application-created resources MUST be closed:
- `camera.NewManager()` → `mgr.Close()`
- `audio.NewStreamBuilder()` → `builder.Close()`
- `media.NewDecoder(mime)` → `codec.Close()`
- All `New*()` constructors return resources that need Close().
### Preventing Memory Leaks
Since there is no GC integration for native resources:
1. **Always defer Close()** immediately after creation.
2. **Check errors from Close()** — some resources (camera devices) may return errors on close.
3. **Clean up in reverse order** — defers naturally handle this.
4. **Reference counting for windows**: Call `window.Acquire()` when sharing an ANativeWindow across goroutines, and `window.Close()` (which calls ANativeWindow_release) from each user.
5. **Looper reference counting**: Call `looper.Acquire()` before sharing across goroutines, each user calls Close().
### CGo Pointer Pinning
When passing Go-allocated pointers to C functions, use `runtime.Pinner`:
```go
src := glStr(shaderSource) // Go-allocated string
var pinner runtime.Pinner
pinner.Pin(src)
defer pinner.Unpin()
gles2.ShaderSource(shader, 1, &src, &length)
```
For `**T` parameters, pin BOTH the outer and inner pointers. For structs with Go pointer fields, pin the struct before passing to C.
## Error Handling
NDK functions return negative int32 status codes on failure. Each module defines typed error constants:
```go
// camera/errors.go
type Error int32
const (
ErrUnknown Error = -10000
ErrInvalidParameter Error = -10001
ErrCameraDisconnected Error = -10002
ErrNotEnoughMemory Error = -10003
ErrCameraInUse Error = -10010
ErrPermissionDenied Error = -10013
// ... more error codes
)
func (e Error) Error() string {
return fmt.Sprintf("camera: error %d", int(e))
}
```
Usage with errors.Is:
```go
dev, err := mgr.OpenCamera(camID, callbacks)
if errors.Is(err, camera.ErrPermissionDenied) {
log.Fatal("CAMERA permission not granted")
}
if err != nil {
log.Fatal(err)
}
```
## Thread Safety
Some Android NDK APIs are thread-local and require `runtime.LockOSThread()`:
### Thread-Local APIs
- **ALooper**: Thread-local event loop. Must call `looper.Prepare()` and `looper.PollOnce()` on the same OS thread.
- **EGL context**: EGL contexts are bound to a thread via `egl.MakeCurrent()`. All GL calls must happen on that thread.
- **AInputQueue**: Input event polling must happen on the thread that attached the queue.
Pattern:
```go
func renderLoop(display egl.EGLDisplay, surface egl.EGLSurface, context egl.EGLContext) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
egl.MakeCurrent(display, surface, surface, context)
defer egl.MakeCurrent(display, egl.NoSurface, egl.NoSurface, egl.NoContext)
for {
// All OpenGL ES calls must happen on this thread
gles2.Clear(gles2.ColorBufferBit)
egl.SwapBuffers(display, surface)
}
}
```
### Thread-Safe APIs
- Camera callbacks (OnDisconnected, OnError, OnReady) are called from NDK threads — use `sync.Mutex` or channels for synchronization.
- `audio.Stream.Write()` and `audio.Stream.Read()` are thread-safe.
- `looper.Wake()` is safe to call from any goroutine (after Acquire).
### Cross-Goroutine Coordination
```go
var wg sync.WaitGroup
wg.Add(1)
var readyOnce sync.Once
session, err := dev.CreateCaptureSession(container,
camera.SessionStateCallbacks{
OnReady: func() {
readyOnce.Do(wg.Done)
},
},
)
wg.Wait() // Block until session is ready
session.SetRepeatingRequest(req)
```
## Handle Interoperability
All handle types implement the `handle.NativeHandle` interface for interop with golang.org/x/mobile, gioui.org, and gomobile bind:
```go
// handle/handle.go
type NativeHandle interface {
Pointer() unsafe.Pointer
UintPtr() uintptr
}
```
Every handle provides:
```go
mgr := camera.NewManager()
ptr := mgr.UintPtr() // Get as uintptr
mgr2 := camera.NewManagerFromUintPtr(ptr) // Reconstruct
mgr3 := camera.NewManagerFromPointer(rawPtr) // From unsafe.Pointer
```
For gomobile bind (which doesn't support uintptr), transport as int64:
```go
// Go side (exported to Java via gomobile bind)
func NewBridge(handle int64) *Bridge {
mgr := sensor.NewManagerFromUintPtr(uintptr(handle))
return &Bridge{mgr: mgr}
}
func (b *Bridge) Handle() int64 {
return int64(b.mgr.UintPtr())
}
```
```java
// Java side
long ptr = nativeGetSensorManager();
Bridge bridge = Mypackage.newBridge(ptr);
```
## Audio (AAudio)
### Playback
```go
import (
"time"
"unsafe"
"github.com/AndroidGoLab/ndk/audio"
)
builder, err := audio.NewStreamBuilder()
if err != nil {
log.Fatal(err)
}
defer builder.Close()
builder.
SetDirection(audio.Output).
SetSampleRate(44100).
SetChannelCount(2).
SetFormat(audio.PcmFloat).
SetPerformanceMode(audio.LowLatency).
SetSharingMode(audio.Shared)
stream, err := builder.Open()
if err != nil {
log.Fatal(err)
}
defer stream.Close()
stream.Start()
framesPerBurst := stream.FramesPerBurst()
buf := make([]float32, int(framesPerBurst)*2)
bufBytes := unsafe.Slice((*byte)(unsafe.Pointer(&buf[0])), len(buf)*int(unsafe.Sizeof(buf[0])))
totalFrames := int32(44100 * 2) // 2 seconds
written := int32(0)
for written < totalFrames {
framesToWrite := framesPerBurst
if remaining := totalFrames - written; remaining < framesToWrite {
framesToWrite = remaining
}
n, err := stream.Write(bufBytes, framesToWrite, time.Second)
if err != nil {
log.Fatal(err)
}
written += n
}
stream.Stop()
```
### Recording
```go
builder.
SetDirection(audio.Input).
SetSampleRate(48000).
SetChannelCount(1).
SetFormat(audio.PcmI16).
SetPerformanceMode(audio.LowLatency).
SetSharingMode(audio.Shared)
stream, _ := builder.Open()
defer stream.Close()
stream.Start()
buf := make([]int16, 1024)
bufBytes := unsafe.Slice((*byte)(unsafe.Pointer(&buf[0])), len(buf)*int(unsafe.Sizeof(buf[0])))
totalFrames := stream.SampleRate() // 1 second
var captured []int16
for int32(len(captured)) < totalFrames {
framesToRead := int32(len(buf))
if remaining := totalFrames - int32(len(captured)); remaining < framesToRead {
framesToRead = remaining
}
n, err := stream.Read(bufBytes, framesToRead, time.Second)
if err != nil {
log.Fatal(err)
}
captured = append(captured, buf[:n]...)
}
stream.Stop()
```
### Stream Properties
```go
stream.SampleRate() // int32
stream.ChannelCount() // int32
stream.FramesPerBurst() // int32
stream.State() // StreamState
stream.XRunCount() // int32 (underrun count)
stream.GetFramesRead() // int64
stream.GetFramesWritten() // int64
```
## Camera (Camera2 NDK)
### Complete Capture Pipeline
```go
import "github.com/AndroidGoLab/ndk/camera"
// 1. Create manager
mgr := camera.NewManager()
defer mgr.Close()
// 2. Discover cameras
ids, err := mgr.CameraIDList()
if err != nil {
log.Fatal(err)
}
// 3. Read characteristics
chars, err := mgr.GetCameraCharacteristics(ids[0])
if err != nil {
log.Fatal(err)
}
defer chars.Close()
// Query sensor orientation
if chars.I32Count(uint32(camera.SensorOrientation)) > 0 {
orient := chars.I32At(uint32(camera.SensorOrientation), 0)
log.Printf("orientation: %d degrees", orient)
}
// Query stream configurations (format, width, height, isInput tuples)
scTag := uint32(camera.ScalerAvailableStreamConfigurations)
count := chars.I32Count(scTag)
for i := int32(0); i+3 < count; i += 4 {
format := chars.I32At(scTag, i)
w := chars.I32At(scTag, i+1)
h := chars.I32At(scTag, i+2)
isInput := chars.I32At(scTag, i+3)
if isInput == 0 {
log.Printf("output: format=%d %dx%d", format, w, h)
}
}
// 4. Open camera with state callbacks
dev, err := mgr.OpenCamera(ids[0], camera.DeviceStateCallbacks{
OnDisconnected: func() { log.Println("disconnected") },
OnError: func(code int) { log.Printf("error %d", code) },
})
if err != nil {
log.Fatal(err)
}
defer dev.Close()
// 5. Create capture request
req, err := dev.CreateCaptureRequest(camera.Preview)
if err != nil {
log.Fatal(err)
}
defer req.Close()
// 6. Create output target from ANativeWindow (from Surface/SurfaceTexture)
outTarget, err := camera.NewOutputTarget(nativeWindow)
if err != nil {
log.Fatal(err)
}
defer outTarget.Close()
req.AddTarget(outTarget)
// 7. Create session output container
sessOut, err := camera.NewSessionOutput(nativeWindow)
if err != nil {
log.Fatal(err)
}
defer sessOut.Close()
container, err := camera.NewSessionOutputContainer()
if err != nil {
log.Fatal(err)
}
defer container.Close()
container.Add(sessOut)
// 8. Create capture session with readiness gate
var wg sync.WaitGroup
wg.Add(1)
var readyOnce sync.Once
session, err := dev.CreateCaptureSession(container,
camera.SessionStateCallbacks{
OnReady: func() { readyOnce.Do(wg.Done) },
OnActive: func() { log.Println("session active") },
OnClosed: func() { log.Println("session closed") },
},
)
if err != nil {
log.Fatal(err)
}
defer session.Close()
wg.Wait()
// 9. Start repeating capture
session.SetRepeatingRequest(req)
// ... render frames ...
session.StopRepeating()
// Cleanup order (via defers): session -> container -> sessOut -> outTarget -> req -> dev -> mgr
```
### Template Types
Available capture request templates: `camera.Preview`, `camera.StillCapture`, `camera.Record`, `camera.VideoSnapshot`, `camera.ZeroShutterLag`, `camera.Manual`.
## Sensor
### Sensor Discovery
```go
import "github.com/AndroidGoLab/ndk/sensor"
mgr := sensor.GetInstance() // Singleton, no Close() needed
accel := mgr.DefaultSensor(sensor.Accelerometer)
fmt.Println(accel.Name()) // e.g. "LSM6DSO Accelerometer"
fmt.Println(accel.Vendor()) // e.g. "STMicroelectronics"
fmt.Println(accel.Resolution()) // float32
fmt.Println(accel.MinDelay()) // microseconds between events
```
### Sensor Types
Available sensor types: `sensor.Accelerometer`, `sensor.MagneticField`, `sensor.Gyroscope`, `sensor.Light`, `sensor.Pressure`, `sensor.Proximity`, `sensor.Gravity`, `sensor.LinearAcceleration`, `sensor.RotationVector`, `sensor.RelativeHumidity`, `sensor.AmbientTemperature`, `sensor.GameRotationVector`, `sensor.StepDetector`, `sensor.StepCounter`, `sensor.GeomagneticRotationVector`, `sensor.HeartRate`, `sensor.HingeAngle`, `sensor.HeadTracker`, `sensor.Heading`.
### Checking Sensor Availability
DefaultSensor always returns a non-nil wrapper. If the sensor is absent, the C pointer is NULL and Name() will panic:
```go
func probeSensor(mgr *sensor.Manager, t sensor.Type) (name string, ok bool) {
defer func() {
if r := recover(); r != nil {
ok = false
}
}()
s := mgr.DefaultSensor(t)
name = s.Name()
return name, name != ""
}
```
### Sensor Event Loop (ALooper-Based)
Reading continuous sensor data requires an ALooper-based event queue:
```go
import (
"runtime"
"github.com/AndroidGoLab/ndk/sensor"
"github.com/AndroidGoLab/ndk/looper"
)
// Step 1: Lock goroutine to OS thread (ALooper is thread-local)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Step 2: Get sensor manager and accelerometer
mgr := sensor.GetInstance()
accel := mgr.DefaultSensor(sensor.Accelerometer)
// Step 3: Prepare a looper for the current thread
lp := looper.Prepare(int32(looper.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS))
defer lp.Close()
// Step 4: Create an event queue bound to the looper
const sensorIdent = 1
queue := mgr.CreateEventQueue(lp.Pointer(), sensorIdent, nil, nil)
defer mgr.DestroyEventQueue(queue)
// Step 5: Enable sensor and set sampling rate
queue.EnableSensor(accel)
queue.SetEventRate(accel, 100000) // 100ms between events
defer queue.DisableSensor(accel)
// Step 6: Poll loop — read sensor events
for {
ident := looper.PollOnce(-1, nil, nil, nil) // -1 = block forever
if ident == sensorIdent {
for queue.HasEvents() > 0 {
// Read ASensorEvent from queue.
// Each event has: type, timestamp, and data union.
// For accelerometer:
// data[0] = X acceleration (m/s^2)
// data[1] = Y acceleration (m/s^2)
// data[2] = Z acceleration (m/s^2)
}
}
}
```
## Media Codecs (AMediaCodec)
### Codec State Machine
```
Created -> Configured -> Started -> (buffer processing) -> Flushed -> Started -> Stopped -> Released
```
Wraps the NDK `AMediaCodec` API. Key C functions: `AMediaCodec_createDecoderByType`, `AMediaCodec_createEncoderByType`, `AMediaCodec_configure`, `AMediaCodec_start`, `AMediaCodec_stop`, `AMediaCodec_flush`, `AMediaCodec_delete`.
### Decoder Setup
```go
import "github.com/AndroidGoLab/ndk/media"
// Create H.264 decoder (wraps AMediaCodec_createDecoderByType)
codec := media.NewDecoder("video/avc")
if codec == nil {
log.Fatal("H.264 decoder not available")
}
defer codec.Close()
// Configure format (wraps AMediaFormat)
format := media.NewFormat()
defer format.Close()
format.
SetString("mime", "video/avc").
SetInt32("width", 1920).
SetInt32("height", 1080)
// Verify properties
var width int32
format.GetInt32("width", &width) // returns bool
// Configure as decoder: flags=0 (requires Activity context)
codec.Configure(format, nil, nil, 0)
codec.Start()
```
### H.264 Encoder Setup
```go
import "github.com/AndroidGoLab/ndk/media"
// Create H.264 encoder (wraps AMediaCodec_createEncoderByType)
codec := media.NewEncoder("video/avc")
if codec == nil {
log.Fatal("H.264 encoder not available")
}
defer codec.Close()
// Configure encoder format with required parameters.
// Format keys are plain strings matching the NDK AMEDIAFORMAT_KEY_* constants.
format := media.NewFormat()
defer format.Close()
format.
SetString("mime", "video/avc"). // AMEDIAFORMAT_KEY_MIME
SetInt32("width", 1920). // AMEDIAFORMAT_KEY_WIDTH
SetInt32("height", 1080). // AMEDIAFORMAT_KEY_HEIGHT
SetInt32("bitrate", 4_000_000). // AMEDIAFORMAT_KEY_BIT_RATE (bits/sec)
SetInt32("frame-rate", 30). // AMEDIAFORMAT_KEY_FRAME_RATE
SetInt32("i-frame-interval", 1). // AMEDIAFORMAT_KEY_I_FRAME_INTERVAL (seconds)
SetInt32("color-format", 21) // COLOR_FormatYUV420SemiPlanar (0x15)
// Optional: set bitrate mode (CBR for streaming, VBR for quality)
// media.ABITRATE_MODE_CBR = 2, media.ABITRATE_MODE_VBR = 1
format.SetInt32("bitrate-mode", int32(media.ABITRATE_MODE_CBR))
// Optional: set H.264 profile and level
format.SetInt32("profile", 8) // AVCProfileHigh
format.SetInt32("level", 512) // AVCLevel31
// Configure as encoder: flags=1 (AMEDIACODEC_CONFIGURE_FLAG_ENCODE)
// surface=nil for buffer-mode input, crypto=nil for no DRM
const configureFlagEncode uint32 = 1 // media.AMEDIACODEC_CONFIGURE_FLAG_ENCODE
codec.Configure(format, nil, nil, configureFlagEncode)
codec.Start()
```
Common MIME types: `"video/avc"` (H.264), `"video/hevc"` (H.265), `"video/x-vnd.on2.vp8"` (VP8), `"video/x-vnd.on2.vp9"` (VP9), `"video/av01"` (AV1), `"audio/mp4a-latm"` (AAC), `"audio/opus"` (Opus).
### Common AMediaFormat Keys
Format keys are passed as strings to `SetInt32`/`SetString`/`SetFloat`/`SetInt64`:
| Key string | NDK constant | Type | Description |
|---|---|---|---|
| `"mime"` | AMEDIAFORMAT_KEY_MIME | string | MIME type |
| `"width"` | AMEDIAFORMAT_KEY_WIDTH | int32 | Frame width in pixels |
| `"height"` | AMEDIAFORMAT_KEY_HEIGHT | int32 | Frame height in pixels |
| `"bitrate"` | AMEDIAFORMAT_KEY_BIT_RATE | int32 | Target bitrate (bits/sec) |
| `"frame-rate"` | AMEDIAFORMAT_KEY_FRAME_RATE | int32 | Frame rate (fps) |
| `"i-frame-interval"` | AMEDIAFORMAT_KEY_I_FRAME_INTERVAL | int32 | I-frame interval (seconds) |
| `"color-format"` | AMEDIAFORMAT_KEY_COLOR_FORMAT | int32 | Color format enum |
| `"bitrate-mode"` | AMEDIAFORMAT_KEY_BITRATE_MODE | int32 | BitrateMode (0=CQ, 1=VBR, 2=CBR) |
| `"profile"` | AMEDIAFORMAT_KEY_PROFILE | int32 | Codec profile |
| `"level"` | AMEDIAFORMAT_KEY_LEVEL | int32 | Codec level |
| `"channel-count"` | AMEDIAFORMAT_KEY_CHANNEL_COUNT | int32 | Audio channel count |
| `"sample-rate"` | AMEDIAFORMAT_KEY_SAMPLE_RATE | int32 | Audio sample rate (Hz) |
### Buffer Processing Loop
The idiomatic `media` package provides all buffer processing functions: `DequeueInputBuffer`, `DequeueOutputBuffer`, `GetInputBuffer`, `QueueInputBuffer`, `GetOutputBuffer`, `ReleaseOutputBuffer`, and all constants (`media.AMEDIACODEC_INFO_*`, `media.AMEDIACODEC_BUFFER_FLAG_*`). The `media.BufferInfo` value struct is used with `DequeueOutputBuffer`.
```go
import (
"unsafe"
"github.com/AndroidGoLab/ndk/media"
)
for {
// 1. Dequeue input buffer
idx := codec.DequeueInputBuffer(timeoutUs)
if idx < 0 { continue } // no buffer available yet
// 2. Fill with data (NAL units for video, PCM for audio)
var bufSize uint64
buf := codec.GetInputBuffer(uint64(idx), &bufSize)
data := unsafe.Slice(buf, bufSize)
n := copy(data, inputFrame)
// 3. Queue for processing
codec.QueueInputBuffer(uint64(idx), 0, uint64(n), presentationTimeUs, 0)
// End of stream: pass uint32(media.AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM)
// 4. Dequeue output buffer with BufferInfo
var info media.BufferInfo
outIdx := codec.DequeueOutputBuffer(&info, timeoutUs)
if outIdx == int64(media.AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
continue // output format changed, query new format
}
if outIdx < 0 { continue }
// 5. Consume output — info.Offset, info.Size, info.PresentationTimeUs, info.Flags
var outSize uint64
outBuf := codec.GetOutputBuffer(uint64(outIdx), &outSize)
outData := unsafe.Slice(outBuf, outSize)
processOutput(outData)
// 6. Release back to codec (render=true to send to surface)
codec.ReleaseOutputBuffer(uint64(outIdx), false)
}
```
### Buffer Flags
Available in the idiomatic `media` package (type `media.MEDIACODEC_BUFFER_FLAG`):
- `media.AMEDIACODEC_BUFFER_FLAG_KEY_FRAME` (1) — output buffer contains a key frame
- `media.AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG` (2) — buffer contains codec config data (SPS/PPS)
- `media.AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM` (4) — signals end of stream
- `media.AMEDIACODEC_BUFFER_FLAG_PARTIAL_FRAME` (8) — buffer contains partial frame data
### Lifecycle Operations
```go
codec.Flush() // Discard pending buffers, stay in Started state
codec.Stop() // Started -> Stopped
codec.Close() // Release all resources (wraps AMediaCodec_delete)
```
### Error Handling
Media functions return errors wrapping `media_status_t` codes. Check with `errors.Is`:
```go
if err := codec.Configure(format, nil, nil, flags); err != nil {
log.Fatalf("configure failed: %v", err)
// Common causes: unsupported format, missing codec, wrong flags
}
if err := codec.Start(); err != nil {
log.Fatalf("start failed: %v", err)
}
```
### Bitrate Modes
```go
media.ABITRATE_MODE_CQ // 0 — Constant Quality
media.ABITRATE_MODE_VBR // 1 — Variable Bitrate
media.ABITRATE_MODE_CBR // 2 — Constant Bitrate
media.ABITRATE_MODE_CBR_FD // 3 — Constant Bitrate with Frame Drop
```
## Assets
### Obtaining the Asset Manager
The AAssetManager comes from the ANativeActivity struct. It is framework-owned — do not Close() it:
```go
import "github.com/AndroidGoLab/ndk/asset"
// In a NativeActivity app:
mgr := activity.AssetManager // from ANativeActivity, no Close()
```
### Reading an Asset File
```go
a := mgr.Open("data/config.json", asset.Streaming)
defer a.Close()
totalLen := a.Length64()
buf := make([]byte, totalLen)
err := a.Read(unsafe.Pointer(&buf[0]), uint64(totalLen))
```
### Asset Open Modes
- `asset.Unknown` — NDK chooses defaults
- `asset.Random` — random access via Seek; NDK may memory-map
- `asset.Streaming` — sequential forward reads; smaller buffer
- `asset.Buffer` — entire asset loaded into memory; `Buffer()` returns direct pointer
### Direct Buffer Access
```go
a := mgr.Open("data/config.json", asset.Buffer)
defer a.Close()
ptr := a.Buffer() // unsafe.Pointer to raw data
data := unsafe.Slice((*byte)(ptr), a.Length64())
```
### Seeking
```go
newPos := a.Seek(0, int32(io.SeekStart)) // SEEK_SET
remaining := a.RemainingLength64()
```
### Directory Iteration
```go
dir := mgr.OpenDir("") // empty string = assets root
defer dir.Close()
for {
name := dir.NextFileName()
if name == "" {
break
}
fmt.Println(name)
}
dir.Rewind() // reset iterator
```
## Looper (ALooper)
### Basic Event Loop
```go
import (
"runtime"
"github.com/AndroidGoLab/ndk/looper"
)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
lp := looper.Prepare(int32(looper.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS))
defer lp.Close()
// Cross-goroutine wake
lp.Acquire() // extra reference for other goroutine
go func() {
time.Sleep(100 * time.Millisecond)
lp.Wake() // safe after Acquire
}()
// Poll
result := looper.PollOnce(-1, nil, nil, nil)
switch {
case result == int32(looper.ALOOPER_POLL_WAKE):
log.Println("woken up")
case result == int32(looper.ALOOPER_POLL_TIMEOUT):
log.Println("timed out")
case result >= 0:
log.Printf("event from ident %d", result)
}
```
## EGL and OpenGL ES
### EGL Context Setup
```go
import (
"runtime"
"github.com/AndroidGoLab/ndk/egl"
"github.com/AndroidGoLab/ndk/gles2"
)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
display := egl.GetDisplay(egl.DefaultDisplay)
egl.Initialize(display, nil, nil)
config := egl.ChooseConfig(display, attribs)
surface := egl.CreateWindowSurface(display, config, nativeWindow, nil)
context := egl.CreateContext(display, config, egl.NoContext, contextAttribs)
egl.MakeCurrent(display, surface, surface, context)
defer egl.MakeCurrent(display, egl.NoSurface, egl.NoSurface, egl.NoContext)
defer egl.DestroyContext(display, context)
defer egl.DestroySurface(display, surface)
defer egl.Terminate(display)
// Now use OpenGL ES on this thread
gles2.ClearColor(0.2, 0.3, 0.3, 1.0)
gles2.Clear(gles2.ColorBufferBit)
egl.SwapBuffers(display, surface)
```
### Shader Compilation
```go
shader := gles2.CreateShader(gles2.VertexShader)
src := gles2.Str(vertexShaderSource)
var pinner runtime.Pinner
pinner.Pin(src)
defer pinner.Unpin()
length := gles2.GLint(len(vertexShaderSource))
gles2.ShaderSource(shader, 1, &src, &length)
gles2.CompileShader(shader)
defer gles2.DeleteShader(shader)
```
## Thermal Monitoring
```go
import "github.com/AndroidGoLab/ndk/thermal"
mgr := thermal.NewManager()
defer mgr.Close()
status := mgr.CurrentThermalStatus()
switch status {
case thermal.StatusNone:
log.Println("cool")
case thermal.StatusLight, thermal.StatusModerate:
log.Println("warm — consider reducing workload")
case thermal.StatusSevere, thermal.StatusCritical:
log.Println("hot — reduce workload immediately")
case thermal.StatusEmergency, thermal.StatusShutdown:
log.Println("critical — shutting down")
}
```
## Window (ANativeWindow)
```go
import "github.com/AndroidGoLab/ndk/window"
win := window.NewWindowFromPointer(rawPtr)
// Reference counting
win.Acquire() // increment ref count
defer win.Close() // decrement ref count (calls ANativeWindow_release)
w := win.Width()
h := win.Height()
fmt.Printf("%dx%d\n", w, h)
win.SetBuffersGeometry(1920, 1080, window.Rgba8888)
win.SetFrameRate(60.0, 0)
```
## Input Events
```go
import (
"runtime"
"github.com/AndroidGoLab/ndk/input"
)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
queue := input.NewQueueFromPointer(rawQueuePtr)
for queue.HasEvents() == nil {
event := queue.GetEvent()
if queue.PreDispatchEvent(event) {
continue
}
switch event.Type() {
case input.EventTypeMotion:
action := event.MotionAction()
x := event.X(0)
y := event.Y(0)
pressure := event.Pressure(0)
log.Printf("touch action=%d at (%.1f, %.1f) pressure=%.2f", action, x, y, pressure)
case input.EventTypeKey:
keyCode := event.KeyCode()
log.Printf("key code=%d action=%d", keyCode, event.KeyAction())
}
queue.FinishEvent(event, 1) // 1 = handled
}
```
## Image Decoding
```go
import "github.com/AndroidGoLab/ndk/image"
decoder := image.NewDecoderFromFd(fd)
defer decoder.Close()
info := decoder.HeaderInfo()
w := info.Width()
h := info.Height()
stride := decoder.MinimumStride()
pixels := make([]byte, int(stride)*int(h))
decoder.Decode(unsafe.Pointer(&pixels[0]), int(stride)*int(h), int(stride))
```
## SurfaceTexture
```go
import "github.com/AndroidGoLab/ndk/surfacetexture"
st := surfacetexture.NewSurfaceTextureFromPointer(ptr)
defer st.Close()
win := st.AcquireWindow() // Get ANativeWindow for camera/video output
defer win.Close()
st.AttachToGLContext(textureID)
defer st.DetachFromGLContext()
st.UpdateTexImage() // Pull latest frame to GL texture
ts := st.Timestamp() // Frame timestamp in nanoseconds
var mat [16]float32
st.TransformMatrix(&mat) // Get texture coordinate transform
```
## Trace (Performance)
```go
import "github.com/AndroidGoLab/ndk/trace"
if trace.IsEnabled() {
trace.BeginSection("myOperation")
defer trace.EndSection()
// ... measured code ...
}
```
## Log
```go
import ndklog "github.com/AndroidGoLab/ndk/log"
// Priority levels: ndklog.Verbose, ndklog.Debug, ndklog.Info, ndklog.Warn, ndklog.Error, ndklog.Fatal
ndklog.Write(int32(ndklog.Info), "MyApp", "Hello from NDK")
ndklog.Write(int32(ndklog.Error), "MyApp", "Something went wrong")
```
## Choreographer (VSync)
The choreographer is a per-thread singleton tied to the calling thread's Looper. It does not require Close().
```go
import "github.com/AndroidGoLab/ndk/choreographer"
// Obtain the per-thread singleton (requires an active Looper on the thread)
ch := choreographer.GetInstance()
if ch == nil {
log.Fatal("no choreographer — is a Looper prepared on this thread?")
}
// Frame callbacks are registered via the NDK's AChoreographer_postFrameCallback.