-
Notifications
You must be signed in to change notification settings - Fork 701
/
Copy pathindex.ts
1477 lines (1307 loc) · 43.3 KB
/
index.ts
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
import { mutation, Inject, InitAfter, Service, PersistentStatefulService } from 'services/core';
import path from 'path';
import Vue from 'vue';
import fs from 'fs-extra';
import * as remote from '@electron/remote';
import { EStreamingState, StreamingService } from 'services/streaming';
import { getPlatformService } from 'services/platforms';
import { UserService } from 'services/user';
import {
IYoutubeVideoUploadOptions,
IYoutubeUploadResponse,
} from 'services/platforms/youtube/uploader';
import { YoutubeService } from 'services/platforms/youtube';
import os from 'os';
import { SCRUB_SPRITE_DIRECTORY, SUPPORTED_FILE_TYPES } from './constants';
import { pmap } from 'util/pmap';
import { RenderingClip } from './rendering/rendering-clip';
import { throttle } from 'lodash-decorators';
import * as Sentry from '@sentry/browser';
import { TAnalyticsEvent, UsageStatisticsService } from 'services/usage-statistics';
import { $t } from 'services/i18n';
import { DismissablesService, EDismissable } from 'services/dismissables';
import { ENotificationType, NotificationsService } from 'services/notifications';
import { JsonrpcService } from 'services/api/jsonrpc';
import { NavigationService } from 'services/navigation';
import { SharedStorageService } from 'services/integrations/shared-storage';
import moment from 'moment';
import uuid from 'uuid';
import { EMenuItemKey } from 'services/side-nav';
import { AiHighlighterUpdater } from './ai-highlighter-updater';
import { IDownloadProgress } from 'util/requests';
import { IncrementalRolloutService } from 'app-services';
import { EAvailableFeatures } from 'services/incremental-rollout';
import {
IAiClip,
IHighlightedStream,
IHighlighterState,
INewClipData,
isAiClip,
IStreamInfoForAiHighlighter,
IStreamMilestones,
IUploadInfo,
TClip,
TStreamInfo,
} from './models/highlighter.models';
import {
EExportStep,
IAudioInfo,
IExportInfo,
IExportOptions,
ITransitionInfo,
IVideoInfo,
TFPS,
TPreset,
TResolution,
} from './models/rendering.models';
import { ProgressTracker, getHighlightClips } from './ai-highlighter-utils';
import {
EAiDetectionState,
TOrientation,
ICoordinates,
IHighlight,
IHighlighterMilestone,
IInput,
} from './models/ai-highlighter.models';
import { HighlighterViews } from './highlighter-views';
import { startRendering } from './rendering/start-rendering';
import { cutHighlightClips } from './cut-highlight-clips';
import { reduce } from 'lodash';
import { extractDateTimeFromPath, fileExists } from './file-utils';
import { addVerticalFilterToExportOptions } from './vertical-export';
@InitAfter('StreamingService')
export class HighlighterService extends PersistentStatefulService<IHighlighterState> {
@Inject() streamingService: StreamingService;
@Inject() userService: UserService;
@Inject() usageStatisticsService: UsageStatisticsService;
@Inject() dismissablesService: DismissablesService;
@Inject() notificationsService: NotificationsService;
@Inject() jsonrpcService: JsonrpcService;
@Inject() navigationService: NavigationService;
@Inject() sharedStorageService: SharedStorageService;
@Inject() incrementalRolloutService: IncrementalRolloutService;
static defaultState: IHighlighterState = {
clips: {},
transition: {
type: 'fade',
duration: 1,
},
video: {
intro: { path: '', duration: null },
outro: { path: '', duration: null },
},
audio: {
musicEnabled: false,
musicPath: '',
musicVolume: 50,
},
export: {
exporting: false,
currentFrame: 0,
totalFrames: 0,
step: EExportStep.AudioMix,
cancelRequested: false,
file: '',
previewFile: path.join(os.tmpdir(), 'highlighter-preview.mp4'),
exported: false,
error: null,
fps: 30,
resolution: 720,
preset: 'ultrafast',
},
upload: {
uploading: false,
uploadedBytes: 0,
totalBytes: 0,
cancelRequested: false,
videoId: null,
error: false,
},
dismissedTutorial: false,
error: '',
useAiHighlighter: false,
highlightedStreams: [],
updaterProgress: 0,
isUpdaterRunning: false,
highlighterVersion: '',
};
aiHighlighterUpdater: AiHighlighterUpdater;
aiHighlighterFeatureEnabled = false;
streamMilestones: IStreamMilestones | null = null;
static filter(state: IHighlighterState) {
return {
...this.defaultState,
clips: state.clips,
highlightedStreams: state.highlightedStreams,
video: state.video,
audio: state.audio,
transition: state.transition,
useAiHighlighter: state.useAiHighlighter,
highlighterVersion: state.highlighterVersion,
};
}
/**
* A dictionary of actual clip classes.
* These are not serializable so kept out of state.
*/
renderingClips: Dictionary<RenderingClip> = {};
directoryCleared = false;
@mutation()
ADD_CLIP(clip: TClip) {
Vue.set(this.state.clips, clip.path, clip);
this.state.export.exported = false;
}
@mutation()
UPDATE_CLIP(clip: Partial<TClip> & { path: string }) {
Vue.set(this.state.clips, clip.path, {
...this.state.clips[clip.path],
...clip,
});
this.state.export.exported = false;
}
@mutation()
REMOVE_CLIP(clipPath: string) {
Vue.delete(this.state.clips, clipPath);
this.state.export.exported = false;
}
@mutation()
SET_EXPORT_INFO(exportInfo: Partial<IExportInfo>) {
this.state.export = {
...this.state.export,
exported: false,
...exportInfo,
};
}
@mutation()
SET_UPLOAD_INFO(uploadInfo: Partial<IUploadInfo>) {
this.state.upload = {
...this.state.upload,
...uploadInfo,
};
}
@mutation()
CLEAR_UPLOAD() {
this.state.upload = {
uploading: false,
uploadedBytes: 0,
totalBytes: 0,
cancelRequested: false,
videoId: null,
error: false,
};
}
@mutation()
SET_TRANSITION_INFO(transitionInfo: Partial<ITransitionInfo>) {
this.state.transition = {
...this.state.transition,
...transitionInfo,
};
this.state.export.exported = false;
}
@mutation()
SET_AUDIO_INFO(audioInfo: Partial<IAudioInfo>) {
this.state.audio = {
...this.state.audio,
...audioInfo,
};
this.state.export.exported = false;
}
@mutation()
SET_VIDEO_INFO(videoInfo: Partial<IVideoInfo>) {
this.state.video = {
...this.state.video,
...videoInfo,
};
this.state.export.exported = false;
}
@mutation()
DISMISS_TUTORIAL() {
this.state.dismissedTutorial = true;
}
@mutation()
SET_ERROR(error: string) {
this.state.error = error;
}
@mutation()
SET_USE_AI_HIGHLIGHTER(useAiHighlighter: boolean) {
Vue.set(this.state, 'useAiHighlighter', useAiHighlighter);
this.state.useAiHighlighter = useAiHighlighter;
}
@mutation()
ADD_HIGHLIGHTED_STREAM(streamInfo: IHighlightedStream) {
// Vue.set(this.state, 'highlightedStreams', streamInfo);
this.state.highlightedStreams.push(streamInfo);
}
@mutation()
UPDATE_HIGHLIGHTED_STREAM(updatedStreamInfo: IHighlightedStream) {
const keepAsIs = this.state.highlightedStreams.filter(
stream => stream.id !== updatedStreamInfo.id,
);
this.state.highlightedStreams = [...keepAsIs, updatedStreamInfo];
}
@mutation()
REMOVE_HIGHLIGHTED_STREAM(id: string) {
this.state.highlightedStreams = this.state.highlightedStreams.filter(
stream => stream.id !== id,
);
}
@mutation()
SET_UPDATER_PROGRESS(progress: number) {
this.state.updaterProgress = progress;
}
@mutation()
SET_UPDATER_STATE(isRunning: boolean) {
this.state.isUpdaterRunning = isRunning;
}
@mutation()
SET_HIGHLIGHTER_VERSION(version: string) {
this.state.highlighterVersion = version;
}
get views() {
return new HighlighterViews(this.state);
}
async init() {
super.init();
this.incrementalRolloutService.featuresReady.then(async () => {
this.aiHighlighterFeatureEnabled = this.incrementalRolloutService.views.featureIsEnabled(
EAvailableFeatures.aiHighlighter,
);
if (this.aiHighlighterFeatureEnabled && !this.aiHighlighterUpdater) {
this.aiHighlighterUpdater = new AiHighlighterUpdater();
}
});
//
this.views.clips.forEach(clip => {
if (isAiClip(clip) && (clip.aiInfo as any).moments) {
clip.aiInfo.inputs = (clip.aiInfo as any).moments;
delete (clip.aiInfo as any).moments;
}
});
//Check if files are existent, if not, delete
this.views.clips.forEach(c => {
if (!fileExists(c.path)) {
this.removeClip(c.path, undefined);
}
});
if (this.views.exportInfo.exporting) {
this.SET_EXPORT_INFO({
exporting: false,
error: null,
cancelRequested: false,
});
}
//Check if aiDetections were still running when the user closed desktop
this.views.highlightedStreams
.filter(stream => stream.state.type === 'detection-in-progress')
.forEach(stream => {
this.UPDATE_HIGHLIGHTED_STREAM({
...stream,
state: { type: EAiDetectionState.CANCELED_BY_USER, progress: 0 },
});
});
this.views.clips.forEach(c => {
this.UPDATE_CLIP({
path: c.path,
loaded: false,
});
});
try {
// On some very very small number of systems, we won't be able to fetch
// the videos path from the system.
// TODO: Add a fallback directory?
this.SET_EXPORT_INFO({
file: path.join(remote.app.getPath('videos'), 'Output.mp4'),
});
} catch (e: unknown) {
console.error('Got error fetching videos directory', e);
}
this.handleStreamingChanges();
}
private handleStreamingChanges() {
let aiRecordingStartTime = moment();
let streamInfo: IStreamInfoForAiHighlighter;
let streamStarted = false;
let aiRecordingInProgress = false;
this.streamingService.replayBufferFileWrite.subscribe(async clipPath => {
const streamId = streamInfo?.id || undefined;
let endTime: number | undefined;
if (streamId) {
endTime = moment().diff(aiRecordingStartTime, 'seconds');
} else {
endTime = undefined;
}
const REPLAY_BUFFER_DURATION = 20; // TODO M: Replace with settingsservice
const startTime = Math.max(0, endTime ? endTime - REPLAY_BUFFER_DURATION : 0);
this.addClips([{ path: clipPath, startTime, endTime }], streamId, 'ReplayBuffer');
});
this.streamingService.streamingStatusChange.subscribe(async status => {
if (status === EStreamingState.Live) {
streamStarted = true; // console.log('live', this.streamingService.views.settings.platforms.twitch.title);
if (!this.aiHighlighterFeatureEnabled) {
return;
}
if (this.views.useAiHighlighter === false) {
console.log('HighlighterService: Game:', this.streamingService.views.game);
// console.log('Highlighter not enabled or not Fortnite');
return;
}
// console.log('recording Alreadyt running?:', this.streamingService.views.isRecording);
this.usageStatisticsService.recordAnalyticsEvent('AIHighlighter', {
type: 'AiRecordingStarted',
});
if (this.streamingService.views.isRecording) {
// console.log('Recording is already running');
} else {
this.streamingService.actions.toggleRecording();
}
streamInfo = {
id: 'fromStreamRecording' + uuid(),
title: this.streamingService.views.settings.platforms.twitch?.title,
game: this.streamingService.views.game,
};
aiRecordingInProgress = true;
aiRecordingStartTime = moment();
}
if (status === EStreamingState.Offline) {
if (
streamStarted &&
this.views.clips.length > 0 &&
this.dismissablesService.views.shouldShow(EDismissable.HighlighterNotification)
) {
this.notificationsService.push({
type: ENotificationType.SUCCESS,
lifeTime: -1,
message: $t(
'Edit your replays with Highlighter, a free editor built in to Streamlabs.',
),
action: this.jsonrpcService.createRequest(
Service.getResourceId(this),
'notificationAction',
),
});
this.usageStatisticsService.recordAnalyticsEvent(
this.views.useAiHighlighter ? 'AIHighlighter' : 'Highlighter',
{
type: 'NotificationShow',
},
);
}
streamStarted = false;
}
if (status === EStreamingState.Ending) {
if (!aiRecordingInProgress) {
return;
}
this.streamingService.actions.toggleRecording();
// Load potential replaybuffer clips
await this.loadClips(streamInfo.id);
}
});
this.streamingService.latestRecordingPath.subscribe(path => {
if (!aiRecordingInProgress) {
return;
}
aiRecordingInProgress = false;
this.detectAndClipAiHighlights(path, streamInfo);
this.navigationService.actions.navigate(
'Highlighter',
{ view: 'stream' },
EMenuItemKey.Highlighter,
);
});
}
notificationAction() {
this.navigationService.navigate('Highlighter');
this.dismissablesService.dismiss(EDismissable.HighlighterNotification);
this.usageStatisticsService.recordAnalyticsEvent(
this.views.useAiHighlighter ? 'AIHighlighter' : 'Highlighter',
{
type: 'NotificationClick',
},
);
}
setTransition(transition: Partial<ITransitionInfo>) {
this.SET_TRANSITION_INFO(transition);
}
setAudio(audio: Partial<IAudioInfo>) {
this.SET_AUDIO_INFO(audio);
}
setVideo(video: Partial<IVideoInfo>) {
this.SET_VIDEO_INFO(video);
}
resetExportedState() {
this.SET_EXPORT_INFO({ exported: false });
}
setExportFile(file: string) {
this.SET_EXPORT_INFO({ file });
}
setFps(fps: TFPS) {
this.SET_EXPORT_INFO({ fps });
}
setResolution(resolution: TResolution) {
this.SET_EXPORT_INFO({ resolution });
}
setPreset(preset: TPreset) {
this.SET_EXPORT_INFO({ preset });
}
dismissError() {
if (this.state.export.error) this.SET_EXPORT_INFO({ error: null });
if (this.state.upload.error) this.SET_UPLOAD_INFO({ error: false });
if (this.state.error) this.SET_ERROR('');
}
dismissTutorial() {
this.DISMISS_TUTORIAL();
}
// =================================================================================================
// CLIPS logic
// =================================================================================================
addClips(
newClips: { path: string; startTime?: number; endTime?: number }[],
streamId: string | undefined,
source: 'Manual' | 'ReplayBuffer',
) {
newClips.forEach((clipData, index) => {
const currentClips = this.getClips(this.views.clips, streamId);
const allClips = this.getClips(this.views.clips, undefined);
const getHighestGlobalOrderPosition = allClips.length;
let newStreamInfo: { [key: string]: TStreamInfo } = {};
if (source === 'Manual') {
if (streamId) {
currentClips.forEach(clip => {
if (clip?.streamInfo?.[streamId] === undefined) {
return;
}
const updatedStreamInfo = {
...clip.streamInfo,
[streamId]: {
...clip.streamInfo[streamId],
orderPosition: clip.streamInfo[streamId]!.orderPosition + 1,
},
};
// update streaminfo position
this.UPDATE_CLIP({
path: clip.path,
streamInfo: updatedStreamInfo,
});
});
// Update globalOrderPosition of all other items as well
allClips.forEach(clip => {
this.UPDATE_CLIP({
path: clip.path,
globalOrderPosition: clip.globalOrderPosition + 1,
});
});
newStreamInfo = {
[streamId]: {
orderPosition: 0 + index,
},
};
} else {
// If no streamId currentCLips = allClips
currentClips.forEach(clip => {
this.UPDATE_CLIP({
path: clip.path,
globalOrderPosition: clip.globalOrderPosition + 1,
});
});
}
} else {
if (streamId) {
newStreamInfo = {
[streamId]: {
orderPosition: index + currentClips.length + 1,
initialStartTime: clipData.startTime,
initialEndTime: clipData.endTime,
},
};
}
}
if (this.state.clips[clipData.path]) {
//Add new newStreamInfo, wont be added if no streamId is available
const updatedStreamInfo = {
...this.state.clips[clipData.path].streamInfo,
...newStreamInfo,
};
this.UPDATE_CLIP({
path: clipData.path,
streamInfo: updatedStreamInfo,
});
return;
} else {
this.ADD_CLIP({
path: clipData.path,
loaded: false,
enabled: true,
startTrim: 0,
endTrim: 0,
deleted: false,
source,
// Manual clips always get prepended to be visible after adding them
// ReplayBuffers will appended to have them in the correct order.
globalOrderPosition:
source === 'Manual' ? 0 + index : index + getHighestGlobalOrderPosition + 1,
streamInfo: streamId !== undefined ? newStreamInfo : undefined,
});
}
});
return;
}
async addAiClips(newClips: INewClipData[], newStreamInfo: IStreamInfoForAiHighlighter) {
const currentHighestOrderPosition = this.getClips(this.views.clips, newStreamInfo.id).length;
const getHighestGlobalOrderPosition = this.getClips(this.views.clips, undefined).length;
newClips.forEach((clip, index) => {
// Don't allow adding the same clip twice for ai clips
if (this.state.clips[clip.path]) return;
const streamInfo: { [key: string]: TStreamInfo } = {
[newStreamInfo.id]: {
// Orderposition will get overwritten by sortStreamClipsByStartTime after creation
orderPosition:
index + currentHighestOrderPosition + (currentHighestOrderPosition === 0 ? 0 : 1),
initialStartTime: clip.startTime,
initialEndTime: clip.endTime,
},
};
this.ADD_CLIP({
path: clip.path,
loaded: false,
enabled: true,
startTrim: clip.startTrim,
endTrim: clip.endTrim,
deleted: false,
source: 'AiClip',
aiInfo: clip.aiClipInfo,
globalOrderPosition:
index + getHighestGlobalOrderPosition + (getHighestGlobalOrderPosition === 0 ? 0 : 1),
streamInfo,
});
});
this.sortStreamClipsByStartTime(this.views.clips, newStreamInfo);
await this.loadClips(newStreamInfo.id);
}
// This sorts all clips (replayBuffer and aiClips) by initialStartTime
// That will assure that replayBuffer clips are also sorted in correctly in the stream
sortStreamClipsByStartTime(clips: TClip[], newStreamInfo: IStreamInfoForAiHighlighter) {
const allClips = this.getClips(clips, newStreamInfo.id);
const sortedClips = allClips.sort(
(a, b) =>
(a.streamInfo?.[newStreamInfo.id]?.initialStartTime || 0) -
(b.streamInfo?.[newStreamInfo.id]?.initialStartTime || 0),
);
// Update order positions based on the sorted order
sortedClips.forEach((clip, index) => {
this.UPDATE_CLIP({
path: clip.path,
streamInfo: {
[newStreamInfo.id]: {
...(clip.streamInfo?.[newStreamInfo.id] ?? {}),
orderPosition: index,
},
},
});
});
return;
}
enableClip(path: string, enabled: boolean) {
this.UPDATE_CLIP({
path,
enabled,
});
}
disableClip(path: string) {
this.UPDATE_CLIP({
path,
enabled: false,
});
}
setStartTrim(path: string, trim: number) {
this.UPDATE_CLIP({
path,
startTrim: trim,
});
}
setEndTrim(path: string, trim: number) {
this.UPDATE_CLIP({
path,
endTrim: trim,
});
}
removeClip(path: string, streamId: string | undefined) {
const clip: TClip = this.state.clips[path];
if (!clip) {
console.warn(`Clip not found for path: ${path}`);
return;
}
if (
fileExists(path) &&
streamId &&
clip.streamInfo &&
Object.keys(clip.streamInfo).length > 1
) {
const updatedStreamInfo = { ...clip.streamInfo };
delete updatedStreamInfo[streamId];
this.UPDATE_CLIP({
path: clip.path,
streamInfo: updatedStreamInfo,
});
} else {
this.REMOVE_CLIP(path);
this.removeScrubFile(clip.scrubSprite);
delete this.renderingClips[path];
}
if (clip.streamInfo !== undefined || streamId !== undefined) {
// if we are passing a streamId, only check if we need to remove the specific streamIds stream
// If we are not passing a streamId, check if we need to remove the streams the clip was part of
const ids: string[] = streamId ? [streamId] : Object.keys(clip.streamInfo ?? {});
const length = this.views.clips.length;
ids.forEach(id => {
let found = false;
if (length !== 0) {
for (let i = 0; i < length; i++) {
if (this.views.clips[i].streamInfo?.[id] !== undefined) {
found = true;
break;
}
}
}
if (!found) {
this.REMOVE_HIGHLIGHTED_STREAM(id);
}
});
}
}
async loadClips(streamInfoId?: string | undefined) {
const clipsToLoad: TClip[] = this.getClips(this.views.clips, streamInfoId);
// this.resetRenderingClips();
await this.ensureScrubDirectory();
for (const clip of clipsToLoad) {
if (!fileExists(clip.path)) {
this.removeClip(clip.path, streamInfoId);
return;
}
if (!SUPPORTED_FILE_TYPES.map(e => `.${e}`).includes(path.parse(clip.path).ext)) {
this.removeClip(clip.path, streamInfoId);
this.SET_ERROR(
$t(
'One or more clips could not be imported because they were not recorded in a supported file format.',
),
);
}
this.renderingClips[clip.path] =
this.renderingClips[clip.path] ?? new RenderingClip(clip.path);
}
//TODO M: tracking type not correct
await pmap(
clipsToLoad.filter(c => !c.loaded),
c => this.renderingClips[c.path].init(),
{
concurrency: os.cpus().length,
onProgress: completed => {
this.usageStatisticsService.recordAnalyticsEvent(
this.views.useAiHighlighter ? 'AIHighlighter' : 'Highlighter',
{
type: 'ClipImport',
source: completed.source,
},
);
this.UPDATE_CLIP({
path: completed.path,
loaded: true,
scrubSprite: this.renderingClips[completed.path].frameSource?.scrubJpg,
duration: this.renderingClips[completed.path].duration,
deleted: this.renderingClips[completed.path].deleted,
});
},
},
);
return;
}
getClips(clips: TClip[], streamId?: string): TClip[] {
return clips.filter(clip => {
if (clip.path === 'add') {
return false;
}
const exists = fileExists(clip.path);
if (!exists) {
this.removeClip(clip.path, streamId);
return false;
}
if (streamId) {
return clip.streamInfo?.[streamId];
}
return true;
});
}
getClipsLoaded(clips: TClip[], streamId?: string): boolean {
return this.getClips(clips, streamId).every(clip => clip.loaded);
}
private hasUnloadedClips(streamId?: string) {
return !this.views.clips
.filter(c => {
if (!c.enabled) return false;
if (!streamId) return true;
return c.streamInfo && c.streamInfo[streamId] !== undefined;
})
.every(clip => clip.loaded);
}
enableOnlySpecificClips(clips: TClip[], streamId?: string) {
clips.forEach(clip => {
this.UPDATE_CLIP({
path: clip.path,
enabled: false,
});
});
// Enable specific clips
const clipsToEnable = this.getClips(clips, streamId);
clipsToEnable.forEach(clip => {
this.UPDATE_CLIP({
path: clip.path,
enabled: true,
});
});
}
// =================================================================================================
// STREAM logic
// =================================================================================================
// TODO M: Temp way to solve the issue
addStream(streamInfo: IHighlightedStream) {
return new Promise<void>(resolve => {
this.ADD_HIGHLIGHTED_STREAM(streamInfo);
setTimeout(() => {
resolve();
}, 2000);
});
}
updateStream(streamInfo: IHighlightedStream) {
this.UPDATE_HIGHLIGHTED_STREAM(streamInfo);
}
removeStream(streamId: string) {
this.REMOVE_HIGHLIGHTED_STREAM(streamId);
//Remove clips from stream
const clipsToRemove = this.getClips(this.views.clips, streamId);
clipsToRemove.forEach(clip => {
this.removeClip(clip.path, streamId);
});
}
// =================================================================================================
// SCRUB logic
// =================================================================================================
private async ensureScrubDirectory() {
try {
try {
//If possible to read, directory exists, if not, catch and mkdir
await fs.readdir(SCRUB_SPRITE_DIRECTORY);
} catch (error: unknown) {
await fs.mkdir(SCRUB_SPRITE_DIRECTORY);
}
} catch (error: unknown) {
console.log('Error creating scrub sprite directory');
}
}
async removeScrubFile(clipPath: string | undefined) {
if (!clipPath) {
console.warn('No scrub file path provided');
return;
}
try {
await fs.remove(clipPath);
} catch (error: unknown) {
console.error('Error removing scrub file', error);
}
}
// =================================================================================================
// EXPORT logic
// =================================================================================================
/**
* Exports the video using the currently configured settings
* Return true if the video was exported, or false if not.
*/
async export(
preview = false,
streamId: string | undefined = undefined,
orientation: TOrientation = 'horizontal',
) {
this.resetRenderingClips();
await this.loadClips(streamId);
if (this.hasUnloadedClips(streamId)) {
console.error('Highlighter: Export called while clips are not fully loaded!: ');
return;
}
if (this.views.exportInfo.exporting) {
console.error('Highlighter: Cannot export until current export operation is finished');
return;
}
this.SET_EXPORT_INFO({
exporting: true,
currentFrame: 0,
step: EExportStep.AudioMix,
cancelRequested: false,
error: null,
});
let renderingClips: RenderingClip[] = await this.generateRenderingClips(streamId, orientation);
const exportOptions: IExportOptions = this.generateExportOptions(
renderingClips,
preview,
orientation,
);
// Reset all clips
await pmap(renderingClips, c => c.reset(exportOptions), {
onProgress: c => {
if (c.deleted) {
this.UPDATE_CLIP({ path: c.sourcePath, deleted: true });
}
},
});
// TODO: For now, just remove deleted clips from the video
// In the future, abort export and surface error to the user.
renderingClips = renderingClips.filter(c => !c.deleted);
if (!renderingClips.length) {
console.error('Highlighter: Export called without any clips!');
this.SET_EXPORT_INFO({
exporting: false,
exported: false,
error: $t('Please select at least one clip to export a video'),
});
return;
}
const setExportInfo = (partialExportInfo: Partial<IExportInfo>) => {
this.SET_EXPORT_INFO(partialExportInfo);
};
const recordAnalyticsEvent = (type: TAnalyticsEvent, data: Record<string, unknown>) => {
this.usageStatisticsService.recordAnalyticsEvent(type, data);
};
const handleFrame = (currentFrame: number) => {
this.setCurrentFrame(currentFrame);
};
startRendering(
{
isPreview: preview,
renderingClips,
exportInfo: this.views.exportInfo,
exportOptions,
audioInfo: this.views.audio,
transitionDuration: this.views.transitionDuration,
transition: this.views.transition,
useAiHighlighter: this.views.useAiHighlighter,
streamId,
},
handleFrame,
setExportInfo,
recordAnalyticsEvent,
);