-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_stmap.go
More file actions
387 lines (340 loc) · 11.1 KB
/
api_stmap.go
File metadata and controls
387 lines (340 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
package control
import (
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strings"
"github.com/zsiec/switchframe/server/control/httperr"
"github.com/zsiec/switchframe/server/stmap"
)
// generateRequest is the JSON body for the ST map generate endpoint.
type generateRequest struct {
Type string `json:"type"`
Params map[string]float64 `json:"params"`
Name string `json:"name"`
Width int `json:"width"`
Height int `json:"height"`
AssignSource string `json:"assign_source"`
AssignProgram bool `json:"assign_program"`
FrameCount int `json:"frame_count"`
}
// stmapAssignRequest is the JSON body for source/program map assignment.
type stmapAssignRequest struct {
Map string `json:"map"`
}
// registerSTMapRoutes registers ST map API routes on the given mux.
func (a *API) registerSTMapRoutes(mux *http.ServeMux) {
if a.stmapRegistry == nil {
return
}
mux.HandleFunc("GET /api/stmap", a.handleSTMapList)
mux.HandleFunc("GET /api/stmap/state", a.handleSTMapState)
mux.HandleFunc("GET /api/stmap/generators", a.handleSTMapGenerators)
mux.HandleFunc("POST /api/stmap/generate", a.handleSTMapGenerate)
mux.HandleFunc("POST /api/stmap/upload/{name}", a.handleSTMapUpload)
mux.HandleFunc("GET /api/stmap/{name}", a.handleSTMapGet)
mux.HandleFunc("DELETE /api/stmap/{name}", a.handleSTMapDelete)
mux.HandleFunc("GET /api/stmap/{name}/download", a.handleSTMapDownload)
mux.HandleFunc("PUT /api/stmap/source/{sourceKey}", a.handleSTMapAssignSource)
mux.HandleFunc("DELETE /api/stmap/source/{sourceKey}", a.handleSTMapRemoveSource)
mux.HandleFunc("PUT /api/stmap/program", a.handleSTMapAssignProgram)
mux.HandleFunc("DELETE /api/stmap/program", a.handleSTMapRemoveProgram)
}
// handleSTMapList returns all stored map names.
func (a *API) handleSTMapList(w http.ResponseWriter, r *http.Request) {
names := a.stmapRegistry.List()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"maps": names})
}
// handleSTMapState returns the current ST map assignments.
func (a *API) handleSTMapState(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(a.stmapRegistry.State())
}
// handleSTMapGenerators returns all available generators with parameter schemas.
func (a *API) handleSTMapGenerators(w http.ResponseWriter, r *http.Request) {
infos := stmap.GeneratorInfoList()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"generators": infos})
}
// handleSTMapGenerate generates a new ST map and stores it.
func (a *API) handleSTMapGenerate(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
var req generateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httperr.Write(w, http.StatusBadRequest, "invalid json")
return
}
if req.Type == "" {
httperr.Write(w, http.StatusBadRequest, "type is required")
return
}
if req.Name == "" {
httperr.Write(w, http.StatusBadRequest, "name is required")
return
}
// Default dimensions from pipeline format.
if req.Width == 0 || req.Height == 0 {
pf := a.switcher.PipelineFormat()
req.Width = pf.Width
req.Height = pf.Height
}
// Try static generator first, then animated.
staticGens := stmap.ListGenerators()
isStatic := false
for _, name := range staticGens {
if name == req.Type {
isStatic = true
break
}
}
var respMap map[string]interface{}
if isStatic {
m, err := stmap.Generate(req.Type, req.Params, req.Width, req.Height)
if err != nil {
httperr.Write(w, http.StatusBadRequest, err.Error())
return
}
m.Name = req.Name
if err := a.stmapRegistry.Store(m); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
// Persist to disk.
if a.stmapStore != nil {
_ = a.stmapStore.SaveStatic(m)
}
respMap = map[string]interface{}{
"name": m.Name,
"width": m.Width,
"height": m.Height,
"type": "static",
}
} else {
// Try animated
frameCount := req.FrameCount
if frameCount <= 0 {
frameCount = 90
}
if frameCount > 300 {
httperr.Write(w, http.StatusBadRequest, "frame_count must be <= 300")
return
}
am, err := stmap.GenerateAnimated(req.Type, req.Params, req.Width, req.Height, frameCount)
if err != nil {
httperr.Write(w, http.StatusBadRequest, err.Error())
return
}
am.Name = req.Name
// Pre-build all per-frame processors now (in the HTTP handler goroutine)
// rather than lazily on the pipeline goroutine, which would freeze video
// processing for several seconds.
if a.stmapCacheDir != "" {
cacheDir := filepath.Join(a.stmapCacheDir,
req.Type+"_"+stmap.CacheKey(req.Type, req.Params, req.Width, req.Height, frameCount))
am.BuildProcessorsCached(cacheDir)
} else {
am.BuildProcessors()
}
if err := a.stmapRegistry.StoreAnimated(am); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
// Persist animated metadata for regeneration on restart.
if a.stmapStore != nil {
_ = a.stmapStore.SaveAnimatedMeta(am, req.Type, req.Params)
}
respMap = map[string]interface{}{
"name": am.Name,
"width": req.Width,
"height": req.Height,
"type": "animated",
"frame_count": len(am.Frames),
}
}
// Optional assignment.
if req.AssignSource != "" {
if err := a.stmapRegistry.AssignSource(req.AssignSource, req.Name); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
}
if req.AssignProgram {
if err := a.stmapRegistry.AssignProgram(req.Name); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(respMap)
}
// handleSTMapUpload accepts an uploaded ST map file (PNG, EXR, or raw binary).
func (a *API) handleSTMapUpload(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
name := r.PathValue("name")
if err := stmap.ValidateName(name); err != nil {
httperr.Write(w, http.StatusBadRequest, err.Error())
return
}
// Detect format from Content-Type or extension.
ct := r.Header.Get("Content-Type")
ext := strings.ToLower(filepath.Ext(name))
r.Body = http.MaxBytesReader(w, r.Body, 64<<20) // 64MB limit
data, err := io.ReadAll(r.Body)
if err != nil {
httperr.Write(w, http.StatusRequestEntityTooLarge, "upload too large (max 64MB)")
return
}
var m *stmap.STMap
switch {
case ct == "image/x-exr" || ext == ".exr":
m, err = stmap.ReadEXR(data, name)
case ct == "image/png" || ext == ".png":
m, err = stmap.ReadPNG(data, name)
case ext == ".stmap":
m, err = stmap.ReadRaw(data, name)
default:
// Auto-detect by magic bytes, then try PNG, then raw.
if stmap.IsEXR(data) {
m, err = stmap.ReadEXR(data, name)
} else {
m, err = stmap.ReadPNG(data, name)
if err != nil {
m, err = stmap.ReadRaw(data, name)
}
}
}
if err != nil {
httperr.Write(w, http.StatusBadRequest, fmt.Sprintf("failed to parse upload: %v", err))
return
}
if err := a.stmapRegistry.Store(m); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
// Persist uploaded map to disk.
if a.stmapStore != nil {
_ = a.stmapStore.SaveStatic(m)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"name": m.Name,
"width": m.Width,
"height": m.Height,
"type": "static",
})
}
// handleSTMapGet returns metadata about a stored map.
func (a *API) handleSTMapGet(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
if m, ok := a.stmapRegistry.Get(name); ok {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"name": m.Name,
"width": m.Width,
"height": m.Height,
"type": "static",
})
return
}
if am, ok := a.stmapRegistry.GetAnimated(name); ok {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"name": am.Name,
"width": am.Frames[0].Width,
"height": am.Frames[0].Height,
"type": "animated",
"frame_count": len(am.Frames),
})
return
}
httperr.WriteErr(w, http.StatusNotFound, stmap.ErrNotFound)
}
// handleSTMapDelete removes a stored map.
func (a *API) handleSTMapDelete(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
name := r.PathValue("name")
if err := a.stmapRegistry.Delete(name); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
// Remove from disk.
if a.stmapStore != nil {
_ = a.stmapStore.Delete(name)
}
w.WriteHeader(http.StatusNoContent)
}
// handleSTMapDownload returns a map as raw binary.
func (a *API) handleSTMapDownload(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
m, ok := a.stmapRegistry.Get(name)
if !ok {
httperr.WriteErr(w, http.StatusNotFound, stmap.ErrNotFound)
return
}
data, err := stmap.WriteRaw(m)
if err != nil {
httperr.WriteErr(w, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name + ".stmap"}))
_, _ = w.Write(data)
}
// handleSTMapAssignSource assigns a map to a source.
func (a *API) handleSTMapAssignSource(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
sourceKey := r.PathValue("sourceKey")
var req stmapAssignRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httperr.Write(w, http.StatusBadRequest, "invalid json")
return
}
if req.Map == "" {
httperr.Write(w, http.StatusBadRequest, "map name is required")
return
}
if err := a.stmapRegistry.AssignSource(sourceKey, req.Map); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(a.stmapRegistry.State())
}
// handleSTMapRemoveSource removes a map assignment from a source.
func (a *API) handleSTMapRemoveSource(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
sourceKey := r.PathValue("sourceKey")
a.stmapRegistry.RemoveSource(sourceKey)
w.WriteHeader(http.StatusNoContent)
}
// handleSTMapAssignProgram assigns a map to the program output.
func (a *API) handleSTMapAssignProgram(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
var req stmapAssignRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httperr.Write(w, http.StatusBadRequest, "invalid json")
return
}
if req.Map == "" {
httperr.Write(w, http.StatusBadRequest, "map name is required")
return
}
if err := a.stmapRegistry.AssignProgram(req.Map); err != nil {
httperr.WriteErr(w, errorStatus(err), err)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(a.stmapRegistry.State())
}
// handleSTMapRemoveProgram removes the program map assignment.
func (a *API) handleSTMapRemoveProgram(w http.ResponseWriter, r *http.Request) {
a.setLastOperator(r)
a.stmapRegistry.RemoveProgram()
w.WriteHeader(http.StatusNoContent)
}