File size: 11,643 Bytes
3d4392e
 
 
 
 
 
09a7c47
3d4392e
 
 
 
09a7c47
 
 
 
 
fddab62
3d4392e
 
 
 
 
 
09a7c47
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101ed0
 
 
 
 
3d4392e
 
 
 
 
 
 
 
 
 
09a7c47
 
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
3d4392e
 
09a7c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
 
 
 
 
 
3d4392e
09a7c47
 
 
 
 
 
 
 
 
 
 
fddab62
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101ed0
09a7c47
 
 
 
 
 
 
 
8101ed0
09a7c47
 
8101ed0
09a7c47
 
 
 
 
3d4392e
8101ed0
3d4392e
 
 
 
 
 
 
8101ed0
 
 
 
 
 
 
3d4392e
 
 
 
 
8101ed0
 
 
 
 
 
 
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101ed0
3d4392e
 
 
 
09a7c47
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
3d4392e
8101ed0
3d4392e
 
 
 
 
 
fddab62
8101ed0
 
3d4392e
 
 
fddab62
3d4392e
 
 
 
fddab62
 
8101ed0
 
 
 
 
 
fddab62
 
 
 
 
 
 
8101ed0
3d4392e
 
 
 
 
 
 
 
 
8101ed0
3d4392e
 
 
 
 
 
 
 
8101ed0
3d4392e
 
 
 
 
 
8101ed0
 
 
 
 
 
 
 
 
 
 
3d4392e
 
8101ed0
 
 
 
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import { create } from "zustand"

import { ClapProject } from "@/lib/clap/types"
import { newClap } from "@/lib/clap/newClap"
import { sleep } from "@/lib/utils/sleep"
// import { getSegmentationCanvas } from "@/lib/on-device-ai/getSegmentationCanvas"

import { LatentEngineStore } from "../core/types"
import { resolveSegments } from "../resolvers/resolveSegments"
import { fetchLatentClap } from "../core/fetchLatentClap"
import { dataUriToBlob } from "@/app/api/utils/dataUriToBlob"
import { parseClap } from "@/lib/clap/parseClap"
import { InteractiveSegmenterResult, MPMask } from "@mediapipe/tasks-vision"
import { segmentFrame } from "@/lib/on-device-ai/segmentFrameOnClick"
import { drawSegmentation } from "../core/drawSegmentation"
import { filterImage } from "@/lib/on-device-ai/filterImage"

export const useLatentEngine = create<LatentEngineStore>((set, get) => ({
  width: 1024,
  height: 576,

  clap: newClap(),
  debug: true,

  streamType: "static",
  isStatic: false,
  isLive: false,
  isInteractive: false,

  isLoading: false, // true when a .clap is being downloaded and/or generated
  isLoaded: false, // true if a clap is loaded
  isPlaying: false,
  isPaused: true,

  // our "this is AI.. gasp!" disclaimer
  hasDisclaimer: true,
  hasPresentedDisclaimer: false,

  simulationPromise: undefined,
  simulationPending: false,
  simulationStartedAt: performance.now(),
  simulationEndedAt: performance.now(),
  simulationDurationInMs: 0,
  simulationVideoPlaybackFPS: 0,
  simulationRenderingTimeFPS: 0,

  renderingIntervalId: undefined,
  renderingIntervalDelayInMs: 2000, // 2 sec
  
  positionInMs: 0,
  durationInMs: 0,

  videoLayerElement: undefined,
  imageElement: undefined,
  videoElement: undefined,
  segmentationElement: undefined,
  
  videoLayer: undefined,
  videoBuffer: "A",
  videoBufferA: null,
  videoBufferB: undefined,

  segmentationLayer: undefined,

  interfaceLayer: undefined,
  interfaceBuffer: "A",
  interfaceBufferA: undefined,
  interfaceBufferB: undefined,

  setContainerDimension: ({ width, height }: { width: number; height: number }) => {
    set({
      width,
      height
    })
  },

  imagine: async (prompt: string): Promise<void> => {
    set({
      isLoaded: false,
      isLoading: true, 
    })

    let clap: ClapProject | undefined = undefined

    try {
      clap = await fetchLatentClap(prompt)
    } catch (err) {
      console.error(`generateAndLoad failed (${err})`)
      set({
        isLoading: false,
      })
    }

    if (!clap) { return }

    get().open(clap)
  },


  open: async (src?: string | ClapProject | Blob) => {
    const { debug } = get()
    set({
      isLoaded: false,
      isLoading: true, 
    })

    let clap: ClapProject | undefined = undefined

    try {
      clap = await parseClap(src, debug)
    } catch (err) {
      console.error(`failed to open the Clap: ${err}`)
      set({
        isLoading: false,
      })
    }

    if (!clap) { return }

    set({
      clap,
      isLoading: false,
      isLoaded: true,
      streamType: clap.meta.streamType,
      isStatic: clap.meta.streamType !== "interactive" && clap.meta.streamType !== "live",
      isLive: clap.meta.streamType === "live",
      isInteractive: clap.meta.streamType === "interactive",
    })
  },

  setVideoLayerElement: (videoLayerElement?: HTMLDivElement) => { set({ videoLayerElement }) },
  setImageElement: (imageElement?: HTMLImageElement) => { set({ imageElement }) },
  setVideoElement: (videoElement?: HTMLVideoElement) => { set({ videoElement }) },
  setSegmentationElement: (segmentationElement?: HTMLCanvasElement) => { set({ segmentationElement }) },

  processClickOnSegment: (result: InteractiveSegmenterResult) => {
    console.log(`processClickOnSegment: user clicked on something:`, result)

    const { videoElement, imageElement, segmentationElement, debug } = get()

    if (!result?.categoryMask) {
      if (debug) {
        console.log(`processClickOnSegment: no categoryMask, so we skip the click`)
      }
      return
    }

    try {
      if (debug) {
        console.log(`processClickOnSegment: callling drawSegmentation`)
      }

      const canvasMask: HTMLCanvasElement = drawSegmentation({
        mask: result.categoryMask,
        canvas: segmentationElement,
        backgroundImage: imageElement,
        fillStyle: "rgba(255, 255, 255, 1.0)"
      })
      // TODO: read the canvas te determine on what the user clicked

      if (debug) {
        console.log(`processClickOnSegment: filtering the original image`)
      }
      // filterImage(imageElement, canvasMask)

      if (debug) {
        console.log("processClickOnSegment: TODO call data.close() to free the memory!")
      }
      result.close()
    } catch (err) {
      console.error(`processClickOnSegment: something failed ${err}`)
    }
  },
  onClickOnSegmentationLayer: (event) => {

    const { videoElement, imageElement, segmentationLayer, segmentationElement, debug } = get()
    if (debug) {
      console.log("onClickOnSegmentationLayer")
    }
    // TODO use the videoElement if this is is video!
    if (!videoElement) { return }

    const box = event.currentTarget.getBoundingClientRect()

    const px = event.clientX
    const py = event.clientY

    const x = px / box.width
    const y = py / box.height
    console.log(`onClickOnSegmentationLayer: user clicked on `, { x, y, px, py, box, videoElement })

    const fn = async () => {
      const results: InteractiveSegmenterResult = await segmentFrame(videoElement, x, y)
      get().processClickOnSegment(results)
    }
    fn()
  },
  
  togglePlayPause: (): boolean => {
    const { isLoaded, isPlaying, renderingIntervalId, videoElement } = get()
    if (!isLoaded) { return false }
    
    const newValue = !isPlaying

    clearInterval(renderingIntervalId)

    if (newValue) {
      if (videoElement) {
        try {
          videoElement.play()
        } catch (err) {
          console.error(`togglePlayPause: failed to start the video (${err})`)
        }
      }
      set({
        isPlaying: true,
        renderingIntervalId: setTimeout(() => { get().runRenderingLoop() }, 0)
      })
    } else {
      if (videoElement) {
        try {
          videoElement.pause()
        } catch (err) {
          console.error(`togglePlayPause: failed to pause the video (${err})`)
        }
      }
      set({ isPlaying: false })
    }

    return newValue
  },


  play: (): boolean => {
    const { isLoaded, isPlaying, renderingIntervalId, renderingIntervalDelayInMs } = get()

    if (!isLoaded) { return false }

    if (isPlaying) { return true }

    clearInterval(renderingIntervalId)
    set({
      isPlaying: true,
      renderingIntervalId: setTimeout(() => { get().runRenderingLoop() }, 0)
    })

    return true
  },

  pause: (): boolean => {
    const { isLoaded, renderingIntervalId } = get()
    if (!isLoaded) { return false }

    clearInterval(renderingIntervalId)

    set({ isPlaying: false })

    return false
  },

  // a slow rendering function (async - might call a third party LLM)
  runSimulationLoop: async () => {
    const {
      isLoaded,
      isPlaying,
      clap,
      segmentationLayer,
      imageElement,
      videoElement,
      height,
      width,
    } = get()

    if (!isLoaded || !isPlaying) {
        
      set({
        simulationPending: false,
      })

      return
    }

    set({
      simulationPending: true,
      simulationStartedAt: performance.now(),
    })

    try {

      /*
      // console.log("doing stuff")
      let timestamp = performance.now()

      if (imageElement) {
        // console.log("we have an image element:", imageElement)
        const segmentationLayer = await getSegmentationCanvas({
          frame: imageElement,
          timestamp,
          width,
          height,
        })
        set({ segmentationLayer })
      }
      */

      // await sleep(500)

      // note: since we are asynchronous, we need to regularly check if
      // the user asked to pause the system or no
      if (get().isPlaying) {
        // console.log(`runSimulationLoop: rendering video content layer..`)
        // we only grab the first one
    


        const videoLayer = (await resolveSegments(clap, "video", 1)).at(0)

        if (get().isPlaying) {

          set({
            videoLayer
          })

          const { videoElement, imageElement, segmentationElement } = get()

          if (videoElement) {
            // yes, it is a very a dirty trick
            // yes, it will look back
            videoElement.defaultPlaybackRate = 0.5
          }

          const canvas = drawSegmentation({
             // no mask means this will effectively clear the canvas
            canvas: segmentationElement,
            backgroundImage: imageElement,
          })
          

          // console.log(`runSimulationLoop: rendered video content layer`)
        }
      }

    } catch (err) {
      console.error(`runSimulationLoop failed to render video layer ${err}`)
    }

    try {
      if (get().isPlaying) {
        // console.log(`runSimulationLoop: rendering UI layer..`)

        // note: for now we only display one element, to avoid handing a list of html elements
        const interfaceLayer = (await resolveSegments(clap, "interface", 1)).at(0)
        if (get().isPlaying) {
          set({
            interfaceLayer
          })

          // console.log(`runSimulationLoop: rendered UI layer`)
        }
      }
    } catch (err) {
      console.error(`runSimulationLoop failed to render UI layer ${err}`)
    }

    const simulationEndedAt = performance.now()
    const simulationDurationInMs = simulationEndedAt - get().simulationStartedAt 
    const simulationDurationInSec =simulationDurationInMs / 1000

    // I've counted the frames manually, and we indeed have, in term of pure video playback,
    // 10 fps divided by 2 (the 0.5 playback factor)
    const videoFPS = 10
    const videoDurationInSec = 1
    const videoPlaybackSpeed = 0.5
    const simulationVideoPlaybackFPS = videoDurationInSec * videoFPS * videoPlaybackSpeed
    const simulationRenderingTimeFPS = (videoDurationInSec * videoFPS) / simulationDurationInSec
    set({
      simulationPending: false,
      simulationEndedAt,
      simulationDurationInMs,
      simulationVideoPlaybackFPS,
      simulationRenderingTimeFPS,
    })
  },

  // a fast sync rendering function; whose sole role is to filter the component
  // list to put into the buffer the one that should be displayed
  runRenderingLoop: () => {
    const {
      isLoaded,
      isPlaying,
      renderingIntervalId,
      renderingIntervalDelayInMs,
      simulationPromise,
      simulationPending,
      runSimulationLoop,
      imageElement,
      videoElement,
    } = get()
    if (!isLoaded) { return }
    if (!isPlaying) { return }
    try {
      // console.log(`runRenderingLoop: starting..`)
    
      // TODO: some operations with
      // console.log(`runRenderingLoop: ended`)
    } catch (err) {
      console.error(`runRenderingLoop failed ${err}`)
    }
    clearInterval(renderingIntervalId)
    set({
      isPlaying: true,
      simulationPromise: simulationPending ? simulationPromise : runSimulationLoop(),

      // TODO: use requestAnimationFrame somehow
      // https://developers.google.com/mediapipe/solutions/vision/image_segmenter/web_js
      renderingIntervalId: setTimeout(() => { get().runRenderingLoop() }, renderingIntervalDelayInMs)
    })
    
  },

  jumpTo: (positionInMs: number) => {
    set({ positionInMs })
  },
  jumpToStart: () => {
    set({ positionInMs: 0 })
  },
}))