shiveshnavin commited on
Commit
5165bfe
·
1 Parent(s): 9fba405

Bubble chain working

Browse files
Files changed (2) hide show
  1. common-utils +1 -1
  2. utils/bubble/Bubble.js +192 -1
common-utils CHANGED
@@ -1 +1 @@
1
- Subproject commit ae3b5f2d4613da9bd6f0b30ad508cc0063a0eaf7
 
1
+ Subproject commit f14b0fb9ba0096171cc049cf6606c114c6ae3951
utils/bubble/Bubble.js CHANGED
@@ -66,12 +66,189 @@ class BubbleMaker {
66
 
67
  /**
68
  * Create an animated bubble (image or text) over a video.
 
 
69
  * @param {string} videoPath - path to base video
70
- * @param {Object} bubble - bubble config (see OriginalManuscriptModel.Bubble)
71
  * @param {string} outputPath - output video path
72
  * @param {Function} onLog - optional logger
73
  */
74
  async makeBubble(videoPath, bubble, outputPath, onLog) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  if (!fs.existsSync(videoPath)) throw new Error('video not found: ' + videoPath);
76
  const meta = await FFMpegUtils.getMediaMetadata(videoPath);
77
  const vw = meta.video.width;
@@ -468,6 +645,20 @@ export async function test() {
468
  const outPath2 = path.join(outDir, 'media_image_template_bubble.mp4');
469
  await bubbleMaker.makeBubble(baseVideo, imageSample, outPath2, console.log);
470
  console.log('Created:', outPath2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  } catch (e) {
472
  console.error('Test failed:', e);
473
  }
 
66
 
67
  /**
68
  * Create an animated bubble (image or text) over a video.
69
+ * The second argument may also be an array of bubble objects; in that case
70
+ * each entry is rendered in sequence, layering the overlays.
71
  * @param {string} videoPath - path to base video
72
+ * @param {Object|Object[]} bubble - bubble config(s) (see OriginalManuscriptModel.Bubble)
73
  * @param {string} outputPath - output video path
74
  * @param {Function} onLog - optional logger
75
  */
76
  async makeBubble(videoPath, bubble, outputPath, onLog) {
77
+ // helper that computes input flag, video filter snippet and audio filter
78
+ // snippet for a single bubble. It largely mirrors the logic used later
79
+ // when executing ffmpeg, but stops before constructing the command.
80
+ const prepareBubble = async (b, vw, vh, meta, inputIndex) => {
81
+ const extra = b.bubbleExtra || {};
82
+ const from = typeof b.fromSec === 'number' ? b.fromSec : 0;
83
+ const to = typeof b.toSec === 'number' ? b.toSec : (from + (b.durationSec || 3));
84
+
85
+ // determine overlay source (image/video) or text
86
+ let isMedia = false;
87
+ let overlayPath = null;
88
+ const mediaField = b.mediaAbsPaths || b.mediaAbsPath || b.mediaAbs;
89
+ let mediaItem = null;
90
+ if (mediaField) {
91
+ mediaItem = Array.isArray(mediaField) ? mediaField[0] : mediaField;
92
+ if (typeof mediaItem === 'string') overlayPath = mediaItem;
93
+ else if (mediaItem && typeof mediaItem.path === 'string') overlayPath = mediaItem.path;
94
+ isMedia = !!overlayPath;
95
+ }
96
+
97
+ // compute size with same math as main code
98
+ const padX = extra.paddingX || 5;
99
+ const padY = extra.paddingY || 5;
100
+ let ow = null;
101
+ let oh = null;
102
+ if (extra.size === 'half') ow = Math.round(vw * 0.45);
103
+ else if (extra.size === 'full') {
104
+ // defer
105
+ } else ow = Math.round(vw * 0.30);
106
+
107
+ let overlayInputFlag = '';
108
+ let vFilter = '';
109
+ let aFilter = '';
110
+ if (isMedia && fs.existsSync(overlayPath)) {
111
+ const imgExts = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif'];
112
+ const overlayExt = path.extname(overlayPath).toLowerCase();
113
+ const isImageFile = imgExts.includes(overlayExt);
114
+ let overlayMeta;
115
+ try { overlayMeta = await FFMpegUtils.getMediaMetadata(overlayPath); } catch (e) { overlayMeta = null; }
116
+ if (overlayMeta && overlayMeta.video && overlayMeta.video.width && overlayMeta.video.height) {
117
+ const iw = overlayMeta.video.width;
118
+ const ih = overlayMeta.video.height;
119
+ const ar = iw / ih;
120
+ if (extra.size === 'full') {
121
+ const maxW = Math.round(vw * (1 - 2 * padX / 100));
122
+ const maxH = Math.round(vh * (1 - 2 * padY / 100));
123
+ const containerRatio = maxW / maxH;
124
+ if (ar > containerRatio) {
125
+ oh = maxH;
126
+ ow = Math.round(maxH * ar);
127
+ } else {
128
+ ow = maxW;
129
+ oh = Math.round(maxW / ar);
130
+ }
131
+ if (ow < maxW) ow = maxW;
132
+ if (oh < maxH) oh = maxH;
133
+ } else {
134
+ if (!ow) ow = Math.round(vw * 0.30);
135
+ if (!oh) oh = Math.round(ow / ar);
136
+ }
137
+ } else {
138
+ if (!oh) {
139
+ if (extra.size === 'full') {
140
+ oh = Math.round(vh * (1 - 2 * padY / 100));
141
+ ow = Math.round(vw * (1 - 2 * padX / 100));
142
+ } else {
143
+ oh = Math.round(ow * 0.75);
144
+ }
145
+ }
146
+ }
147
+
148
+ const { x, y } = computeXY(ow, oh, extra, vw, vh);
149
+ const anim = (mediaItem && mediaItem.animExtra) || b.animExtra || {};
150
+ const animTpl = (anim && typeof anim.template === 'string') ? anim.template : null;
151
+ const animDur = (typeof anim.durationSec === 'number') ? anim.durationSec : Math.min(0.5, (to - from) / 2);
152
+ let xExpr = x;
153
+ let yExpr = y;
154
+ if (animTpl) {
155
+ const tpl = animTpl;
156
+ const wrapVal = (v) => (typeof v === 'number' ? `(${v})` : v);
157
+ const quote = (expr) => `'${expr.replace(/'/g, "\\'")}'`;
158
+ if (tpl === 'slide_down') {
159
+ const startY = -oh;
160
+ yExpr = `if(lt(t,${from + animDur}), ${wrapVal(startY)} + (${wrapVal(y)}-${wrapVal(startY)})*(t-${from})/${animDur}, ${wrapVal(y)})`;
161
+ } else if (tpl === 'slide_up') {
162
+ const startY = vh;
163
+ yExpr = `if(lt(t,${from + animDur}), ${wrapVal(startY)} + (${wrapVal(y)}-${wrapVal(startY)})*(t-${from})/${animDur}, ${wrapVal(y)})`;
164
+ } else if (tpl === 'slide_left') {
165
+ const startX = -ow;
166
+ xExpr = `if(lt(t,${from + animDur}), ${wrapVal(startX)} + (${wrapVal(x)}-${wrapVal(startX)})*(t-${from})/${animDur}, ${wrapVal(x)})`;
167
+ } else if (tpl === 'slide_right') {
168
+ const startX = vw;
169
+ xExpr = `if(lt(t,${from + animDur}), ${wrapVal(startX)} + (${wrapVal(x)}-${wrapVal(startX)})*(t-${from})/${animDur}, ${wrapVal(x)})`;
170
+ }
171
+ if (typeof xExpr === 'string') xExpr = quote(xExpr);
172
+ if (typeof yExpr === 'string') yExpr = quote(yExpr);
173
+ }
174
+ // video filter part for this bubble; use [0:v] placeholder which
175
+ // will later be swapped with the current chain label by the caller
176
+ vFilter = `[0:v][${inputIndex}:v]overlay=${xExpr}:${yExpr}:enable='between(t,${from},${to})'[v${inputIndex}]`;
177
+ // audio filter part for effect
178
+ if (b.audioEffectFile) {
179
+ const aVol = typeof b.audioEffectVolume === 'number' ? b.audioEffectVolume : 1.0;
180
+ const delayMs = Math.round(from * 1000);
181
+ const clipSec = Math.min((typeof b.audioEffectDurationSec === 'number' ? b.audioEffectDurationSec : (to - from)), (to - from));
182
+ aFilter = `[0:a]aresample=async=1[a0];[${inputIndex + 1}:a]atrim=0:${clipSec},asetpts=PTS-STARTPTS,volume=${aVol}[aeff];[aeff]adelay=${delayMs}|${delayMs}[aeffd];[a0][aeffd]amix=inputs=2:duration=first:dropout_transition=0[aout]`;
183
+ }
184
+ // input flag
185
+ overlayInputFlag = isImageFile
186
+ ? (meta.duration ? `-loop 1 -t ${meta.duration} -i "${overlayPath}"` : `-loop 1 -i "${overlayPath}"`)
187
+ : `-i "${overlayPath}"`;
188
+ } else if (b.bubbleText && b.bubbleText.text) {
189
+ // text bubble becomes ASS entry; we'll handle outside of this helper
190
+ vFilter = null; // indicates we'll use subtitles grouping
191
+ }
192
+ return { overlayInputFlag, vFilter, aFilter, isText: !!(b.bubbleText && b.bubbleText.text) };
193
+ };
194
+
195
+ // support passing an array of bubble configs. If all bubbles are media
196
+ // (no bubbleText) we can render them in a single ffmpeg invocation; otherwise
197
+ // fall back to the original sequential encoding so text rendering via ASS
198
+ // continues to work.
199
+ if (Array.isArray(bubble)) {
200
+ const hasText = bubble.some(b => b.bubbleText && b.bubbleText.text);
201
+ if (hasText) {
202
+ // sequential because mixing ASS events is tricky
203
+ let current = videoPath;
204
+ for (let idx = 0; idx < bubble.length; idx++) {
205
+ const tmp = tempPath('bubble-step', 'mp4');
206
+ await this.makeBubble(current, bubble[idx], tmp, onLog);
207
+ if (current !== videoPath && fs.existsSync(current)) fs.unlinkSync(current);
208
+ current = tmp;
209
+ }
210
+ fs.copyFileSync(current, outputPath);
211
+ return outputPath;
212
+ }
213
+
214
+ if (!fs.existsSync(videoPath)) throw new Error('video not found: ' + videoPath);
215
+ const meta = await FFMpegUtils.getMediaMetadata(videoPath);
216
+ const vw = meta.video.width;
217
+ const vh = meta.video.height;
218
+ const mainDuration = meta.duration || meta.video?.duration || 0;
219
+ let inputs = [`-i "${videoPath}"`];
220
+ const filterParts = [];
221
+ const audioParts = [];
222
+ let currentLabel = '[0:v]';
223
+ let inputIndex = 1;
224
+
225
+ // (no ASS processing needed because hasText is false)
226
+
227
+ for (const b of bubble) {
228
+ const { overlayInputFlag, vFilter, aFilter } = await prepareBubble(b, vw, vh, meta, inputIndex);
229
+ if (overlayInputFlag) {
230
+ inputs.push(overlayInputFlag);
231
+ inputIndex++;
232
+ }
233
+ if (vFilter) {
234
+ const part = vFilter.replace(/\[0:v\]/g, currentLabel);
235
+ filterParts.push(part);
236
+ currentLabel = `[v${inputIndex - 1}]`;
237
+ }
238
+ if (aFilter) audioParts.push(aFilter);
239
+ }
240
+
241
+
242
+ const videoFilter = filterParts.length ? filterParts.join(';') : '';
243
+ const audioFilter = audioParts.length ? audioParts.join(';') : '[0:a]aresample=async=1[aout]';
244
+ const fc = [videoFilter, audioFilter].filter(Boolean).join(';');
245
+
246
+ const cmd = `ffmpeg ${inputs.join(' ')} -filter_complex "${fc}" -map "${currentLabel === '[0:v]' ? '[0:v]' : currentLabel}" ${audioFilter ? '-map "[aout]" -c:a aac' : ''} -c:v libx264 -preset veryfast -crf 23 -shortest "${outputPath}" -y`;
247
+ onLog && onLog('Running ffmpeg: ' + cmd);
248
+ await FFMpegUtils.execute(cmd);
249
+ return outputPath;
250
+ }
251
+
252
  if (!fs.existsSync(videoPath)) throw new Error('video not found: ' + videoPath);
253
  const meta = await FFMpegUtils.getMediaMetadata(videoPath);
254
  const vw = meta.video.width;
 
645
  const outPath2 = path.join(outDir, 'media_image_template_bubble.mp4');
646
  await bubbleMaker.makeBubble(baseVideo, imageSample, outPath2, console.log);
647
  console.log('Created:', outPath2);
648
+
649
+ // combined example: two bubbles layered one after the other
650
+ const comboSample = [
651
+ imageSample,
652
+ {
653
+ templateName: 'simple-top-center',
654
+ bubbleText: { text: 'SECOND BUBBLE' },
655
+ fromSec: 5,
656
+ toSec: 10
657
+ }
658
+ ];
659
+ const outPath3 = path.join(outDir, 'media_combo_bubbles.mp4');
660
+ await bubbleMaker.makeBubble(baseVideo, comboSample, outPath3, console.log);
661
+ console.log('Created combo:', outPath3);
662
  } catch (e) {
663
  console.error('Test failed:', e);
664
  }