-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.ts
293 lines (269 loc) · 9.88 KB
/
cli.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
import { bold, red, yellow } from "https://deno.land/[email protected]/fmt/colors.ts";
import { toText } from "https://deno.land/[email protected]/streams/to_text.ts";
import {
Command,
EnumType,
ValidationError,
} from "https://deno.land/x/[email protected]/command/mod.ts";
import { Table } from "https://deno.land/x/[email protected]/table/mod.ts";
import { MusicBrainzClient } from "jsr:@kellnerd/musicbrainz@^0.0.3";
import {
detectFormatAndParseCueSheet,
formatCueSheet,
getPossibleFormatsByExtension,
parseCueSheet,
} from "./conversion.ts";
import { type CueSheet } from "./cuesheet.ts";
import {
type CueFormatId,
formats,
inputFormatIds,
outputFormatIds,
} from "./formats.ts";
import { createFFmpegArguments } from "./format/ffmpeg_commands.ts";
import { recommendedFFProbeOptions } from "./format/ffprobe_json.ts";
const version = "0.7.2";
const userAgent = `cueshit/${version} ( https://deno.land/x/cueshit )`;
/** MusicBrainz URLs which are accepted by the CLI. */
const musicBrainzUrlPattern = new URLPattern({
pathname: "/release/:mbid([0-9a-f-]{36})",
});
/**
* Creates a cue sheet from the content at the given input path or URL.
*
* - Automatically tries to detect format from file extension if not specified.
* - Tries to call ffprobe for (multimedia) files with an unknown extension.
* - If the extension is ambiguous, all parsers will be tried until success.
*
* @param inputPathOrUrl Path or URL to the input, falls back to standard input.
* @param options Source format and additional cue sheet properties.
*/
export async function processCueSheetInput(
inputPathOrUrl: string | undefined,
options: {
from?: CueFormatId;
sheet?: Record<string, string | undefined>;
},
): Promise<CueSheet> {
let input: string;
if (inputPathOrUrl) {
if (!options.from) {
let url: URL | undefined;
try {
url = new URL(inputPathOrUrl);
} catch {
url = undefined;
}
if (url) {
const mbid = musicBrainzUrlPattern.exec(url)?.pathname.groups.mbid;
if (mbid) {
const mb = new MusicBrainzClient({ userAgent });
const release = await mb.lookup("release", mbid, [
"recordings",
"artist-credits",
]);
input = JSON.stringify(release);
options.from = "mb-api";
} else {
const response = await fetch(inputPathOrUrl, {
headers: { "User-Agent": userAgent },
});
if (!response.ok) {
throw new ValidationError(
"Failed to fetch from URL, are you sure it is supported?",
);
}
input = await response.text();
}
} else {
const possibleFormatIds = getPossibleFormatsByExtension(inputPathOrUrl);
// We do not know the extension, so we expect a multimedia file.
if (!possibleFormatIds.length) {
// Fail if ffprobe permission has not been configured.
const ffprobeStatus = await Deno.permissions.query({
name: "run",
command: "ffprobe",
});
if (ffprobeStatus.state !== "granted") {
throw new ValidationError(
"Unknown input file extension, please specify an input format.",
);
}
// If the CLI has the permission to call ffprobe, we try to do that.
const ffprobe = new Deno.Command("ffprobe", {
args: [...recommendedFFProbeOptions, inputPathOrUrl],
});
const { stderr, stdout, success } = await ffprobe.output();
const textDecoder = new TextDecoder();
if (success) {
input = textDecoder.decode(stdout);
options.from = "ffprobe";
} else {
throw new ValidationError(
`Failed to open input with ffprobe: ${
textDecoder.decode(stderr)
}You may want to explicitly specify an input format.`,
);
}
}
}
}
// The (text-based) input format has explicitly been specified or we know
// the file extension. We want to directly read the text content.
input ??= await Deno.readTextFile(inputPathOrUrl);
} else {
input = await toText(Deno.stdin.readable);
}
// Parse input, detect format if not specified.
let cueSheet: CueSheet | undefined;
if (options.from) {
// Specified input format is guaranteed to be supported (cliffy EnumType).
cueSheet = parseCueSheet(input, options.from)!;
} else {
const result = detectFormatAndParseCueSheet(input, inputPathOrUrl);
if (result) {
cueSheet = result.cueSheet;
} else {
logErrorAndExit("Input could not be parsed, unsupported format.");
}
}
// Set the values of cue sheet properties via CLI options.
for (const [key, value] of Object.entries(options.sheet ?? {})) {
if (key === "title" || key === "performer" || key === "mediaFile") {
cueSheet[key] = value;
} else if (key === "duration") {
cueSheet[key] = parseFloat(value!);
} else {
logErrorAndExit(`Cue sheets have no "${key}" property.`);
}
}
return cueSheet;
}
/** Cliffy command specification of the CLI. */
export const cli = new Command()
.name("cueshit")
.version(version)
.description(`
Convert between different cue sheet / chapter / tracklist formats.
Reads from standard input if no input path or URL is specified.
Writes to standard output if no output path is specified.
Automatically tries to detect input and output format if not specified.
`)
.globalType("input-format", new EnumType(inputFormatIds))
.globalType("output-format", new EnumType(outputFormatIds))
.option("-f, --from <format:input-format>", "ID of the input format.")
.option("-t, --to <format:output-format>", "ID of the output format.")
.option("-o, --output <path:file>", "Path to the output file.")
.option("--sheet.* <value>", "Set the value of a cue sheet property.")
.arguments("[input-path-or-url:file]")
.action(async (options, inputPathOrUrl) => {
if (!options.to && !options.output) {
throw new ValidationError(
'Missing option "--to" or "--output" to determine output format.',
);
}
const cueSheet = await processCueSheetInput(inputPathOrUrl, options);
// Determine output format using file extension, if not specified.
if (!options.to) {
const possibleOutputFormats = getPossibleFormatsByExtension(
// We have already checked above that `options.output` is specified.
options.output!,
).filter((format) =>
// Ignore irrelevant possible input formats.
outputFormatIds.includes(format)
);
if (possibleOutputFormats.length === 1) {
options.to = possibleOutputFormats[0];
} else {
throw new ValidationError(
`Missing option "--to", could not determine format by file extension.`,
);
}
}
// Try to format output.
const output = formatCueSheet(cueSheet, options.to);
if (!output) {
logErrorAndExit(`No formatter for "${options.to}" exists.`);
}
if (options.output) {
await Deno.writeTextFile(options.output, output);
} else {
console.log(output);
}
})
.command("formats", "List all supported formats.")
.action(() => {
const supported = (value: unknown) => value ? "X" : "";
new Table()
.header(["ID", "Input", "Output", "Name", "Extensions"].map(bold))
.body(
Object.entries(formats).map(([id, format]) => [
yellow(id),
supported(format.parse),
supported(format.format ?? format.formatCue),
format.name,
format.fileExtensions?.join(" "),
]),
)
.columns([{}, { align: "center" }, { align: "center" }])
.padding(2)
.render();
});
const ffmpegStatus = await Deno.permissions.query({
name: "run",
command: "ffmpeg",
});
// Register command which relies on the permission to run ffmpeg.
if (ffmpegStatus.state === "granted") {
cli
.command("split <input-path-or-url:file> [ffmpeg-options...]")
.description(`
Split a media file into its chapters (using ffmpeg).
Accepts a multimedia file with embedded chapters or a cue file as input.
May require path to source media file to be passed with "--sheet.media-file".
The split media files will be numbered and output into the working directory.
Additional ffmpeg options for the output file can be specified at the end.
`)
.option("-f, --from <format:input-format>", "ID of the input format.")
.option(
"-x, --ext <output-ext>",
"File extension of the output files (with leading period).",
)
.option("--sheet.* <value>", "Set the value of a cue sheet property.")
.stopEarly()
.action(async (options, inputPath, ...ffmpegOptions) => {
const cueSheet = await processCueSheetInput(inputPath, options);
if (!cueSheet.mediaFile) {
throw new ValidationError(
`Missing option "--sheet.media-file", input does not specify its path.`,
);
}
const textDecoder = new TextDecoder();
const chapterArguments = createFFmpegArguments(cueSheet, {
output: ffmpegOptions,
outputExtension: options.ext,
});
for (const args of chapterArguments) {
const ffmpeg = new Deno.Command("ffmpeg", { args });
const { stderr, success } = await ffmpeg.output();
// FFmpeg writes all log messages to stderr
const logMessages = textDecoder.decode(stderr).trimEnd();
if (logMessages) {
console.log(logMessages);
}
if (success) {
const outputPath = args.at(-1);
console.log(`Saved '${outputPath}'`);
} else {
logErrorAndExit("Failed to split input using ffmpeg.");
}
}
});
}
function logErrorAndExit(message: string, code = 1): never {
console.error(red(`${bold("error")}: ${message}`));
Deno.exit(code);
}
if (import.meta.main) {
await cli.parse();
}