summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/transformers/v17-to-v18.ts
blob: 660d91ee3c7be27c6f3d21f3c64069d9ecd769d6 (plain) (blame)
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
import type { MigrationResult, ProjectRecord } from "./types";
import { getProjectId, isRecord } from "./utils";

// Frozen snapshots of v18-era volume bounds. See ./README.md.
const VOLUME_DB_MIN = -60;
const VOLUME_DB_MAX = 20;

export function transformProjectV17ToV18({
	project,
}: {
	project: ProjectRecord;
}): MigrationResult<ProjectRecord> {
	if (!getProjectId({ project })) {
		return { project, skipped: true, reason: "no project id" };
	}

	if (typeof project.version === "number" && project.version >= 18) {
		return { project, skipped: true, reason: "already v18" };
	}

	return {
		project: {
			...migrateElementVolumes({ project }),
			version: 18,
		},
		skipped: false,
	};
}

function migrateElementVolumes({
	project,
}: {
	project: ProjectRecord;
}): ProjectRecord {
	const scenesValue = project.scenes;
	if (!Array.isArray(scenesValue)) {
		return project;
	}

	const migratedScenes = scenesValue.map((scene) => {
		if (!isRecord(scene)) {
			return scene;
		}

		const tracksValue = scene.tracks;
		if (!Array.isArray(tracksValue)) {
			return scene;
		}

		const migratedTracks = tracksValue.map((track) => {
			if (!isRecord(track)) {
				return track;
			}

			const elementsValue = track.elements;
			if (!Array.isArray(elementsValue)) {
				return track;
			}

			const migratedElements = elementsValue.map((element) => {
				if (!isRecord(element)) {
					return element;
				}

				if (element.type !== "audio" && element.type !== "video") {
					return element;
				}

				const legacyVolume = element.volume;
				return {
					...element,
					volume:
						typeof legacyVolume === "number" ? linearGainToDb(legacyVolume) : 0,
				};
			});

			return {
				...track,
				elements: migratedElements,
			};
		});

		return {
			...scene,
			tracks: migratedTracks,
		};
	});

	return {
		...project,
		scenes: migratedScenes,
	};
}

function linearGainToDb(gain: number): number {
	if (!Number.isFinite(gain)) {
		return 0;
	}

	if (gain <= 0) {
		return VOLUME_DB_MIN;
	}

	return clampDb(20 * Math.log10(gain));
}

function clampDb(value: number): number {
	if (!Number.isFinite(value)) {
		return 0;
	}

	return Math.min(VOLUME_DB_MAX, Math.max(VOLUME_DB_MIN, value));
}