File size: 10,601 Bytes
52ae39e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const FPS = 30;
let frame = 0;
var chunks = [];
var stream;
var rec;
var track;

function timeout(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function initRecorder() {
  stream = document.getElementById('canvasrecord').captureStream(0);
  track = stream.getVideoTracks()[0];

  if (!track.requestFrame) {
    track.requestFrame = () => stream.requestFrame();
  }

  rec = new MediaRecorder(stream, {
    bitsPerSecond: 3200000,
  });

  rec.ondataavailable = function (evt) {
    console.log('chunky');
    chunks.push(evt.data);
  };

  rec.start();

  console.log('Recorder has been started');

  rec.onstart = function () {
    rec.pause();
    console.log('start!');
  };
}

async function recordFrame() {
  console.log(frame);

  waitForEvent(rec, 'pause');

  //rec.onpause = async function(e) {

  // wake up the recorder
  rec.resume();
  recordAnimate(false, (frame / FPS) * 1000);
  //animate(false, (frame/FPS)*1000)
  // force write the frame
  track.requestFrame();

  // wait until our frame-time elapsed
  await timeout(1000 / FPS);

  // sleep recorder
  rec.pause();
  //}
}

async function exportRecording() {
  rec.stop();
  stream.getTracks().forEach((track) => track.stop());
  await waitForEvent(rec, 'stop');
  return new Blob(chunks);
}

// Record canvas
async function record() {
  updateRecordCanvas();
  if ($('input[name=radio]:checked').val() == 'image') {
    recording = true;
    paused = true;
    animate(false, currenttime);
    const dataURL = canvasrecord.toDataURL({
      format: 'png',
    });
    const link = document.createElement('a');
    link.download = 'image.png';
    link.href = dataURL;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    recording = false;
  } else {
    if (!recording) {
      recording = true;
      paused = true;
      recordAnimate(false, (frame / FPS) * 1000);
      recording = true;
      $('#download-real').html('Rendering...');
      $('#download-real').addClass('downloading');
      var fps = 60;
      var aCtx = new AudioContext();
      function audioTimerLoop(callback, frequency) {
        var freq = frequency / 1000;
        var silence = aCtx.createGain();
        silence.gain.value = 0;
        silence.connect(aCtx.destination);
        onOSCend();
        var stopped = false;
        function onOSCend() {
          osc = aCtx.createOscillator();
          osc.onended = onOSCend;
          osc.connect(silence);
          osc.start(0);
          osc.stop(aCtx.currentTime + freq);
          callback(aCtx.currentTime);
          if (stopped) {
            osc.onended = function () {
              return;
            };
          }
        }
        return function () {
          stopped = true;
        };
      }
      var stopAnim = audioTimerLoop(renderAnim, 1000 / fps);
      var stream = document
        .getElementById('canvasrecord')
        .captureStream(fps);
      objects.forEach(function (object) {
        if (
          canvasrecord.getItemById(object.id).get('assetType') &&
          canvasrecord.getItemById(object.id).get('assetType') ==
            'video'
        ) {
          var audio = $(
            canvasrecord.getItemById(object.id).getElement()
          )[0];
          var audioContext = new AudioContext();
          var audioSource =
            audioContext.createMediaElementSource(audio);
          var audioDestination =
            audioContext.createMediaStreamDestination();
          audioSource.connect(audioDestination);
          stream.addTrack(
            audioDestination.stream.getAudioTracks()[0]
          );
        }
      });
      if (background_audio != false) {
        var audioContext = new AudioContext();
        var audioSource =
          audioContext.createMediaElementSource(background_audio);
        var audioDestination =
          audioContext.createMediaStreamDestination();
        audioSource.connect(audioDestination);
        stream.addTrack(audioDestination.stream.getAudioTracks()[0]);
        background_audio.currentTime = 0;
        background_audio.play();
      }
      let chunks = [];
      var recorder = new MediaRecorder(stream, {
        bitsPerSecond: 3200000,
      });
      recorder.ondataavailable = (e) => chunks.push(e.data);
      recorder.onstop = (e) => {
        stopAnim();
        downloadRecording(chunks);
        animate(false, 0);
        $('#seekbar').offset({
          left:
            offset_left +
            $('#inner-timeline').offset().left +
            currenttime / timelinetime,
        });
        canvas.renderAll();
        console.log('Finished rendering');
      };
      recorder.start();

      setTimeout(function () {
        recorder.stop();
      }, duration);

      async function renderAnim(time) {
        await recordAnimate(time * 1000);
      }
    }
  }
}

/*

			initRecorder();

			//await timeout(2000)
		
			// draw one frame at a time
			while (frame++ < FPS * (duration/1000)) {
				await longDraw(); // do the long drawing
				await recordFrame(); // record at constant FPS 
			}
			// now all the frames have been drawn
			const recorded = await exportRecording(); // we can get our final video file
			const a = document.createElement('a');
			a.style.display = 'none';
			a.href =  URL.createObjectURL(recorded);
			a.download = "test.webm";
			document.body.appendChild(a);
			a.click();
			recording = false;
			currenttime = 0;
			animate(false, 0);
			$("#seekbar").offset({left:offset_left+$("#inner-timeline").offset().left+(currenttime/timelinetime)});
			canvas.renderAll();
				resizeCanvas();
				if (background_audio != false) {
						background_audio.pause();
						background_audio = new Audio(background_audio.src)
				}
			$("#download-real").html("Download");
			$("#download-real").removeClass("downloading");
			updateRecordCanvas();
		
			// Fake long drawing operations that make real-time recording impossible
			function longDraw() {
				recordAnimate((frame/FPS)*1000)
				return wait(Math.random() * 300)
					.then(recordAnimate((frame/FPS)*1000));
			}*/

/*
paused = true;
			recording = true;
			$("#download-real").html("Rendering...");
			$("#download-real").addClass("downloading");
			var fps = 60;
			var aCtx = new AudioContext();
			function audioTimerLoop(callback, frequency) {
					var freq = frequency / 1000;
					var silence = aCtx.createGain();
					silence.gain.value = 0;
					silence.connect(aCtx.destination);
					onOSCend();
					var stopped = false;
					function onOSCend() {
							osc = aCtx.createOscillator();
							osc.onended = onOSCend;
							osc.connect(silence);
							osc.start(0);
							osc.stop(aCtx.currentTime + freq);
							callback(aCtx.currentTime);
							if (stopped) {
									osc.onended = function() {
											return;
									};
							}
					};
					return function() {
					stopped = true;
					};
			}
			var stopAnim = audioTimerLoop(renderAnim, 1000/(fps));
			var stream = document.getElementById("canvasrecord").captureStream(fps);
			objects.forEach(function(object){
					if (canvasrecord.getItemById(object.id).get("assetType") && canvasrecord.getItemById(object.id).get("assetType") == "video") {
							var audio = $(canvasrecord.getItemById(object.id).getElement())[0];
							var audioContext = new AudioContext();
							var audioSource = audioContext.createMediaElementSource(audio);
							var audioDestination = audioContext.createMediaStreamDestination();
							audioSource.connect(audioDestination);
							stream.addTrack(audioDestination.stream.getAudioTracks()[0]);
					}
			})
			if (background_audio != false) {
					var audioContext = new AudioContext();
					var audioSource = audioContext.createMediaElementSource(background_audio);
					var audioDestination = audioContext.createMediaStreamDestination();
					audioSource.connect(audioDestination);
					stream.addTrack(audioDestination.stream.getAudioTracks()[0]);
					background_audio.currentTime = 0;
					background_audio.play();
			}
			let chunks = [];
			var recorder = new MediaRecorder(stream, {
				bitsPerSecond : 3200000,
			});
			recorder.ondataavailable = e => chunks.push(e.data);
			recorder.onstop = e => {
					stopAnim();
					downloadRecording(chunks);
					animate(false, 0);
					$("#seekbar").offset({left:offset_left+$("#inner-timeline").offset().left+(currenttime/timelinetime)});
					canvas.renderAll();
					console.log("Finished rendering")
			}
			recorder.start();

			setTimeout(function() {
					recorder.stop();
			}, duration)

			async function renderAnim(time) {
					await animate(false, time*1000);
			} 

*/

/*
$("#download-real").html("Rendering...");
			$("#download-real").addClass("downloading");
		
			// browser check
			if (typeof MediaStreamTrackGenerator === undefined || typeof MediaStream === undefined || typeof VideoFrame === undefined) {
				console.log('Your browser does not support the web APIs used in this demo');
				return;
			}
		
			// recording setup
			const fps = 60;
			const generator = new MediaStreamTrackGenerator({ kind: "video" });
			const writer = generator.writable.getWriter();
			const stream = new MediaStream();
			stream.addTrack(generator);
			const recorder = new MediaRecorder(stream, { mimeType: "video/webm" });
			recorder.start();

			function timeout(ms) {
				return new Promise(resolve => setTimeout(resolve, ms));
		}
		
			// animate stuff
			console.log('rendering...')
			console.log(duration);
			for (let i = 0; i < (duration/1000)*fps; i++) {
				animate(false, (i/fps)*1000);
				const frame = new VideoFrame(document.getElementById("canvasrecord"), { 
					timestamp: (i / fps)*1000
				});
				await writer.write(frame);
				await timeout(100)
				console.log("frame "+(i/fps)*1000);
			}
			console.log('rendering done');
		
			// stop recording and 
			recorder.addEventListener("dataavailable", (evt) => {
				const a = document.createElement('a');
				a.style.display = 'none';
				a.href =  URL.createObjectURL(evt.data);
				a.download = "test.webm";
				document.body.appendChild(a);
				a.click();
				recording = false;
				currenttime = 0;
				animate(false, 0);
				$("#seekbar").offset({left:offset_left+$("#inner-timeline").offset().left+(currenttime/timelinetime)});
				canvas.renderAll();
					resizeCanvas();
					if (background_audio != false) {
							background_audio.pause();
							background_audio = new Audio(background_audio.src)
					}
				$("#download-real").html("Download");
				$("#download-real").removeClass("downloading");
				updateRecordCanvas();
			});
			recorder.stop();
			*/