index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.toBlobURL = exports.downloadWithProgress = exports.importScript = exports.fetchFile = void 0;
  13. const errors_js_1 = require("./errors.js");
  14. const const_js_1 = require("./const.js");
  15. const readFromBlobOrFile = (blob) => new Promise((resolve, reject) => {
  16. const fileReader = new FileReader();
  17. fileReader.onload = () => {
  18. const { result } = fileReader;
  19. if (result instanceof ArrayBuffer) {
  20. resolve(new Uint8Array(result));
  21. }
  22. else {
  23. resolve(new Uint8Array());
  24. }
  25. };
  26. fileReader.onerror = (event) => {
  27. var _a, _b;
  28. reject(Error(`File could not be read! Code=${((_b = (_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.code) || -1}`));
  29. };
  30. fileReader.readAsArrayBuffer(blob);
  31. });
  32. /**
  33. * An util function to fetch data from url string, base64, URL, File or Blob format.
  34. *
  35. * Examples:
  36. * ```ts
  37. * // URL
  38. * await fetchFile("http://localhost:3000/video.mp4");
  39. * // base64
  40. * await fetchFile("data:<type>;base64,wL2dvYWwgbW9yZ...");
  41. * // URL
  42. * await fetchFile(new URL("video.mp4", import.meta.url));
  43. * // File
  44. * fileInput.addEventListener('change', (e) => {
  45. * await fetchFile(e.target.files[0]);
  46. * });
  47. * // Blob
  48. * const blob = new Blob(...);
  49. * await fetchFile(blob);
  50. * ```
  51. */
  52. const fetchFile = (file) => __awaiter(void 0, void 0, void 0, function* () {
  53. let data;
  54. if (typeof file === "string") {
  55. /* From base64 format */
  56. if (/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(file)) {
  57. data = atob(file.split(",")[1])
  58. .split("")
  59. .map((c) => c.charCodeAt(0));
  60. /* From remote server/URL */
  61. }
  62. else {
  63. data = yield (yield fetch(file)).arrayBuffer();
  64. }
  65. }
  66. else if (file instanceof URL) {
  67. data = yield (yield fetch(file)).arrayBuffer();
  68. }
  69. else if (file instanceof File || file instanceof Blob) {
  70. data = yield readFromBlobOrFile(file);
  71. }
  72. else {
  73. return new Uint8Array();
  74. }
  75. return new Uint8Array(data);
  76. });
  77. exports.fetchFile = fetchFile;
  78. /**
  79. * importScript dynamically import a script, useful when you
  80. * want to use different versions of ffmpeg.wasm based on environment.
  81. *
  82. * Example:
  83. *
  84. * ```ts
  85. * await importScript("http://localhost:3000/ffmpeg.js");
  86. * ```
  87. */
  88. const importScript = (url) => __awaiter(void 0, void 0, void 0, function* () {
  89. return new Promise((resolve) => {
  90. const script = document.createElement("script");
  91. const eventHandler = () => {
  92. script.removeEventListener("load", eventHandler);
  93. resolve();
  94. };
  95. script.src = url;
  96. script.type = "text/javascript";
  97. script.addEventListener("load", eventHandler);
  98. document.getElementsByTagName("head")[0].appendChild(script);
  99. });
  100. });
  101. exports.importScript = importScript;
  102. /**
  103. * Download content of a URL with progress.
  104. *
  105. * Progress only works when Content-Length is provided by the server.
  106. *
  107. */
  108. const downloadWithProgress = (url, cb) => __awaiter(void 0, void 0, void 0, function* () {
  109. var _a;
  110. const resp = yield fetch(url);
  111. let buf;
  112. try {
  113. // Set total to -1 to indicate that there is not Content-Type Header.
  114. const total = parseInt(resp.headers.get(const_js_1.HeaderContentLength) || "-1");
  115. const reader = (_a = resp.body) === null || _a === void 0 ? void 0 : _a.getReader();
  116. if (!reader)
  117. throw errors_js_1.ERROR_RESPONSE_BODY_READER;
  118. const chunks = [];
  119. let received = 0;
  120. for (;;) {
  121. const { done, value } = yield reader.read();
  122. const delta = value ? value.length : 0;
  123. if (done) {
  124. if (total != -1 && total !== received)
  125. throw errors_js_1.ERROR_INCOMPLETED_DOWNLOAD;
  126. cb && cb({ url, total, received, delta, done });
  127. break;
  128. }
  129. chunks.push(value);
  130. received += delta;
  131. cb && cb({ url, total, received, delta, done });
  132. }
  133. const data = new Uint8Array(received);
  134. let position = 0;
  135. for (const chunk of chunks) {
  136. data.set(chunk, position);
  137. position += chunk.length;
  138. }
  139. buf = data.buffer;
  140. }
  141. catch (e) {
  142. console.log(`failed to send download progress event: `, e);
  143. // Fetch arrayBuffer directly when it is not possible to get progress.
  144. buf = yield resp.arrayBuffer();
  145. cb &&
  146. cb({
  147. url,
  148. total: buf.byteLength,
  149. received: buf.byteLength,
  150. delta: 0,
  151. done: true,
  152. });
  153. }
  154. return buf;
  155. });
  156. exports.downloadWithProgress = downloadWithProgress;
  157. /**
  158. * toBlobURL fetches data from an URL and return a blob URL.
  159. *
  160. * Example:
  161. *
  162. * ```ts
  163. * await toBlobURL("http://localhost:3000/ffmpeg.js", "text/javascript");
  164. * ```
  165. */
  166. const toBlobURL = (url, mimeType, progress = false, cb) => __awaiter(void 0, void 0, void 0, function* () {
  167. const buf = progress
  168. ? yield (0, exports.downloadWithProgress)(url, cb)
  169. : yield (yield fetch(url)).arrayBuffer();
  170. const blob = new Blob([buf], { type: mimeType });
  171. return URL.createObjectURL(blob);
  172. });
  173. exports.toBlobURL = toBlobURL;