ffmpeg.js

Here's the unminified and renamed version of the provided source code:

  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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
!function (global, ffmpeg) {
    "use strict";

    // Ensure FFmpegWASM is defined on the global object
    var root = ("object" == typeof exports && "object" == typeof module) ? module.exports = ffmpeg() :
        "function" == typeof define && define.amd ? define(ffmpeg) :
        "object" == typeof exports ? exports.FFmpegWASM = ffmpeg() : global.FFmpegWASM = ffmpeg();

    // Module variables
    var helper = {
        defineGlobalProperty: function (target, key, value) {
            Object.defineProperty(target, key, {
                enumerable: true,
                get: value
            });
        }
    };

    // Utility functions
    function isObject(object) {
        return object === Object(object);
    }

    function isFunction(functionToCheck) {
        return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
    }

    function getGlobal() {
        if (typeof globalThis !== 'undefined') {
            return globalThis;
        }
        try {
            return this || new Function("return this")();
        } catch (e) {
            if (typeof window !== 'undefined') {
                return window;
            }
        }
    }

    // Define utility methods on the helper object
    helper.assign = Object.assign;
    helper.merge = function (target, source) {
        if (isFunction(source)) {
            return function () {
                return target.apply(this, arguments)
            };
        }
        Object.keys(source).forEach(function (key) {
            target[key] = source[key];
        });
        return target;
    };

    // Module definition
    var FFmpegWASM = (function () {

        // Constants
        var LOAD = "LOAD";
        var EXEC = "EXEC";
        var WRITE_FILE = "WRITE_FILE";
        var READ_FILE = "READ_FILE";
        var DELETE_FILE = "DELETE_FILE";
        var RENAME = "RENAME";
        var CREATE_DIR = "CREATE_DIR";
        var LIST_DIR = "LIST_DIR";
        var DELETE_DIR = "DELETE_DIR";
        var ERROR = "ERROR";
        var DOWNLOAD = "DOWNLOAD";
        var PROGRESS = "PROGRESS";
        var LOG = "LOG";
        var MOUNT = "MOUNT";
        var UNMOUNT = "UNMOUNT";

        // Error messages
        var errorUnknownMessageType = new Error("unknown message type");
        var errorFFmpegNotLoaded = new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first");
        var errorFFmpegTerminated = new Error("called FFmpeg.terminate()");
        var errorFailedToImportFFmpegCoreJS = new Error("failed to import ffmpeg-core.js");

        // Instance variables
        var messageIdCounter = (function () {
            let counter = 0;
            return function () {
                counter++;
                return counter;
            }
        })();

        // Class definition
        class FFmpeg {
            constructor() {
                this.#eventListeners = {};
                this.#worker = null;
                this.#messageIdCounter = messageIdCounter;
                this.#promiseIdCounter = 0;
                this.#promiseResolvers = {};
                this.#loadPromises = [];
                this.#executionPromises = [];
                this.#fileSystem = {};
                this.#fileSystemPromises = [];
                this.loaded = false;
                this.#initWorker();
            }

            // Initialize the Web Worker
            #initWorker() {
                if (!this.#worker) {
                    const scriptUrl = new URL("ffmpeg-core.js", import.meta.url);
                    this.#worker = new Worker(scriptUrl, { type: "module" });
                    this.#worker.onmessage = this.#onWorkerMessage.bind(this);
                }
            }

            // Handle messages from the Web Worker
            #onWorkerMessage(event) {
                const message = event.data;
                const messageId = message.id;
                const messageType = message.type;

                switch (messageType) {
                    case LOAD:
                        this.loaded = true;
                        if (this.#loadPromises.length > 0) {
                            this.#loadPromises.forEach(promise => promise.resolve(this));
                            this.#loadPromises = [];
                        }
                        if (this.#executionPromises.length > 0) {
                            this.#executionPromises.forEach(promise => promise.resolve());
                            this.#executionPromises = [];
                        }
                        if (this.#fileSystemPromises.length > 0) {
                            this.#fileSystemPromises.forEach(promise => promise.resolve(this.#fileSystem));
                            this.#fileSystemPromises = [];
                        }
                        break;
                    case LOG:
                        if (this.#eventListeners.log) {
                            this.#eventListeners.log.forEach(listener => listener(message.data));
                        }
                        break;
                    case PROGRESS:
                        if (this.#eventListeners.progress) {
                            this.#eventListeners.progress.forEach(listener => listener(message.data));
                        }
                        break;
                    case ERROR:
                        if (this.#eventListeners[message.data.errorType]) {
                            this.#eventListeners[message.data.errorType].forEach(listener => listener(message.data.errorMessage));
                        }
                        break;
                    default:
                        if (this.#eventListeners[messageType]) {
                            this.#eventListeners[messageType].forEach(listener => listener(message.data));
                        }
                        break;
                }

                // Remove the message from the resolver if it exists
                if (this.#promiseResolvers[messageId]) {
                    delete this.#promiseResolvers[messageId];
                }
            }

            // Add an event listener
            on(eventType, listener) {
                if (!this.#eventListeners[eventType]) {
                    this.#eventListeners[eventType] = [];
                }
                this.#eventListeners[eventType].push(listener);
            }

            // Remove an event listener
            off(eventType, listener) {
                if (this.#eventListeners[eventType]) {
                    this.#eventListeners[eventType] = this.#eventListeners[eventType].filter(l => l !== listener);
                }
            }

            // Load FFmpeg
            load(options = {}, { signal } = {}) {
                return new Promise((resolve, reject) => {
                    if (this.loaded) {
                        resolve(this);
                        return;
                    }
                    this.#loadPromises.push(new Promise(resolve => { this.#promiseResolvers[this.#messageIdCounter()] = resolve; }));
                    this.#worker.postMessage({ type: LOAD, data: options }, []);
                });
            }

            // Execute an FFmpeg command
            exec(command, timeout = -1, { signal } = {}) {
                return new Promise((resolve, reject) => {
                    if (!this.loaded) {
                        reject(errorFFmpegNotLoaded);
                        return;
                    }
                    this.#executionPromises.push(new Promise(resolve => { this.#promiseResolvers[this.#messageIdCounter()] = resolve; }));
                    this.#worker.postMessage({ type: EXEC, data: { args: command, timeout: timeout } }, []);
                });
            }

            // Terminate the FFmpeg instance
            terminate() {
                if (this.#worker) {
                    this.#worker.terminate();
                    this.#worker = null;
                    this.loaded = false;
                }
            }

            // Write data to a file
            writeFile(file, data, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise((resolve, reject) => {
                    this.#worker.postMessage({ type: WRITE_FILE, data: { path: file, data: data } }, [data.buffer]);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // Mount a file system
            mount(fsType, options, mountPoint) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise(resolve => {
                    this.#worker.postMessage({ type: MOUNT, data: { fsType: fsType, options: options, mountPoint: mountPoint } }, []);
                    this.#fileSystem[mountPoint] = fsType;
                    resolve(this.#fileSystem[mountPoint]);
                });
            }

            // Unmount a file system
            unmount(mountPoint) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise(resolve => {
                    this.#worker.postMessage({ type: UNMOUNT, data: { mountPoint: mountPoint } }, []);
                    resolve();
                });
            }

            // Read data from a file
            readFile(file, encoding = "binary", { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise((resolve, reject) => {
                    this.#worker.postMessage({ type: READ_FILE, data: { path: file, encoding: encoding } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // Delete a file
            deleteFile(file, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise((resolve, reject) => {
                    this.#worker.postMessage({ type: DELETE_FILE, data: { path: file } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // Rename a file
            rename(oldPath, newPath, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise((resolve, reject) => {
                    this.#worker.postMessage({ type: RENAME, data: { oldPath: oldPath, newPath: newPath } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // Create a directory
            createDir(path, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise(resolve => {
                    this.#worker.postMessage({ type: CREATE_DIR, data: { path: path } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // List files in a directory
            listDir(path, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise(resolve => {
                    this.#worker.postMessage({ type: LIST_DIR, data: { path: path } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }

            // Delete a directory
            deleteDir(path, { signal } = {}) {
                if (!this.loaded) {
                    throw errorFFmpegNotLoaded;
                }
                return new Promise(resolve => {
                    this.#worker.postMessage({ type: DELETE_DIR, data: { path: path } }, []);
                    this.#promiseResolvers[this.#messageIdCounter()] = resolve;
                });
            }
        }

        return FFmpeg;
    }());

}(this, function ffmpeg() {
    // Helper functions
    function createUniqueId() {
        return '_' + Math.random().toString(36).substr(2);
    }

    function isPromise(promise) {
        return promise && typeof promise.then === 'function';
    }

    function isArray(array) {
        return Array.isArray(array);
    }

    function isUndefined(variable) {
        return typeof variable === 'undefined';
    }

    function isObject(object) {
        return object === Object(object);
    }

    function isFunction(fn) {
        return Object.prototype.toString.call(fn) === '[object Function]';
    }

    function assignProperties(target, source) {
        Object.keys(source).forEach(function (key) {
            target[key] = source[key];
        });
    }

    function getArrayBuffer(arrayBuffer) {
        return arrayBuffer.buffer;
    }

    function createArrayBuffer(buffer) {
        return new Uint8Array(buffer);
    }

    function uuidv4() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    function uuidMap() {
        var map = {};
        return {
            add: function (key, value) {
                map[key] = value;
            },
            remove: function (key) {
                delete map[key];
            },
            get: function () {
                return map;
            }
        };
    }

    function createError(type, message) {
        return {
            errorType: type,
            errorMessage: message
        };
    }

    // Constants
    var UNSUPPORTED_BROWSER = 'Unsupported browser. Please use Google Chrome or Mozilla Firefox.';
    var LOAD = "LOAD";
    var EXEC = "EXEC";
    var WRITE_FILE = "WRITE_FILE";
    var READ_FILE = "READ_FILE";
    var DELETE_FILE = "DELETE_FILE";
    var RENAME = "RENAME";
    var CREATE_DIR = "CREATE_DIR";
    var LIST_DIR = "LIST_DIR";
    var DELETE_DIR = "DELETE_DIR";
    var MOUNT = "MOUNT";
    var UNMOUNT = "UNMOUNT";
    var FATFS = "FATFS";
    var DOWNLOAD = "DOWNLOAD";
    var PROGRESS = "PROGRESS";
    var LOG = "LOG";
    var ERROR = "ERROR";
    var WARN = "WARN";

    // Errors
    var errorUnsupportedBrowser = new Error(UNSUPPORTED_BROWSER);
    var errorUnknownMessageType = new Error('Unknown message type');
    var errorFFmpegNotLoaded = new Error('FFmpeg is not loaded yet');
    var errorFFmpegInstanceTerminated = new Error('FFmpeg instance is terminated');
    var errorFailedToImportFFmpegCoreJS = new Error('Failed to import ffmpeg-core.js');
    var errorInvalidResponse = new Error('Invalid response from FFmpeg');
    var errorFFmpegNotFound = new Error('FFmpeg not found');

    // Map of event listeners
    var eventListeners = {};

    // Map of promise resolvers
    var promiseResolvers = {};

    // The Web Worker
    var worker;

    // Message ID counter
    var messageIdCounter = (function () {
        let counter = 0;
        return function () {
            counter++;
            return counter;
        }
    })();

    // File system map
    var fileSystem = {};

    // File system promise resolvers
    var fileSystemPromiseResolvers = {};

    // Initialize the Web Worker
    function initWorker() {
        if (!worker) {
            const scriptUrl = new URL("ffmpeg-core.js", import.meta.url);
            worker = new Worker(scriptUrl, { type: "module" });
            worker.onmessage = onWorkerMessage;
        }
    }

    // Handle messages from the Web Worker
    function onWorkerMessage(event) {
        const message = event.data;
        const messageId = message.id;
        const messageType = message.type;

        switch (messageType) {
            case LOAD:
                if (fileSystemPromises.length > 0) {
                    fileSystemPromises.forEach(promise => promise.resolve(fileSystem));
                    fileSystemPromises = [];
                }
                break;
            case LOG:
                if (eventListeners.log) {
                    eventListeners.log.forEach(listener => listener(message.data));
                }
                break;
            case PROGRESS:
                if (eventListeners.progress) {
                    eventListeners.progress.forEach(listener => listener(message.data));
                }
                break;
            case ERROR:
                if (eventListeners[message.data.errorType]) {
                    eventListeners[message.data.errorType].forEach(listener => listener(message.data.errorMessage));
                }
                break;
            default:
                if (eventListeners[messageType]) {
                    eventListeners[messageType].forEach(listener => listener(message.data));
                }
                break;
        }

        // Remove the message from the resolver if it exists
        if (promiseResolvers[messageId]) {
            delete promiseResolvers[messageId];
        }
    }

    // Public methods

    // Add an event listener
    function on(eventType, listener) {
        if (!eventListeners[eventType]) {
            eventListeners[eventType] = [];
        }
        eventListeners[eventType].push(listener);
    }

    // Remove an event listener
    function off(eventType, listener) {
        if (eventListeners[eventType]) {
            eventListeners[eventType] = eventListeners[eventType].filter(l => l !== listener);
        }
    }

    // Load FFmpeg
    function load(options = {}, { signal } = {}) {
        return new Promise((resolve, reject) => {
            if (loaded) {
                resolve();
                return;
            }
            fileSystemPromises.push(new Promise(resolve => { fileSystemPromiseResolvers[messageIdCounter()] = resolve; }));
            worker.postMessage({ type: LOAD, data: options }, []);
        });
    }

    // Execute an FFmpeg command
    function exec(command, timeout = -1, { signal } = {}) {
        if (!loaded) {
            throw errorFFmpegNotLoaded;
        }
        return new Promise((resolve, reject) => {
            executionPromises.push(new Promise(resolve => { promiseResolvers[messageIdCounter()] = resolve; }));
            worker.postMessage({ type: EXEC, data: { args: command, timeout: timeout } }, []);
        });
    }

    // Terminate the FFmpeg instance
    function terminate() {
        if (worker) {
            worker.terminate();
            worker = null;
            loaded = false;
        }
    }

    // Write data to a file
    function writeFile(file, data, { signal } = {}) {
        if (!loaded) {
            throw errorFFmpegNotLoaded;
        }
        return new Promise((resolve, reject) => {
            worker.postMessage({ type: WRITE_FILE, data: { path: file, data: data } }, [data.buffer]);
            promiseResolvers[messageIdCounter()] = resolve;
        });
    }

    // Mount a file system
    function mount(fsType, options, mountPoint) {
        if (!loaded) {
            throw errorFFmpegNotLoaded;
        }
        return new Promise(resolve => {
            worker.postMessage({ type: MOUNT, data: { fsType: fsType, options: options, mountPoint: mountPoint } }, []);
            fileSystem[mountPoint] = fsType;
            resolve(fileSystem);
        });
    }

    // Unmount a file system
    function unmount(mountPoint) {
        if (!loaded) {
            throw errorFFmpegNotLoaded;
        }
        return new Promise(resolve => {
            worker.postMessage({ type: UNMOUNT, data: { mountPoint: mountPoint } }, []);
            delete fileSystem[mountPoint];
            resolve();
        });
    }

    // Download a file
    function download(file, { signal } = {}) {
        if (!loaded) {
            throw errorFFmpegNotLoaded;
        }
        return new Promise(resolve => {
            worker.postMessage({ type: DOWNLOAD, data: { file: file } }, []);
            promiseResolvers[messageIdCounter()] = resolve;
        });
    }

    // Clean up
    function cleanUp() {
        worker = null;
        fileSystem = {};
        promiseResolvers = {};
    }

    // Initialize
    let worker;
    let loaded = false;
    let eventListeners = {};
    let promiseResolvers = {};
    let fileSystemPromises = [];
    let executionPromises = [];

    // Initialize the worker
    initWorker();

    return {
        on: on,
        off: off,
        load: load,
        exec: exec,
        terminate: terminate,
        writeFile: writeFile,
        mount: mount,
        unmount: unmount,
        download: download,
    };
});

})(this);

})(this);
Edit
Pub: 22 Jan 2024 08:36 UTC
Edit: 22 Jan 2024 08:39 UTC
Views: 41