aboutsummaryrefslogtreecommitdiff
path: root/elac-encode
blob: 61f909b91178f55d300fdc9551383ce387c0e8a3 (plain)
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
#!/usr/bin/env node
global.path = require('path');
global.fs = require('fs');
global.zlib = require('zlib');
global.os = require('os');
global.child_process = require('child_process');
global.uuid = require('uuid')['v4'];

global.version = "1.1";

global.argv = process.argv;
argv.shift(); argv.shift();

console.log("Equestria Lossless Audio Codec");
console.log("    (c) Copyright, Equestria.dev");
console.log("ELAC Encoder");
console.log("    (c) Copyright, Equestria.dev");
console.log("version " + version);
console.log("");

try {
    child_process.execSync("ffmpeg -version");
    child_process.execSync("ffprobe -version");
    child_process.execSync("ffplay -version");
} catch (e) {
    console.error("Unable to start the ELAC Encoder:\n    ffmpeg was not found or is incomplete");
    process.exit(2);
}

if (argv.length < 1) {
    console.error("Unable to start the ELAC Encoder:\n    No output file has been specified");
    process.exit(2);
}

global.output = argv[0].trim();
global.dir = path.dirname(output);
global.file = path.basename(output);

if (!output.endsWith(".elac")) {
    console.warn("warning: specified output (\"" + output + "\") does not contain extension, using \"" + output + ".elac\" instead.");
    file = file + ".elac";
    output = output + ".elac";
}

if (!fs.existsSync(dir)) {
    console.error("Unable to encode \"" + file + "\":\n    \"" + dir + "\": no such file or directory");
    process.exit(2);
}

if (fs.existsSync(output)) {
    console.error("Unable to encode \"" + file + "\":\n    \"" + output + "\": file exists");
    process.exit(2);
}

if (argv.length < 2) {
    console.error("Unable to encode \"" + file + "\":\n    No input stream found");
    process.exit(2);
}

global.inputs = argv; inputs.shift();
global.valid_inputs = [];
global.out = {
    _eqmc: true,
    files: []
};

for (let input of inputs) {
    if (!fs.existsSync(input)) {
        console.warn("warning: specified input (\"" + input + "\") cannot be used: no such file or directory.");
        continue;
    }
    try {
        fs.readFileSync(input);
    } catch (e) {
        console.warn("warning: specified input (\"" + input + "\") cannot be used: file is unreadable.");
        continue;
    }
    let probe = JSON.parse(child_process.execFileSync("ffprobe", [ "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", input]).toString());

    let streams = probe.streams.filter(i => i['codec_type'] === "audio");

    if (streams.length < 1) {
        console.warn("warning: specified input (\"" + input + "\") cannot be used: no audio streams found.");
        continue;
    }

    if (streams.length > 1) {
        console.warn("warning: specified input (\"" + input + "\") contains more than one audio stream, only the " + probe.streams[0]["codec_name"] + " stream will be used.");
        continue;
    }

    valid_inputs.push(input);
}

for (let input of valid_inputs) {
    let probe = JSON.parse(child_process.execFileSync("ffprobe", [ "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", input]).toString());
    let streams = probe.streams.filter(i => i['codec_type'] === "audio");
    let fileId = uuid();

    let lossless = false;
    let outFile = os.tmpdir() + "/elac-encode-temp/" + fileId + ".mp3";

    if (streams[0]['codec_name'].includes("pcm") || streams[0]['codec_name'].includes("flac") || streams[0]['codec_name'].includes("alac") || streams[0]['codec_name'].includes("dts")) {
        lossless = true;
        outFile = os.tmpdir() + "/elac-encode-temp/" + fileId + ".flac";
    }

    console.log("\n" + input + ":");
    console.log("    Duration: " + new Date(probe.format['duration'] * 1000).toISOString().substring(11, 19));
    console.log("    Container Type: " + probe.format['format_long_name']);
    console.log("    Stream Type: " + streams[0]['codec_long_name']);
    console.log("    ELAC Stream ID: " + fileId);
    console.log("    Lossless Mode: " + (lossless ? "yes" : "no") + " (" + (lossless ? "ELAC Physical Lossless" : "ELAC Emulated Lossless") + ")");
    console.log("");

    try {
        if (fs.existsSync(os.tmpdir() + "/elac-encode-temp")) {
            fs.rmSync(os.tmpdir() + "/elac-encode-temp", { recursive: true });
        }
        fs.mkdirSync(os.tmpdir() + "/elac-encode-temp", { recursive: true });
    } catch (e) {
        console.error("Unable to encode \"" + file + "\":\n    Cannot create temporary working directory");
        process.exit(2);
    }

    console.log("Encoding \"" + output + ":/" + fileId + "\"...");
    try {
        child_process.execFileSync("ffmpeg", [ "-v", "quiet", "-i", input, "-map_metadata", "-1", outFile ]);
        if (!fs.existsSync(outFile)) {
            console.error("Unable to encode \"" + file + "\":\n    Successfully encoded file " + fileId + ", but file does not exist");
            process.exit(2);
        }
    } catch (e) {
        console.error("Unable to encode \"" + file + "\":\n    Failed to encode file " + fileId);
        process.exit(2);
    }

    out.files.push({
        _id: fileId,
        lossless,
        data: zlib.deflateSync(fs.readFileSync(outFile), {
            level: -1,
            strategy: 0,
            memLevel: 9
        }).toString("base64"),
        tags: probe.format.tags
    })

    try {
        fs.rmSync(os.tmpdir() + "/elac-encode-temp", { recursive: true });
    } catch (e) {
        console.error("Unable to encode \"" + file + "\":\n    Cannot clear temporary working directory");
        process.exit(2);
    }
}

console.log("Writing to \"" + output + "\"...");
fs.writeFileSync(output, zlib.deflateSync(JSON.stringify(out), {
    level: -1,
    strategy: 0,
    memLevel: 9
}));
console.log("Done!");