-
Notifications
You must be signed in to change notification settings - Fork 703
/
Copy pathrecording-mode.ts
381 lines (326 loc) · 11.7 KB
/
recording-mode.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
import Vue from 'vue';
import moment from 'moment';
import * as Sentry from '@sentry/browser';
import { Inject, mutation, PersistentStatefulService, ViewHandler, Service } from 'services/core';
import { SourcesService } from './sources';
import { $t } from './i18n';
import { ELayout, ELayoutElement, LayoutService } from './layout';
import { ScenesService } from './scenes';
import { EObsSimpleEncoder, SettingsService } from './settings';
import { AnchorPoint, ScalableRectangle } from 'util/ScalableRectangle';
import { TDisplayType, VideoSettingsService } from './settings-v2/video';
import { ENotificationType, NotificationsService } from 'services/notifications';
import { DefaultHardwareService } from './hardware';
import { RunInLoadingMode } from './app/app-decorators';
import { byOS, OS } from 'util/operating-systems';
import { JsonrpcService } from './api/jsonrpc';
import { NavigationService, UsageStatisticsService, SharedStorageService } from 'app-services';
import { getPlatformService } from 'services/platforms';
import { IYoutubeUploadResponse } from 'services/platforms/youtube/uploader';
import { YoutubeService } from 'services/platforms/youtube';
import { capitalize } from 'lodash';
export interface IRecordingEntry {
timestamp: string;
filename: string;
}
export interface IUploadInfo {
uploading: boolean;
uploadedBytes?: number;
totalBytes?: number;
error?: string;
}
interface IRecordingModeState {
enabled: boolean;
recordingHistory: Dictionary<IRecordingEntry>;
uploadInfo: IUploadInfo;
}
class RecordingModeViews extends ViewHandler<IRecordingModeState> {
get isRecordingModeEnabled() {
return this.state.enabled;
}
get sortedRecordings() {
return Object.values(this.state.recordingHistory).sort((a, b) =>
moment(a.timestamp).isAfter(moment(b.timestamp)) ? -1 : 1,
);
}
formattedTimestamp(timestamp: string) {
return moment(timestamp).fromNow();
}
}
export class RecordingModeService extends PersistentStatefulService<IRecordingModeState> {
@Inject() private layoutService: LayoutService;
@Inject() private scenesService: ScenesService;
@Inject() private settingsService: SettingsService;
@Inject() private sourcesService: SourcesService;
@Inject() private videoSettingsService: VideoSettingsService;
@Inject() private defaultHardwareService: DefaultHardwareService;
@Inject() private notificationsService: NotificationsService;
@Inject() private jsonrpcService: JsonrpcService;
@Inject() private usageStatisticsService: UsageStatisticsService;
@Inject() private navigationService: NavigationService;
@Inject() private sharedStorageService: SharedStorageService;
static defaultState: IRecordingModeState = {
enabled: false,
recordingHistory: {},
uploadInfo: { uploading: false } as IUploadInfo,
};
static filter(state: IRecordingModeState) {
return { ...state, uploadInfo: {} };
}
init() {
super.init();
this.pruneRecordingEntries();
}
cancelFunction = () => {};
cancelUpload() {
this.cancelFunction();
this.SET_UPLOAD_INFO({});
}
get views() {
return new RecordingModeViews(this.state);
}
/**
* When recording mode is enabled as part of onboarding, it does a handful
* of initial setup items that differ from if you are streaming. These are
* only ever done during onboarding from a fresh cache, and won't be
* performed if you later enable recording mode.
*/
setUpRecordingFirstTimeSetup() {
this.setRecordingLayout();
this.addRecordingCapture();
this.setRecordingEncoder();
}
setRecordingMode(enabled: boolean) {
this.SET_RECORDING_MODE(enabled);
}
private setRecordingLayout() {
this.layoutService.changeLayout(ELayout.Classic);
this.layoutService.setSlots({
[ELayoutElement.Display]: { slot: '1' },
[ELayoutElement.Scenes]: { slot: '2' },
[ELayoutElement.Sources]: { slot: '3' },
[ELayoutElement.Mixer]: { slot: '4' },
});
this.layoutService.setBarResize('bar1', 0.3);
}
private addRecordingCapture() {
this.scenesService.views.activeScene.createAndAddSource(
$t('Screen Capture (Double-click to select)'),
byOS({ [OS.Windows]: 'screen_capture', [OS.Mac]: 'window_capture' }),
);
}
/**
* This is only done after hardware setup so that we apply the
* correct webcam and preset filter.
*/
@RunInLoadingMode()
async addRecordingWebcam() {
// Force clearing of temporary sources
this.defaultHardwareService.clearTemporarySources();
// This gives the backend time to release exclusive rights to the webcam
// TODO: This really shouldn't be required to be a race condition.
await new Promise(r => {
setTimeout(r, 2000);
});
const item = this.scenesService.views.activeScene.createAndAddSource(
'Webcam',
byOS({ [OS.Windows]: 'dshow_input', [OS.Mac]: 'av_capture_input' }),
);
let sub = this.sourcesService.sourceUpdated.subscribe(s => {
if (s.sourceId === item.source.sourceId && s.width && s.height) {
sub.unsubscribe();
sub = null;
// Create a rect to represent the source
const rect = new ScalableRectangle({ x: 0, y: 0, width: s.width, height: s.height });
// Scale width to approximately 25% of canvas width
rect.scaleX = (this.videoSettingsService.baseWidth / rect.width) * 0.25;
// Scale height to match
rect.scaleY = rect.scaleX;
// Move to just near bottom left corner
rect.withAnchor(AnchorPoint.SouthWest, () => {
rect.x = 20;
rect.y = this.videoSettingsService.baseHeight - 20;
});
item.setTransform({
position: { x: rect.x, y: rect.y },
scale: { x: rect.scaleX, y: rect.scaleY },
});
}
});
// If for some reason we don't hear about the width/height within 10
// seconds, don't keep waiting for it to come.
setTimeout(() => {
if (sub) sub.unsubscribe();
}, 10 * 1000);
}
/**
* Add entry to recording history and show notification
* @param filename - name of file to show in recording history
* @param showNotification - primarily used when recording in dual output mode to only show the notification once
*/
addRecordingEntry(filename: string, display?: TDisplayType) {
const timestamp = moment().format();
this.ADD_RECORDING_ENTRY(timestamp, filename);
const message = display
? $t(`A new ${capitalize(display)} Recording has been completed. Click for more info`)
: $t('A new Recording has been completed. Click for more info');
this.notificationsService.actions.push({
type: ENotificationType.SUCCESS,
message,
action: this.jsonrpcService.createRequest(
Service.getResourceId(this),
'showRecordingHistory',
),
});
}
removeRecordingEntry(timestamp: string) {
this.REMOVE_RECORDING_ENTRY(timestamp);
}
pruneRecordingEntries() {
if (Object.keys(this.state.recordingHistory).length < 30) return;
const oneMonthAgo = moment().subtract(30, 'days');
const prunedEntries: Dictionary<IRecordingEntry> = {};
Object.keys(this.state.recordingHistory).forEach(timestamp => {
if (moment(timestamp).isAfter(oneMonthAgo)) {
prunedEntries[timestamp] = this.state.recordingHistory[timestamp];
}
});
this.SET_RECORDING_ENTRIES(prunedEntries);
}
showRecordingHistory() {
this.navigationService.navigate('RecordingHistory');
}
async uploadToYoutube(filename: string) {
const yt = getPlatformService('youtube') as YoutubeService;
this.SET_UPLOAD_INFO({ uploading: true });
const { cancel, complete } = yt.uploader.uploadVideo(
filename,
{ title: filename, description: '', privacyStatus: 'private' },
progress => {
this.SET_UPLOAD_INFO({
uploadedBytes: progress.uploadedBytes,
totalBytes: progress.totalBytes,
});
},
);
this.cancelFunction = cancel;
let result: IYoutubeUploadResponse | null = null;
try {
result = await complete;
} catch (e: unknown) {
Sentry.withScope(scope => {
scope.setTag('feature', 'recording-history');
console.error('Got error uploading YT video', e);
});
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadYouTubeError',
});
}
this.cancelFunction = () => {};
this.CLEAR_UPLOAD_INFO();
if (result) {
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadYouTubeSuccess',
privacy: 'private',
});
return result.id;
}
}
async uploadToStorage(filename: string, platform: string) {
this.SET_UPLOAD_INFO({ uploading: true });
const { cancel, complete, size } = await this.sharedStorageService.actions.return.uploadFile(
filename,
progress => {
this.SET_UPLOAD_INFO({
uploadedBytes: progress.uploadedBytes,
totalBytes: progress.totalBytes,
});
},
(error: unknown) => {
this.SET_UPLOAD_INFO({ error: error.toString() });
},
platform,
);
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadStorageBegin',
fileSize: size,
platform,
});
this.cancelFunction = () => {
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadStorageCancel',
fileSize: size,
platform,
});
cancel();
};
let result;
try {
result = await complete;
} catch (e: unknown) {
Sentry.withScope(scope => {
scope.setTag('feature', 'recording-history');
console.error('Got error uploading Storage video', e);
});
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadStorageError',
fileSize: size,
platform,
});
}
this.cancelFunction = () => {};
this.CLEAR_UPLOAD_INFO();
if (result) {
this.usageStatisticsService.recordAnalyticsEvent('RecordingHistory', {
type: 'UploadStorageSuccess',
fileSize: size,
platform,
});
return result.id;
}
}
private setRecordingEncoder() {
const encoderPriority: EObsSimpleEncoder[] = [
EObsSimpleEncoder.jim_nvenc,
EObsSimpleEncoder.amd,
EObsSimpleEncoder.nvenc,
EObsSimpleEncoder.x264,
];
// Set these first, as they affect available options
this.settingsService.setSettingsPatch({ Output: { Mode: 'Simple' } });
this.settingsService.setSettingsPatch({ Output: { RecQuality: 'Small' } });
const availableEncoders = this.settingsService
.findSetting(this.settingsService.state.Output.formData, 'Recording', 'RecEncoder')
.options.map((opt: { value: EObsSimpleEncoder }) => opt.value);
const bestEncoder = encoderPriority.find(e => {
return availableEncoders.includes(e);
});
this.settingsService.setSettingsPatch({
Output: { RecEncoder: bestEncoder, RecFormat: 'mp4' },
});
}
@mutation()
private ADD_RECORDING_ENTRY(timestamp: string, filename: string) {
Vue.set(this.state.recordingHistory, timestamp, { timestamp, filename });
}
@mutation()
private REMOVE_RECORDING_ENTRY(timestamp: string) {
Vue.delete(this.state.recordingHistory, timestamp);
}
@mutation()
private SET_RECORDING_ENTRIES(entries: Dictionary<IRecordingEntry>) {
this.state.recordingHistory = entries;
}
@mutation()
private SET_RECORDING_MODE(val: boolean) {
this.state.enabled = val;
}
@mutation()
private SET_UPLOAD_INFO(info: Partial<IUploadInfo>) {
this.state.uploadInfo = { ...this.state.uploadInfo, ...info };
}
@mutation()
private CLEAR_UPLOAD_INFO() {
this.state.uploadInfo = { uploading: false };
}
}