capacitor-native-video-compressor 1.1.3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -57
- package/android/build.gradle +5 -0
- package/android/src/main/AndroidManifest.xml +8 -14
- package/android/src/main/java/com/atomic/videocompressor/NativeVideoCompressorPlugin.java +217 -116
- package/android/src/main/java/com/atomic/videocompressor/VideoCompressionWorker.java +120 -0
- package/dist/docs.json +15 -38
- package/dist/esm/definitions.d.ts +30 -25
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/web.d.ts +3 -5
- package/dist/esm/web.js +6 -7
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +6 -7
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +6 -7
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/NativeVideoCompressorPlugin/NativeVideoCompressorPlugin.swift +0 -8
- package/package.json +1 -1
- package/android/src/main/java/com/atomic/videocompressor/VideoCompressionService.java +0 -328
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sources":["esm/definitions.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * `code` on the error `compressVideo` rejects with when `cancel()` stopped it.\n * Callers should treat it as \"the user asked for this\" — no error toast, no\n * retry prompt — and tell it apart from a genuine compression failure.\n */\nexport const CANCELLED = 'CANCELLED';\n//# sourceMappingURL=definitions.js.map","import { registerPlugin } from '@capacitor/core';\nconst NativeVideoCompressor = registerPlugin('NativeVideoCompressor', {\n web: () => import('./web').then((m) => new m.NativeVideoCompressorWeb()),\n});\nexport * from './definitions';\nexport { NativeVideoCompressor };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nimport { FFmpeg } from '@ffmpeg/ffmpeg';\nimport { toBlobURL } from '@ffmpeg/util';\nimport { ALL_FORMATS, BlobSource, BufferTarget, Conversion, ConversionCanceledError, Input, Mp4OutputFormat, Output, Quality, canEncodeVideo, } from 'mediabunny';\nimport { CANCELLED } from './definitions';\n/**\n * Rejection shape for a cancelled compress. `code` matches what `call.reject`\n * puts on the error object on iOS/Android, so one `error.code === 'CANCELLED'`\n * check works on every platform — and on both web engines below.\n */\nclass CancelledError extends Error {\n constructor() {\n super('Đã hủy nén');\n this.code = CANCELLED;\n this.name = 'CancelledError';\n }\n}\n/**\n * WebCodecs target per quality tier: cap height + a bitrate ceiling. The\n * quantizer (constant 26, CRF-like) drives quality where the encoder honours\n * it; H.264 on most browsers is bitrate-driven, so `bitrate` is the real knob.\n * fps is capped to 30 at call time (never upsampled). Audio is left to\n * mediabunny, which re-encodes to AAC for the MP4 container.\n */\nconst WEBCODECS_LADDER = {\n VERY_HIGH: { height: 1080, bitrate: 4000000 },\n HIGH: { height: 720, bitrate: 2000000 },\n MEDIUM: { height: 540, bitrate: 1200000 },\n LOW: { height: 480, bitrate: 1000000 },\n '360P': { height: 360, bitrate: 700000 },\n VERY_LOW: { height: 240, bitrate: 350000 },\n};\nconst WEBCODECS_QUANTIZER = 26;\nconst FPS_CAP = 30;\nconst CORE_BASE_URL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm';\n/**\n * Cancelling means terminating the worker, which drops the loaded core with\n * it — so without this the next compress re-downloads ~30 MB of wasm and\n * \"cancel\" quietly costs more than it saves. Module scope, not instance: the\n * bytes are identical for every instance and every job. Only the ffmpeg\n * fallback ever pays this download; the WebCodecs primary path needs no core.\n */\nlet corePromise = null;\nconst loadCoreURLs = () => {\n if (!corePromise) {\n corePromise = Promise.all([\n toBlobURL(`${CORE_BASE_URL}/ffmpeg-core.js`, 'text/javascript'),\n toBlobURL(`${CORE_BASE_URL}/ffmpeg-core.wasm`, 'application/wasm'),\n ])\n .then(([coreURL, wasmURL]) => ({ coreURL, wasmURL }))\n .catch((e) => {\n // Don't cache a failure — a flaky network shouldn't make every later\n // compress in this session fail too.\n corePromise = null;\n throw e;\n });\n }\n return corePromise;\n};\nexport class NativeVideoCompressorWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.ffmpeg = null;\n this.isLoaded = false;\n /** The mediabunny conversion running now, so `cancel()` can abort it. */\n this.activeConversion = null;\n /** The job `compressVideo` is running right now, for `cancel({ jobId })`. */\n this.currentJobId = null;\n this.cancelRequested = false;\n }\n async initialize() {\n // WebCodecs (the primary path) needs no core download, so there is nothing\n // to warm. Eagerly loading the ffmpeg core here would pull ~30 MB for a\n // path most compresses never take. The fallback lazy-loads its core on\n // first use. Kept as a resolving no-op so callers that await it still pass.\n return { success: true, message: 'ready' };\n }\n async compressVideo(options) {\n var _a, _b;\n this.currentJobId = (_a = options.jobId) !== null && _a !== void 0 ? _a : 'default';\n this.cancelRequested = false;\n // Checked at every stage boundary, not just around the encode: cancelling\n // an engine only reaches work already handed to it, so a cancel during the\n // source fetch or before init has nothing to interrupt and would otherwise\n // let the compress carry on as if nothing had happened.\n const throwIfCancelled = () => {\n if (this.cancelRequested)\n throw new CancelledError();\n };\n try {\n throwIfCancelled();\n const blob = await this.fetchSourceBlob(options.sourcePath);\n throwIfCancelled();\n const quality = (_b = options.quality) !== null && _b !== void 0 ? _b : 'MEDIUM';\n if (await this.canUseWebCodecs(quality)) {\n try {\n const result = await this.compressWithWebCodecs(blob, quality, throwIfCancelled);\n if (result)\n return result;\n // null → conversion invalid / tracks discarded → fall back to ffmpeg.\n }\n catch (e) {\n if ((e === null || e === void 0 ? void 0 : e.code) === CANCELLED)\n throw e; // user cancel: never fall back\n console.warn('[compress] WebCodecs failed, falling back to ffmpeg:', e);\n throwIfCancelled();\n }\n }\n return await this.compressWithFfmpeg(blob, quality, throwIfCancelled);\n }\n catch (error) {\n if ((error === null || error === void 0 ? void 0 : error.code) === CANCELLED) {\n console.log('[compress] cancelled');\n }\n else {\n console.error('[compress] failed:', error);\n }\n throw error;\n }\n finally {\n this.currentJobId = null;\n this.cancelRequested = false;\n this.activeConversion = null;\n }\n }\n /**\n * Kill whichever engine is mid-compress. Only one is ever active at a time,\n * so acting on both is safe.\n *\n * WebCodecs: `conversion.cancel()` makes the in-flight `execute()` reject\n * with `ConversionCanceledError`, surfaced as a `CancelledError` below.\n * ffmpeg: `exec()` runs synchronously inside the worker and never reaches a\n * message poll while encoding, so `worker.terminate()` is the only way to\n * stop it — its cost is the loaded core, which is why the core URLs are\n * cached above.\n */\n /**\n * Chỉ Android mới có foreground service để mà hạ xuống. Hiện diện ở đây để\n * caller gọi thẳng, không phải rẽ nhánh theo platform ở mọi call site.\n */\n async finishUpload() {\n return;\n }\n async cancel(options) {\n var _a;\n if (!this.currentJobId)\n return { cancelled: false };\n if ((options === null || options === void 0 ? void 0 : options.jobId) && options.jobId !== this.currentJobId)\n return { cancelled: false };\n // Set even when neither engine exists yet: the job may still be fetching\n // the source or inside loadFFmpeg, which read this flag at their boundaries.\n this.cancelRequested = true;\n const conversion = this.activeConversion;\n this.activeConversion = null;\n // Fire-and-forget: the CancelledError surfaces from the execute() rejection,\n // not from here; awaiting would only make cancel() slower.\n conversion === null || conversion === void 0 ? void 0 : conversion.cancel().catch(() => undefined);\n (_a = this.ffmpeg) === null || _a === void 0 ? void 0 : _a.terminate();\n this.ffmpeg = null;\n this.isLoaded = false;\n return { cancelled: true };\n }\n async fetchSourceBlob(sourcePath) {\n try {\n const response = await fetch(sourcePath);\n return await response.blob();\n }\n catch (err) {\n console.error('[compress] Error fetching source file:', err);\n throw new Error('Could not fetch source video file');\n }\n }\n async canUseWebCodecs(quality) {\n try {\n const { bitrate } = WEBCODECS_LADDER[quality];\n return await canEncodeVideo('avc', {\n quality: new Quality({ quantizer: WEBCODECS_QUANTIZER, bitrate }),\n });\n }\n catch (_a) {\n return false;\n }\n }\n async compressWithWebCodecs(blob, quality, throwIfCancelled) {\n const { height, bitrate } = WEBCODECS_LADDER[quality];\n const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(blob) });\n const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });\n // Cap fps at 30, but never upsample: probe the source and take the min.\n // A failed probe just omits frameRate, leaving the source rate untouched.\n let frameRate;\n try {\n const track = await input.getPrimaryVideoTrack();\n if (track) {\n const stats = await track.computePacketStats(100);\n if (stats.averagePacketRate > 0) {\n frameRate = Math.min(FPS_CAP, Math.round(stats.averagePacketRate));\n }\n }\n }\n catch (_a) {\n frameRate = undefined;\n }\n throwIfCancelled();\n const conversion = await Conversion.init({\n input,\n output,\n video: Object.assign({ height, quality: new Quality({ quantizer: WEBCODECS_QUANTIZER, bitrate }), hardwareAcceleration: 'prefer-hardware' }, (frameRate ? { frameRate } : {})),\n });\n if (!conversion.isValid) {\n console.warn('[compress] WebCodecs conversion invalid:', conversion.discardedTracks.map((t) => t.reason));\n return null;\n }\n this.activeConversion = conversion;\n this.notifyListeners('onProgress', { status: 'started', percent: 0 });\n conversion.onProgress = (progress) => {\n this.notifyListeners('onProgress', { status: 'progress', percent: Math.round(progress * 100) });\n };\n throwIfCancelled();\n try {\n await conversion.execute();\n }\n catch (e) {\n if (this.cancelRequested || e instanceof ConversionCanceledError)\n throw new CancelledError();\n throw e;\n }\n const buffer = output.target.buffer;\n if (!buffer)\n throw new Error('WebCodecs produced no output');\n const outBlob = new Blob([buffer], { type: 'video/mp4' });\n return { success: true, destPath: URL.createObjectURL(outBlob) };\n }\n async loadFFmpeg() {\n if (this.isLoaded && this.ffmpeg)\n return;\n this.notifyListeners('onProgress', { status: 'loading_core', percent: 0 });\n // Built on a local, published to the field only once it is ready and still\n // wanted. Assigning `this.ffmpeg` up front and setting `isLoaded` after the\n // await left a window where a cancel could null the instance and the load,\n // finishing a moment later, would set `isLoaded = true` on nothing at all —\n // after which every compressVideo threw 'FFmpeg failed to load' for the\n // rest of the page's life.\n const instance = new FFmpeg();\n instance.on('progress', ({ progress }) => {\n this.notifyListeners('onProgress', { status: 'progress', percent: Math.round(progress * 100) });\n });\n instance.on('log', ({ message }) => {\n console.log('[FFmpeg Log]', message);\n });\n try {\n await instance.load(await loadCoreURLs());\n }\n catch (e) {\n instance.terminate();\n console.error('Failed to load FFmpeg:', e);\n throw e;\n }\n // Cancelled while this was loading. Terminate what we just built rather\n // than publish it — the caller asked for none of it.\n if (this.cancelRequested) {\n instance.terminate();\n throw new CancelledError();\n }\n this.ffmpeg = instance;\n this.isLoaded = true;\n }\n async compressWithFfmpeg(blob, quality, throwIfCancelled) {\n if (!this.isLoaded) {\n await this.loadFFmpeg();\n }\n throwIfCancelled();\n if (!this.ffmpeg) {\n throw new Error('FFmpeg failed to load');\n }\n // Bound once. `this.ffmpeg` is nulled by cancel(), so reading it after any\n // of the awaits below can hand back null on a reference the compiler\n // narrowed here — surfacing a cancel as a TypeError, not a CancelledError.\n const ffmpeg = this.ffmpeg;\n this.notifyListeners('onProgress', { status: 'started', percent: 0 });\n const inputFileName = 'input.mp4';\n const outputFileName = 'output.mp4';\n let crf = '28';\n let scale = '';\n let audioBitrate = '128k';\n switch (quality) {\n case 'VERY_HIGH':\n crf = '23';\n scale = '-vf scale=-2:1080';\n audioBitrate = '128k';\n break;\n case 'HIGH':\n crf = '28';\n scale = '-vf scale=-2:720';\n audioBitrate = '128k';\n break;\n case 'MEDIUM':\n crf = '30';\n scale = '-vf scale=-2:540';\n audioBitrate = '96k';\n break;\n case 'LOW':\n crf = '32';\n scale = '-vf scale=-2:480';\n audioBitrate = '96k';\n break;\n case '360P':\n crf = '28';\n scale = '-vf scale=-2:360';\n audioBitrate = '64k';\n break;\n case 'VERY_LOW':\n crf = '35';\n scale = '-vf scale=-2:240';\n audioBitrate = '48k';\n break;\n }\n const inputData = new Uint8Array(await blob.arrayBuffer());\n try {\n await ffmpeg.writeFile(inputFileName, inputData);\n }\n catch (err) {\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error writing to FS:', err);\n throw new Error('Could not write to FFmpeg FS');\n }\n throwIfCancelled();\n const args = ['-i', inputFileName];\n args.push('-c:v', 'libx264', '-preset', 'superfast', '-crf', crf);\n if (scale) {\n args.push(...scale.split(' '));\n }\n args.push('-c:a', 'aac', '-b:a', audioBitrate);\n args.push(outputFileName);\n try {\n await ffmpeg.exec(args);\n }\n catch (err) {\n // terminate() rejects every in-flight call, so a cancel arrives here\n // looking like a generic failure unless we name it.\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error executing command:', err);\n throw new Error('FFmpeg execution failed');\n }\n throwIfCancelled();\n let data;\n try {\n data = await ffmpeg.readFile(outputFileName);\n }\n catch (err) {\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error reading output file:', err);\n throw new Error('Could not read FFmpeg output');\n }\n await ffmpeg.deleteFile(inputFileName);\n await ffmpeg.deleteFile(outputFileName);\n const outBlob = new Blob([data], { type: 'video/mp4' });\n return { success: true, destPath: URL.createObjectURL(outBlob) };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","toBlobURL","WebPlugin","canEncodeVideo","Quality","Input","ALL_FORMATS","BlobSource","Output","Mp4OutputFormat","BufferTarget","Conversion","ConversionCanceledError","FFmpeg"],"mappings":";;;IAAA;IACA;IACA;IACA;IACA;AACY,UAAC,SAAS,GAAG;;ACJpB,UAAC,qBAAqB,GAAGA,mBAAc,CAAC,uBAAuB,EAAE;IACtE,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,wBAAwB,EAAE,CAAC;IAC5E,CAAC;;ICED;IACA;IACA;IACA;IACA;IACA,MAAM,cAAc,SAAS,KAAK,CAAC;IACnC,IAAI,WAAW,GAAG;IAClB,QAAQ,KAAK,CAAC,YAAY,CAAC;IAC3B,QAAQ,IAAI,CAAC,IAAI,GAAG,SAAS;IAC7B,QAAQ,IAAI,CAAC,IAAI,GAAG,gBAAgB;IACpC,IAAI;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAM,gBAAgB,GAAG;IACzB,IAAI,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,O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ACR,QAAQ,MAAM,MAAM,CAAC,UAAU,CAAC,aAAa,CAAC;IAC9C,QAAQ,MAAM,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC;IAC/C,QAAQ,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAC/D,QAAQ,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE;IACxE,IAAI;IACJ;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"plugin.js","sources":["esm/definitions.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * `code` on the error `compressVideo` rejects with when `cancel()` stopped it.\n * Callers should treat it as \"the user asked for this\" — no error toast, no\n * retry prompt — and tell it apart from a genuine compression failure.\n */\nexport const CANCELLED = 'CANCELLED';\n//# sourceMappingURL=definitions.js.map","import { registerPlugin } from '@capacitor/core';\nconst NativeVideoCompressor = registerPlugin('NativeVideoCompressor', {\n web: () => import('./web').then((m) => new m.NativeVideoCompressorWeb()),\n});\nexport * from './definitions';\nexport { NativeVideoCompressor };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nimport { FFmpeg } from '@ffmpeg/ffmpeg';\nimport { toBlobURL } from '@ffmpeg/util';\nimport { ALL_FORMATS, BlobSource, BufferTarget, Conversion, ConversionCanceledError, Input, Mp4OutputFormat, Output, Quality, canEncodeVideo, } from 'mediabunny';\nimport { CANCELLED } from './definitions';\n/**\n * Rejection shape for a cancelled compress. `code` matches what `call.reject`\n * puts on the error object on iOS/Android, so one `error.code === 'CANCELLED'`\n * check works on every platform — and on both web engines below.\n */\nclass CancelledError extends Error {\n constructor() {\n super('Đã hủy nén');\n this.code = CANCELLED;\n this.name = 'CancelledError';\n }\n}\n/**\n * WebCodecs target per quality tier: cap height + a bitrate ceiling. The\n * quantizer (constant 26, CRF-like) drives quality where the encoder honours\n * it; H.264 on most browsers is bitrate-driven, so `bitrate` is the real knob.\n * fps is capped to 30 at call time (never upsampled). Audio is left to\n * mediabunny, which re-encodes to AAC for the MP4 container.\n */\nconst WEBCODECS_LADDER = {\n VERY_HIGH: { height: 1080, bitrate: 4000000 },\n HIGH: { height: 720, bitrate: 2000000 },\n MEDIUM: { height: 540, bitrate: 1200000 },\n LOW: { height: 480, bitrate: 1000000 },\n '360P': { height: 360, bitrate: 700000 },\n VERY_LOW: { height: 240, bitrate: 350000 },\n};\nconst WEBCODECS_QUANTIZER = 26;\nconst FPS_CAP = 30;\nconst CORE_BASE_URL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm';\n/**\n * Cancelling means terminating the worker, which drops the loaded core with\n * it — so without this the next compress re-downloads ~30 MB of wasm and\n * \"cancel\" quietly costs more than it saves. Module scope, not instance: the\n * bytes are identical for every instance and every job. Only the ffmpeg\n * fallback ever pays this download; the WebCodecs primary path needs no core.\n */\nlet corePromise = null;\nconst loadCoreURLs = () => {\n if (!corePromise) {\n corePromise = Promise.all([\n toBlobURL(`${CORE_BASE_URL}/ffmpeg-core.js`, 'text/javascript'),\n toBlobURL(`${CORE_BASE_URL}/ffmpeg-core.wasm`, 'application/wasm'),\n ])\n .then(([coreURL, wasmURL]) => ({ coreURL, wasmURL }))\n .catch((e) => {\n // Don't cache a failure — a flaky network shouldn't make every later\n // compress in this session fail too.\n corePromise = null;\n throw e;\n });\n }\n return corePromise;\n};\nexport class NativeVideoCompressorWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.ffmpeg = null;\n this.isLoaded = false;\n /** The mediabunny conversion running now, so `cancel()` can abort it. */\n this.activeConversion = null;\n /** The job `compressVideo` is running right now, for `cancel({ jobId })`. */\n this.currentJobId = null;\n this.cancelRequested = false;\n }\n async initialize() {\n // WebCodecs (the primary path) needs no core download, so there is nothing\n // to warm. Eagerly loading the ffmpeg core here would pull ~30 MB for a\n // path most compresses never take. The fallback lazy-loads its core on\n // first use. Kept as a resolving no-op so callers that await it still pass.\n return { success: true, message: 'ready' };\n }\n async finishUpload() {\n // Nothing holds a process alive on the web — the tab either lives or the\n // whole compress is gone with it. Resolving no-op so the one call site\n // can fire unconditionally instead of branching on platform.\n return { released: false };\n }\n async compressVideo(options) {\n var _a, _b;\n this.currentJobId = (_a = options.jobId) !== null && _a !== void 0 ? _a : 'default';\n this.cancelRequested = false;\n // Checked at every stage boundary, not just around the encode: cancelling\n // an engine only reaches work already handed to it, so a cancel during the\n // source fetch or before init has nothing to interrupt and would otherwise\n // let the compress carry on as if nothing had happened.\n const throwIfCancelled = () => {\n if (this.cancelRequested)\n throw new CancelledError();\n };\n try {\n throwIfCancelled();\n const blob = await this.fetchSourceBlob(options.sourcePath);\n throwIfCancelled();\n const quality = (_b = options.quality) !== null && _b !== void 0 ? _b : 'MEDIUM';\n if (await this.canUseWebCodecs(quality)) {\n try {\n const result = await this.compressWithWebCodecs(blob, quality, throwIfCancelled);\n if (result)\n return result;\n // null → conversion invalid / tracks discarded → fall back to ffmpeg.\n }\n catch (e) {\n if ((e === null || e === void 0 ? void 0 : e.code) === CANCELLED)\n throw e; // user cancel: never fall back\n console.warn('[compress] WebCodecs failed, falling back to ffmpeg:', e);\n throwIfCancelled();\n }\n }\n return await this.compressWithFfmpeg(blob, quality, throwIfCancelled);\n }\n catch (error) {\n if ((error === null || error === void 0 ? void 0 : error.code) === CANCELLED) {\n console.log('[compress] cancelled');\n }\n else {\n console.error('[compress] failed:', error);\n }\n throw error;\n }\n finally {\n this.currentJobId = null;\n this.cancelRequested = false;\n this.activeConversion = null;\n }\n }\n /**\n * Kill whichever engine is mid-compress. Only one is ever active at a time,\n * so acting on both is safe.\n *\n * WebCodecs: `conversion.cancel()` makes the in-flight `execute()` reject\n * with `ConversionCanceledError`, surfaced as a `CancelledError` below.\n * ffmpeg: `exec()` runs synchronously inside the worker and never reaches a\n * message poll while encoding, so `worker.terminate()` is the only way to\n * stop it — its cost is the loaded core, which is why the core URLs are\n * cached above.\n */\n async cancel(options) {\n var _a;\n if (!this.currentJobId)\n return { cancelled: false };\n if ((options === null || options === void 0 ? void 0 : options.jobId) && options.jobId !== this.currentJobId)\n return { cancelled: false };\n // Set even when neither engine exists yet: the job may still be fetching\n // the source or inside loadFFmpeg, which read this flag at their boundaries.\n this.cancelRequested = true;\n const conversion = this.activeConversion;\n this.activeConversion = null;\n // Fire-and-forget: the CancelledError surfaces from the execute() rejection,\n // not from here; awaiting would only make cancel() slower.\n conversion === null || conversion === void 0 ? void 0 : conversion.cancel().catch(() => undefined);\n (_a = this.ffmpeg) === null || _a === void 0 ? void 0 : _a.terminate();\n this.ffmpeg = null;\n this.isLoaded = false;\n return { cancelled: true };\n }\n async fetchSourceBlob(sourcePath) {\n try {\n const response = await fetch(sourcePath);\n return await response.blob();\n }\n catch (err) {\n console.error('[compress] Error fetching source file:', err);\n throw new Error('Could not fetch source video file');\n }\n }\n async canUseWebCodecs(quality) {\n try {\n const { bitrate } = WEBCODECS_LADDER[quality];\n return await canEncodeVideo('avc', {\n quality: new Quality({ quantizer: WEBCODECS_QUANTIZER, bitrate }),\n });\n }\n catch (_a) {\n return false;\n }\n }\n async compressWithWebCodecs(blob, quality, throwIfCancelled) {\n const { height, bitrate } = WEBCODECS_LADDER[quality];\n const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(blob) });\n const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });\n // Cap fps at 30, but never upsample: probe the source and take the min.\n // A failed probe just omits frameRate, leaving the source rate untouched.\n let frameRate;\n try {\n const track = await input.getPrimaryVideoTrack();\n if (track) {\n const stats = await track.computePacketStats(100);\n if (stats.averagePacketRate > 0) {\n frameRate = Math.min(FPS_CAP, Math.round(stats.averagePacketRate));\n }\n }\n }\n catch (_a) {\n frameRate = undefined;\n }\n throwIfCancelled();\n const conversion = await Conversion.init({\n input,\n output,\n video: Object.assign({ height, quality: new Quality({ quantizer: WEBCODECS_QUANTIZER, bitrate }), hardwareAcceleration: 'prefer-hardware' }, (frameRate ? { frameRate } : {})),\n });\n if (!conversion.isValid) {\n console.warn('[compress] WebCodecs conversion invalid:', conversion.discardedTracks.map((t) => t.reason));\n return null;\n }\n this.activeConversion = conversion;\n this.notifyListeners('onProgress', { status: 'started', percent: 0 });\n conversion.onProgress = (progress) => {\n this.notifyListeners('onProgress', { status: 'progress', percent: Math.round(progress * 100) });\n };\n throwIfCancelled();\n try {\n await conversion.execute();\n }\n catch (e) {\n if (this.cancelRequested || e instanceof ConversionCanceledError)\n throw new CancelledError();\n throw e;\n }\n const buffer = output.target.buffer;\n if (!buffer)\n throw new Error('WebCodecs produced no output');\n const outBlob = new Blob([buffer], { type: 'video/mp4' });\n return { success: true, destPath: URL.createObjectURL(outBlob) };\n }\n async loadFFmpeg() {\n if (this.isLoaded && this.ffmpeg)\n return;\n this.notifyListeners('onProgress', { status: 'loading_core', percent: 0 });\n // Built on a local, published to the field only once it is ready and still\n // wanted. Assigning `this.ffmpeg` up front and setting `isLoaded` after the\n // await left a window where a cancel could null the instance and the load,\n // finishing a moment later, would set `isLoaded = true` on nothing at all —\n // after which every compressVideo threw 'FFmpeg failed to load' for the\n // rest of the page's life.\n const instance = new FFmpeg();\n instance.on('progress', ({ progress }) => {\n this.notifyListeners('onProgress', { status: 'progress', percent: Math.round(progress * 100) });\n });\n instance.on('log', ({ message }) => {\n console.log('[FFmpeg Log]', message);\n });\n try {\n await instance.load(await loadCoreURLs());\n }\n catch (e) {\n instance.terminate();\n console.error('Failed to load FFmpeg:', e);\n throw e;\n }\n // Cancelled while this was loading. Terminate what we just built rather\n // than publish it — the caller asked for none of it.\n if (this.cancelRequested) {\n instance.terminate();\n throw new CancelledError();\n }\n this.ffmpeg = instance;\n this.isLoaded = true;\n }\n async compressWithFfmpeg(blob, quality, throwIfCancelled) {\n if (!this.isLoaded) {\n await this.loadFFmpeg();\n }\n throwIfCancelled();\n if (!this.ffmpeg) {\n throw new Error('FFmpeg failed to load');\n }\n // Bound once. `this.ffmpeg` is nulled by cancel(), so reading it after any\n // of the awaits below can hand back null on a reference the compiler\n // narrowed here — surfacing a cancel as a TypeError, not a CancelledError.\n const ffmpeg = this.ffmpeg;\n this.notifyListeners('onProgress', { status: 'started', percent: 0 });\n const inputFileName = 'input.mp4';\n const outputFileName = 'output.mp4';\n let crf = '28';\n let scale = '';\n let audioBitrate = '128k';\n switch (quality) {\n case 'VERY_HIGH':\n crf = '23';\n scale = '-vf scale=-2:1080';\n audioBitrate = '128k';\n break;\n case 'HIGH':\n crf = '28';\n scale = '-vf scale=-2:720';\n audioBitrate = '128k';\n break;\n case 'MEDIUM':\n crf = '30';\n scale = '-vf scale=-2:540';\n audioBitrate = '96k';\n break;\n case 'LOW':\n crf = '32';\n scale = '-vf scale=-2:480';\n audioBitrate = '96k';\n break;\n case '360P':\n crf = '28';\n scale = '-vf scale=-2:360';\n audioBitrate = '64k';\n break;\n case 'VERY_LOW':\n crf = '35';\n scale = '-vf scale=-2:240';\n audioBitrate = '48k';\n break;\n }\n const inputData = new Uint8Array(await blob.arrayBuffer());\n try {\n await ffmpeg.writeFile(inputFileName, inputData);\n }\n catch (err) {\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error writing to FS:', err);\n throw new Error('Could not write to FFmpeg FS');\n }\n throwIfCancelled();\n const args = ['-i', inputFileName];\n args.push('-c:v', 'libx264', '-preset', 'superfast', '-crf', crf);\n if (scale) {\n args.push(...scale.split(' '));\n }\n args.push('-c:a', 'aac', '-b:a', audioBitrate);\n args.push(outputFileName);\n try {\n await ffmpeg.exec(args);\n }\n catch (err) {\n // terminate() rejects every in-flight call, so a cancel arrives here\n // looking like a generic failure unless we name it.\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error executing command:', err);\n throw new Error('FFmpeg execution failed');\n }\n throwIfCancelled();\n let data;\n try {\n data = await ffmpeg.readFile(outputFileName);\n }\n catch (err) {\n if (this.cancelRequested)\n throw new CancelledError();\n console.error('[FFmpeg] Error reading output file:', err);\n throw new Error('Could not read FFmpeg output');\n }\n await ffmpeg.deleteFile(inputFileName);\n await ffmpeg.deleteFile(outputFileName);\n const outBlob = new Blob([data], { type: 'video/mp4' });\n return { success: true, destPath: URL.createObjectURL(outBlob) };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","toBlobURL","WebPlugin","canEncodeVideo","Quality","Input","ALL_FORMATS","BlobSource","Output","Mp4OutputFormat","BufferTarget","Conversion","ConversionCanceledError","FFmpeg"],"mappings":";;;IAAA;IACA;IACA;IACA;IACA;AACY,UAAC,SAAS,GAAG;;ACJpB,UAAC,qBAAqB,GAAGA,mBAAc,CAAC,uBAAuB,EAAE;IACtE,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,wBAAwB,EAAE,CAAC;IAC5E,CAAC;;ICED;IACA;IACA;IACA;IACA;IACA,MAAM,cAAc,SAAS,KAAK,CAAC;IACnC,IAAI,WAAW,GAAG;IAClB,QAAQ,KAAK,CAAC,YAAY,CAAC;IAC3B,QAAQ,IAAI,CAAC,IAAI,GAAG,SAAS;IAC7B,QAAQ,IAAI,CAAC,IAAI,GAAG,gBAAgB;IACpC,IAAI;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAM,gBAAgB,GAAG;IACzB,IAAI,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE;IACjD,IAAI,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;IAC3C,IAAI,MAAM,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;IAC7C,IAAI,GAAG,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;IAC1C,IAAI,MAAM,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE;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C,eAAe,CAAC,OAAO,CAAC,EAAE;IACxE,IAAI;IACJ;;;;;;;;;;;;;;;;"}
|
|
@@ -16,7 +16,6 @@ public class NativeVideoCompressorPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
16
16
|
CAPPluginMethod(name: "compressVideo", returnType: CAPPluginReturnPromise),
|
|
17
17
|
CAPPluginMethod(name: "cancel", returnType: CAPPluginReturnPromise),
|
|
18
18
|
CAPPluginMethod(name: "initialize", returnType: CAPPluginReturnPromise),
|
|
19
|
-
CAPPluginMethod(name: "finishUpload", returnType: CAPPluginReturnPromise)
|
|
20
19
|
]
|
|
21
20
|
|
|
22
21
|
/// The job `compressVideo` is running right now, for `cancel(jobId:)`.
|
|
@@ -42,13 +41,6 @@ public class NativeVideoCompressorPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
42
41
|
* down the `else` branch — `markAsFinished()`, `group.leave()` — and the
|
|
43
42
|
* existing completion handler runs. No new exit path, no polling.
|
|
44
43
|
*/
|
|
45
|
-
/// Chỉ Android mới có foreground service để hạ xuống. Khai ở đây để caller
|
|
46
|
-
/// gọi thẳng mà không phải rẽ nhánh theo platform ở mọi call site - thiếu
|
|
47
|
-
/// nó thì mỗi lần gọi trên iOS là một promise bị reject "not implemented".
|
|
48
|
-
@objc func finishUpload(_ call: CAPPluginCall) {
|
|
49
|
-
call.resolve()
|
|
50
|
-
}
|
|
51
|
-
|
|
52
44
|
@objc func cancel(_ call: CAPPluginCall) {
|
|
53
45
|
stateLock.lock()
|
|
54
46
|
let running = currentJobId
|
package/package.json
CHANGED
|
@@ -1,328 +0,0 @@
|
|
|
1
|
-
package com.atomic.videocompressor;
|
|
2
|
-
|
|
3
|
-
import android.app.Notification;
|
|
4
|
-
import android.app.NotificationChannel;
|
|
5
|
-
import android.app.NotificationManager;
|
|
6
|
-
import android.app.PendingIntent;
|
|
7
|
-
import android.app.Service;
|
|
8
|
-
import android.content.Intent;
|
|
9
|
-
import android.content.pm.ServiceInfo;
|
|
10
|
-
import android.os.Build;
|
|
11
|
-
import android.os.Handler;
|
|
12
|
-
import android.os.IBinder;
|
|
13
|
-
import android.os.Looper;
|
|
14
|
-
import android.os.SystemClock;
|
|
15
|
-
import android.util.Log;
|
|
16
|
-
import androidx.annotation.Nullable;
|
|
17
|
-
import androidx.core.app.NotificationCompat;
|
|
18
|
-
import androidx.core.app.ServiceCompat;
|
|
19
|
-
import java.util.LinkedHashMap;
|
|
20
|
-
import java.util.Map;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Giữ tiến trình nén + upload sống khi user rời app.
|
|
24
|
-
*
|
|
25
|
-
* Mọi thứ trong đây phải đáp ứng được 5 tiêu chí foreground service của Google
|
|
26
|
-
* Play, vì bản thiếu chúng (1.1.0) đã bị từ chối ở version code 29:
|
|
27
|
-
*
|
|
28
|
-
* - user perceptible -> notification có progress thật, cập nhật theo % nén
|
|
29
|
-
* và theo pha (nén / tải lên), chứ không phải một dòng chữ tĩnh
|
|
30
|
-
* - stoppable by user -> action "Huỷ" ngay trên notification, vì khi user đã
|
|
31
|
-
* rời app thì UI trong app không còn với tới được
|
|
32
|
-
* - runs only as long as necessary -> watchdog tự tắt khi không còn ai báo
|
|
33
|
-
* tiến trình, để một lần JS chết giữa đường không để lại FGS chạy vô hạn
|
|
34
|
-
*/
|
|
35
|
-
public class VideoCompressionService extends Service {
|
|
36
|
-
|
|
37
|
-
private static final String TAG = "VideoCompressionService";
|
|
38
|
-
private static final String CHANNEL_ID = "VideoCompressionChannel";
|
|
39
|
-
private static final int NOTIFICATION_ID = 1001;
|
|
40
|
-
|
|
41
|
-
static final String ACTION_START = "com.atomic.videocompressor.START";
|
|
42
|
-
static final String ACTION_UPLOAD = "com.atomic.videocompressor.UPLOAD";
|
|
43
|
-
static final String ACTION_FINISH = "com.atomic.videocompressor.FINISH";
|
|
44
|
-
/** Do chính user bấm từ notification. */
|
|
45
|
-
static final String ACTION_CANCEL = "com.atomic.videocompressor.CANCEL";
|
|
46
|
-
|
|
47
|
-
static final String EXTRA_JOB_ID = "jobId";
|
|
48
|
-
static final String EXTRA_PERCENT = "percent";
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Không nhận được update nào trong khoảng này thì coi như phía gọi đã chết
|
|
52
|
-
* (WebView bị kill, hoặc một exception thoát ra ngoài nhánh finishUpload) và
|
|
53
|
-
* tự dừng. Không có nó, `jobs` không bao giờ rỗng và service chạy mãi với
|
|
54
|
-
* một notification treo - đúng thứ khiến Play đánh trượt tiêu chí "runs only
|
|
55
|
-
* for as long as necessary".
|
|
56
|
-
*
|
|
57
|
-
* Chọn 15 phút: dài hơn mọi khoảng lặng hợp lệ (upload một video đã nén trên
|
|
58
|
-
* mạng chậm, hoặc pha nén chưa kịp bắn progress đầu tiên), ngắn hơn nhiều so
|
|
59
|
-
* với mức mà user kịp nhận ra có gì đó treo.
|
|
60
|
-
*/
|
|
61
|
-
private static final long WATCHDOG_MS = 15 * 60 * 1000L;
|
|
62
|
-
|
|
63
|
-
/** Đừng vẽ lại notification mỗi tick progress của LightCompressor. */
|
|
64
|
-
private static final long MIN_REDRAW_INTERVAL_MS = 500L;
|
|
65
|
-
|
|
66
|
-
private enum Phase { COMPRESSING, UPLOADING }
|
|
67
|
-
|
|
68
|
-
private static final class Job {
|
|
69
|
-
Phase phase = Phase.COMPRESSING;
|
|
70
|
-
int percent = 0;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** LinkedHashMap: notification một job hiển thị đúng job đã bắt đầu trước. */
|
|
74
|
-
private final Map<String, Job> jobs = new LinkedHashMap<>();
|
|
75
|
-
|
|
76
|
-
private final Handler handler = new Handler(Looper.getMainLooper());
|
|
77
|
-
private final Runnable watchdog = this::onWatchdogFired;
|
|
78
|
-
|
|
79
|
-
private long lastRedrawUptime = 0;
|
|
80
|
-
private boolean inForeground = false;
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Instance đang sống, để plugin đẩy % vào mà không phải gửi một Intent cho
|
|
84
|
-
* mỗi tick.
|
|
85
|
-
*
|
|
86
|
-
* volatile vì được đọc từ thread nền: LightCompressor gọi onProgress thẳng
|
|
87
|
-
* từ coroutine encoder (Dispatchers.Default), không hop về main - đã kiểm
|
|
88
|
-
* bằng bytecode, onProgressChanged gọi listener trực tiếp không qua
|
|
89
|
-
* withContext. Thiếu volatile thì thread đó có thể đọc phải một tham chiếu
|
|
90
|
-
* cũ của service đã destroy.
|
|
91
|
-
*/
|
|
92
|
-
@Nullable
|
|
93
|
-
private static volatile VideoCompressionService instance = null;
|
|
94
|
-
|
|
95
|
-
@Override
|
|
96
|
-
public void onCreate() {
|
|
97
|
-
super.onCreate();
|
|
98
|
-
instance = this;
|
|
99
|
-
NotificationChannel channel = new NotificationChannel(
|
|
100
|
-
CHANNEL_ID, "Xử lý và tải video lên", NotificationManager.IMPORTANCE_LOW
|
|
101
|
-
);
|
|
102
|
-
channel.setDescription("Tiến trình nén và tải video lên");
|
|
103
|
-
NotificationManager manager = getSystemService(NotificationManager.class);
|
|
104
|
-
if (manager != null) manager.createNotificationChannel(channel);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
@Override
|
|
108
|
-
public void onDestroy() {
|
|
109
|
-
handler.removeCallbacks(watchdog);
|
|
110
|
-
if (instance == this) instance = null;
|
|
111
|
-
super.onDestroy();
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Cập nhật tiến độ nén. Gọi được từ thread bất kỳ.
|
|
116
|
-
*
|
|
117
|
-
* No-op khi service chưa/không còn sống: progress là thông tin trang trí,
|
|
118
|
-
* không đáng để dựng lại một foreground service đã tắt.
|
|
119
|
-
*/
|
|
120
|
-
static void publishProgress(String jobId, int percent) {
|
|
121
|
-
VideoCompressionService service = instance;
|
|
122
|
-
if (service == null) return;
|
|
123
|
-
// Chuyển về main thread: lời gọi tới đây nằm trên thread encoder của
|
|
124
|
-
// LightCompressor, còn jobs/handler/notification đều chỉ được chạm từ
|
|
125
|
-
// main. Không post thì LinkedHashMap bị sửa đồng thời với onStartCommand.
|
|
126
|
-
service.handler.post(() -> service.applyProgress(jobId, percent));
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
private void applyProgress(String jobId, int percent) {
|
|
130
|
-
Job job = jobs.get(jobId);
|
|
131
|
-
if (job == null) return;
|
|
132
|
-
|
|
133
|
-
int clamped = Math.max(0, Math.min(100, percent));
|
|
134
|
-
// Mỗi update đều gia hạn watchdog, kể cả khi bỏ qua việc vẽ lại:
|
|
135
|
-
// throttle chỉ để tiết kiệm vẽ, không phải dấu hiệu job đã chết.
|
|
136
|
-
armWatchdog();
|
|
137
|
-
if (job.percent == clamped) return;
|
|
138
|
-
job.percent = clamped;
|
|
139
|
-
|
|
140
|
-
long now = SystemClock.uptimeMillis();
|
|
141
|
-
if (now - lastRedrawUptime < MIN_REDRAW_INTERVAL_MS && clamped < 100) return;
|
|
142
|
-
lastRedrawUptime = now;
|
|
143
|
-
render();
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
@Override
|
|
147
|
-
public int onStartCommand(Intent intent, int flags, int startId) {
|
|
148
|
-
if (intent == null) {
|
|
149
|
-
// START_NOT_STICKY nên chỉ xảy ra khi hệ thống restart service;
|
|
150
|
-
// không có job nào để phục hồi, dừng cho sạch.
|
|
151
|
-
stopEverything();
|
|
152
|
-
return START_NOT_STICKY;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
String action = intent.getAction();
|
|
156
|
-
|
|
157
|
-
if (ACTION_CANCEL.equals(action)) {
|
|
158
|
-
// Notification là thứ duy nhất user còn thấy khi đã rời app, nên
|
|
159
|
-
// nút này huỷ tất cả: không có UI nào ở đây để chọn từng job.
|
|
160
|
-
NativeVideoCompressorPlugin.cancelAllFromNotification();
|
|
161
|
-
stopEverything();
|
|
162
|
-
return START_NOT_STICKY;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
String jobId = intent.getStringExtra(EXTRA_JOB_ID);
|
|
166
|
-
if (jobId == null) return START_NOT_STICKY;
|
|
167
|
-
|
|
168
|
-
if (ACTION_START.equals(action)) {
|
|
169
|
-
jobs.put(jobId, new Job());
|
|
170
|
-
} else if (ACTION_UPLOAD.equals(action)) {
|
|
171
|
-
Job job = jobs.get(jobId);
|
|
172
|
-
if (job != null) {
|
|
173
|
-
job.phase = Phase.UPLOADING;
|
|
174
|
-
// Pha upload không có % nào bắn về, nên thanh progress chuyển
|
|
175
|
-
// sang indeterminate thay vì đứng im ở con số của pha nén.
|
|
176
|
-
job.percent = -1;
|
|
177
|
-
}
|
|
178
|
-
} else if (ACTION_FINISH.equals(action)) {
|
|
179
|
-
jobs.remove(jobId);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
if (jobs.isEmpty()) {
|
|
183
|
-
stopEverything();
|
|
184
|
-
return START_NOT_STICKY;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
armWatchdog();
|
|
188
|
-
lastRedrawUptime = SystemClock.uptimeMillis();
|
|
189
|
-
render();
|
|
190
|
-
return START_NOT_STICKY;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* startForeground() phải được gọi trong mọi nhánh của onStartCommand đến
|
|
195
|
-
* được từ startForegroundService(), kể cả nhánh dừng ngay: nếu không,
|
|
196
|
-
* Android giết cả app bằng ForegroundServiceDidNotStartInTimeException.
|
|
197
|
-
*/
|
|
198
|
-
private void render() {
|
|
199
|
-
Job shown = jobs.values().iterator().next();
|
|
200
|
-
int running = jobs.size();
|
|
201
|
-
boolean indeterminate = shown.percent < 0;
|
|
202
|
-
|
|
203
|
-
String title;
|
|
204
|
-
if (running > 1) {
|
|
205
|
-
title = "Đang xử lý " + running + " video";
|
|
206
|
-
} else {
|
|
207
|
-
title = shown.phase == Phase.UPLOADING ? "Đang tải video lên" : "Đang nén video";
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Hai pha nói hai điều khác nhau, vì chúng chạy ở hai nơi khác nhau.
|
|
211
|
-
//
|
|
212
|
-
// Nén chạy ở native trong chính service này nên vẫn chạy khi app
|
|
213
|
-
// xuống nền. Upload thì chạy bằng JS trong webview, nên nó đứng lại
|
|
214
|
-
// và chỉ tiếp tục khi app trở lại foreground - đo được: nén xong là
|
|
215
|
-
// mọi hoạt động mạng dừng hẳn cho tới khi watchdog tự dừng service
|
|
216
|
-
// sau 15 phút. Vì vậy pha upload phải nói rõ việc người dùng cần làm.
|
|
217
|
-
String text;
|
|
218
|
-
if (shown.phase == Phase.UPLOADING) {
|
|
219
|
-
text = indeterminate
|
|
220
|
-
? "Mở lại ứng dụng để hoàn tất tải lên"
|
|
221
|
-
: shown.percent + "% - mở lại ứng dụng để hoàn tất tải lên";
|
|
222
|
-
} else {
|
|
223
|
-
text = indeterminate
|
|
224
|
-
? "Đang nén video"
|
|
225
|
-
: shown.percent + "% - đang nén";
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
|
|
229
|
-
.setContentTitle(title)
|
|
230
|
-
.setContentText(text)
|
|
231
|
-
.setSmallIcon(resolveSmallIcon())
|
|
232
|
-
.setProgress(100, indeterminate ? 0 : shown.percent, indeterminate)
|
|
233
|
-
.setOngoing(true)
|
|
234
|
-
// Không có nó, mỗi lần vẽ lại progress là một lần notification
|
|
235
|
-
// nhảy lên đầu danh sách và rung máy.
|
|
236
|
-
.setOnlyAlertOnce(true)
|
|
237
|
-
.setPriority(NotificationCompat.PRIORITY_LOW)
|
|
238
|
-
.setContentIntent(buildOpenAppIntent())
|
|
239
|
-
.addAction(0, "Huỷ", buildCancelIntent())
|
|
240
|
-
.build();
|
|
241
|
-
|
|
242
|
-
try {
|
|
243
|
-
ServiceCompat.startForeground(
|
|
244
|
-
this, NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
|
|
245
|
-
);
|
|
246
|
-
inForeground = true;
|
|
247
|
-
} catch (Exception e) {
|
|
248
|
-
// Nuốt để không giết app, nhưng log: service chạy nền âm thầm thì
|
|
249
|
-
// nén vẫn bị huỷ ngay khi user rời app và không ai biết tại sao.
|
|
250
|
-
Log.e(TAG, "startForeground thất bại - tiến trình có thể bị huỷ khi rời app", e);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/**
|
|
255
|
-
* Icon brand của app nếu có drawable `ic_stat_video_compress`, nếu không thì
|
|
256
|
-
* icon hệ thống. Notification mang icon hệ thống trông như của Android chứ
|
|
257
|
-
* không phải của app - trên video demo gửi Play, đó là một điểm trừ.
|
|
258
|
-
*/
|
|
259
|
-
private int resolveSmallIcon() {
|
|
260
|
-
int id = getResources().getIdentifier("ic_stat_video_compress", "drawable", getPackageName());
|
|
261
|
-
return id != 0 ? id : android.R.drawable.ic_popup_sync;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
private PendingIntent buildCancelIntent() {
|
|
265
|
-
Intent intent = new Intent(this, VideoCompressionService.class).setAction(ACTION_CANCEL);
|
|
266
|
-
return PendingIntent.getService(
|
|
267
|
-
this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
|
268
|
-
);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** Bấm vào notification thì quay lại app, chứ không phải không có gì xảy ra. */
|
|
272
|
-
@Nullable
|
|
273
|
-
private PendingIntent buildOpenAppIntent() {
|
|
274
|
-
Intent launch = getPackageManager().getLaunchIntentForPackage(getPackageName());
|
|
275
|
-
if (launch == null) return null;
|
|
276
|
-
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
|
277
|
-
return PendingIntent.getActivity(
|
|
278
|
-
this, 2, launch, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
|
279
|
-
);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
private void armWatchdog() {
|
|
283
|
-
handler.removeCallbacks(watchdog);
|
|
284
|
-
handler.postDelayed(watchdog, WATCHDOG_MS);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
private void onWatchdogFired() {
|
|
288
|
-
Log.w(TAG, "Không có tiến trình nào trong " + (WATCHDOG_MS / 60000) + " phút - tự dừng");
|
|
289
|
-
NativeVideoCompressorPlugin.cancelAllFromNotification();
|
|
290
|
-
stopEverything();
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Android 15+ giới hạn dataSync tổng 6 giờ/24 giờ rồi gọi onTimeout. Phải
|
|
295
|
-
* dừng trong vài giây, nếu không app ăn ANR. destini-web đặt minSdk 35 nên
|
|
296
|
-
* mọi thiết bị đều ở trong diện này.
|
|
297
|
-
*/
|
|
298
|
-
@Override
|
|
299
|
-
public void onTimeout(int startId, int fgsType) {
|
|
300
|
-
Log.w(TAG, "Hệ thống hết hạn foreground service (type " + fgsType + ") - dừng ngay");
|
|
301
|
-
NativeVideoCompressorPlugin.cancelAllFromNotification();
|
|
302
|
-
stopEverything();
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/** Overload của API 34, giữ lại cho thiết bị chạy Android 14. */
|
|
306
|
-
@Override
|
|
307
|
-
public void onTimeout(int startId) {
|
|
308
|
-
Log.w(TAG, "Hệ thống hết hạn foreground service - dừng ngay");
|
|
309
|
-
NativeVideoCompressorPlugin.cancelAllFromNotification();
|
|
310
|
-
stopEverything();
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
private void stopEverything() {
|
|
314
|
-
handler.removeCallbacks(watchdog);
|
|
315
|
-
jobs.clear();
|
|
316
|
-
if (inForeground) {
|
|
317
|
-
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE);
|
|
318
|
-
inForeground = false;
|
|
319
|
-
}
|
|
320
|
-
stopSelf();
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
@Nullable
|
|
324
|
-
@Override
|
|
325
|
-
public IBinder onBind(Intent intent) {
|
|
326
|
-
return null;
|
|
327
|
-
}
|
|
328
|
-
}
|