-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate.ts
More file actions
207 lines (186 loc) · 5.81 KB
/
create.ts
File metadata and controls
207 lines (186 loc) · 5.81 KB
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
import { Command } from '@cliffy/command';
import type Mux from '@mux/mux-node';
import { handleCommandError } from '@/lib/errors.ts';
import { createAuthenticatedMuxClient } from '@/lib/mux.ts';
type Resolution = NonNullable<
Mux.Video.AssetCreateStaticRenditionParams['resolution']
>;
const VALID_RESOLUTIONS: Resolution[] = [
'highest',
'audio-only',
'2160p',
'1440p',
'1080p',
'720p',
'540p',
'480p',
'360p',
'270p',
];
interface CreateOptions {
resolution: Resolution;
passthrough?: string;
wait?: boolean;
json?: boolean;
}
export const createCommand = new Command()
.description('Create a static rendition for an asset')
.arguments('<asset-id:string>')
.option(
'-r, --resolution <resolution:string>',
'Target resolution (highest, audio-only, 2160p, 1440p, 1080p, 720p, 540p, 480p, 360p, 270p)',
{
required: true,
value: (value: string): Resolution => {
if (!VALID_RESOLUTIONS.includes(value as Resolution)) {
throw new Error(
`Invalid resolution: ${value}. Must be one of: ${VALID_RESOLUTIONS.join(', ')}`,
);
}
return value as Resolution;
},
},
)
.option(
'-p, --passthrough <passthrough:string>',
'Arbitrary metadata stored on rendition and returned in API responses (max 255 chars)',
)
.option(
'-w, --wait',
'Wait for the rendition to be ready (polls up to 10 minutes, exits with error on timeout)',
)
.option('--json', 'Output JSON instead of pretty format')
.action(async (options: CreateOptions, assetId: string) => {
try {
const mux = await createAuthenticatedMuxClient();
const params: Mux.Video.AssetCreateStaticRenditionParams = {
resolution: options.resolution,
};
if (options.passthrough) {
if (options.passthrough.length > 255) {
throw new Error('Passthrough value must be 255 characters or less');
}
params.passthrough = options.passthrough;
}
const rendition = await mux.video.assets.createStaticRendition(
assetId,
params,
);
if (options.wait && rendition.status === 'preparing') {
const finalRendition = await pollForRendition(
mux,
assetId,
rendition.id as string,
options.json,
);
outputRendition(finalRendition, options.json, false);
} else {
outputRendition(rendition, options.json, !options.wait);
}
} catch (error) {
await handleCommandError(error, 'assets', 'create', options);
}
});
async function pollForRendition(
mux: Mux,
assetId: string,
renditionId: string,
jsonOutput?: boolean,
): Promise<Mux.Video.AssetCreateStaticRenditionResponse> {
const POLL_INTERVAL_MS = 2000;
const MAX_POLL_TIME_MS = 10 * 60 * 1000; // 10 minutes
const startTime = Date.now();
if (!jsonOutput) {
process.stdout.write('Waiting for rendition to be ready');
}
while (Date.now() - startTime < MAX_POLL_TIME_MS) {
const asset = await mux.video.assets.retrieve(assetId);
const files = asset.static_renditions?.files ?? [];
const rendition = files.find((f) => f.id === renditionId);
if (rendition) {
if (rendition.status === 'ready') {
if (!jsonOutput) {
console.log(' done!');
}
return rendition as Mux.Video.AssetCreateStaticRenditionResponse;
}
if (rendition.status === 'errored') {
if (!jsonOutput) {
console.log(' failed!');
}
return rendition as Mux.Video.AssetCreateStaticRenditionResponse;
}
if (rendition.status === 'skipped') {
if (!jsonOutput) {
console.log(' skipped!');
}
return rendition as Mux.Video.AssetCreateStaticRenditionResponse;
}
}
if (!jsonOutput) {
process.stdout.write('.');
}
await sleep(POLL_INTERVAL_MS);
}
throw new Error('Timed out waiting for rendition to be ready');
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function outputRendition(
rendition: Mux.Video.AssetCreateStaticRenditionResponse,
jsonOutput?: boolean,
showAsyncMessage?: boolean,
) {
if (jsonOutput) {
console.log(JSON.stringify(rendition, null, 2));
} else {
console.log(`Static rendition created:`);
console.log(` ID: ${rendition.id}`);
console.log(` Name: ${rendition.name}`);
console.log(` Resolution: ${rendition.resolution}`);
console.log(` Status: ${rendition.status}`);
if (rendition.width && rendition.height) {
console.log(` Dimensions: ${rendition.width}x${rendition.height}`);
}
if (rendition.bitrate) {
console.log(` Bitrate: ${formatBitrate(rendition.bitrate)}`);
}
if (rendition.filesize) {
console.log(` Size: ${formatFilesize(rendition.filesize)}`);
}
if (rendition.passthrough) {
console.log(` Passthrough: ${rendition.passthrough}`);
}
if (showAsyncMessage && rendition.status === 'preparing') {
console.log(
'\nNote: Static rendition generation is asynchronous. ' +
"Use 'mux assets static-renditions list <asset-id>' to check the status, " +
'or use the --wait flag to poll until ready.',
);
}
}
}
function formatBitrate(bps: number): string {
if (bps >= 1_000_000) {
return `${(bps / 1_000_000).toFixed(1)} Mbps`;
}
if (bps >= 1_000) {
return `${(bps / 1_000).toFixed(0)} kbps`;
}
return `${bps} bps`;
}
function formatFilesize(bytes: string): string {
const size = Number.parseInt(bytes, 10);
if (Number.isNaN(size)) return bytes;
if (size >= 1_000_000_000) {
return `${(size / 1_000_000_000).toFixed(1)} GB`;
}
if (size >= 1_000_000) {
return `${(size / 1_000_000).toFixed(1)} MB`;
}
if (size >= 1_000) {
return `${(size / 1_000).toFixed(1)} KB`;
}
return `${size} B`;
}