vidspotai-shared 1.0.133 → 1.0.135

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.
Files changed (43) hide show
  1. package/lib/globals/aiModels/providers/falVideo.d.ts +34 -0
  2. package/lib/globals/aiModels/providers/falVideo.d.ts.map +1 -0
  3. package/lib/globals/aiModels/providers/falVideo.js +102 -0
  4. package/lib/globals/index.d.ts +1 -0
  5. package/lib/globals/index.d.ts.map +1 -1
  6. package/lib/globals/index.js +1 -0
  7. package/lib/globals/musicStudio.d.ts +90 -0
  8. package/lib/globals/musicStudio.d.ts.map +1 -0
  9. package/lib/globals/musicStudio.js +221 -0
  10. package/lib/globals/types.d.ts +10 -1
  11. package/lib/globals/types.d.ts.map +1 -1
  12. package/lib/globals/types.js +12 -0
  13. package/lib/models/index.d.ts +1 -0
  14. package/lib/models/index.d.ts.map +1 -1
  15. package/lib/models/index.js +1 -0
  16. package/lib/models/musicJob.model.d.ts +73 -0
  17. package/lib/models/musicJob.model.d.ts.map +1 -0
  18. package/lib/models/musicJob.model.js +2 -0
  19. package/lib/services/aiGen/providers/fal/falMusic.service.d.ts +63 -0
  20. package/lib/services/aiGen/providers/fal/falMusic.service.d.ts.map +1 -0
  21. package/lib/services/aiGen/providers/fal/falMusic.service.js +310 -0
  22. package/lib/services/aiGen/providers/fal/falVideo.service.d.ts +39 -0
  23. package/lib/services/aiGen/providers/fal/falVideo.service.d.ts.map +1 -0
  24. package/lib/services/aiGen/providers/fal/falVideo.service.js +266 -0
  25. package/lib/services/aiGen/providers/fal/index.d.ts +1 -0
  26. package/lib/services/aiGen/providers/fal/index.d.ts.map +1 -1
  27. package/lib/services/aiGen/providers/fal/index.js +1 -0
  28. package/lib/services/firestore.service.d.ts +2 -0
  29. package/lib/services/firestore.service.d.ts.map +1 -1
  30. package/lib/services/firestore.service.js +3 -0
  31. package/lib/services/index.d.ts +1 -0
  32. package/lib/services/index.d.ts.map +1 -1
  33. package/lib/services/index.js +1 -0
  34. package/lib/services/music/index.d.ts +3 -0
  35. package/lib/services/music/index.d.ts.map +1 -0
  36. package/lib/services/music/index.js +18 -0
  37. package/lib/services/music/musicLyricWriter.d.ts +25 -0
  38. package/lib/services/music/musicLyricWriter.d.ts.map +1 -0
  39. package/lib/services/music/musicLyricWriter.js +58 -0
  40. package/lib/services/music/musicLyrics.d.ts +66 -0
  41. package/lib/services/music/musicLyrics.d.ts.map +1 -0
  42. package/lib/services/music/musicLyrics.js +258 -0
  43. package/package.json +1 -1
@@ -0,0 +1,73 @@
1
+ import { FieldValue } from "firebase-admin/firestore";
2
+ import { EImageJobStatus } from "../globals/types";
3
+ import type { MusicJobOp, MusicModelKey, MusicStemName } from "../globals/musicStudio";
4
+ export type MusicVocalStyle = "female" | "male" | "duet" | "choir";
5
+ /** One sung line with its start/end on the track, from the lyric-sync pass. */
6
+ export interface MusicTimedLine {
7
+ text: string;
8
+ start: number;
9
+ end: number;
10
+ }
11
+ /**
12
+ * Persistent record for one Music Studio track (or one operation on a track).
13
+ * Created by the Cloud Function controller, finalized by the MUSIC_JOBS
14
+ * worker; the same doc is the user's library entry. Status values reuse
15
+ * EImageJobStatus so the client normaliser is shared with image jobs.
16
+ *
17
+ * Ops other than `generate` / `convert` point at their source with
18
+ * `sourceJobId` + `sourceAudioUrl`. `stems` jobs produce `stems` instead of
19
+ * a new `audioUrl`.
20
+ */
21
+ export interface IMusicJobModel {
22
+ userId: string;
23
+ op: MusicJobOp;
24
+ status: EImageJobStatus;
25
+ /** Generation model (generate). Track ops are pinned to their own provider app. */
26
+ modelKey?: MusicModelKey;
27
+ title: string;
28
+ prompt: string;
29
+ lyrics?: string;
30
+ instrumental: boolean;
31
+ vocalStyle?: MusicVocalStyle;
32
+ genres?: string[];
33
+ moods?: string[];
34
+ bpm?: number;
35
+ language?: string;
36
+ /** Requested length (generate), extension length (extend). */
37
+ durationSec?: number;
38
+ sourceJobId?: string;
39
+ sourceAudioUrl?: string;
40
+ /** Source track length the op was billed on (remix / section / stems / convert). */
41
+ sourceDurationSec?: number;
42
+ /** `section`: the span to regenerate. */
43
+ sectionStartSec?: number;
44
+ sectionEndSec?: number;
45
+ /** `remix`: "remix" restyles the music; "lyrics" keeps it and swaps the words. */
46
+ remixMode?: "remix" | "lyrics";
47
+ /** `convert`: how far to move from the recording (0–1). */
48
+ strength?: number;
49
+ providerApp?: string;
50
+ providerRequestId?: string;
51
+ stage?: "writing-lyrics" | "composing" | "uploading" | "syncing-lyrics";
52
+ audioUrl?: string;
53
+ mimeType?: string;
54
+ outputDurationSec?: number;
55
+ stems?: Partial<Record<MusicStemName, string>>;
56
+ /** Lyrics actually sung — user's, auto-written, or the model's own. */
57
+ sungLyrics?: string;
58
+ timedLines?: MusicTimedLine[];
59
+ /** Style tags the model settled on (ACE-Step). Reused by remix/extend. */
60
+ styleTags?: string;
61
+ seed?: number;
62
+ coverImageUrl?: string;
63
+ isPublic: boolean;
64
+ estimatedCredits?: number;
65
+ totalCreditsUsed?: number;
66
+ errorMessage?: string;
67
+ lastHeartbeatAt?: FieldValue;
68
+ creditReconciliationStatus?: "completed" | "pending";
69
+ creditReconciliationError?: string;
70
+ createdAt: FieldValue;
71
+ updatedAt: FieldValue;
72
+ }
73
+ //# sourceMappingURL=musicJob.model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"musicJob.model.d.ts","sourceRoot":"","sources":["../../src/models/musicJob.model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvF,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAEnE,+EAA+E;AAC/E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,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AE,OAAO,CAAC,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/C,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,cAAc,EAAE,CAAC;IAC9B,0EAA0E;IAC1E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IAGvB,QAAQ,EAAE,OAAO,CAAC;IAGlB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,UAAU,CAAC;IAC7B,0BAA0B,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IACrD,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,EAAE,UAAU,CAAC;CACvB"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,63 @@
1
+ import { type MusicModelKey, type MusicStemName } from "../../../../globals/musicStudio";
2
+ import type { IMusicJobModel } from "../../../../models/musicJob.model";
3
+ import { type LyricWord } from "../../../music/musicLyrics";
4
+ export type FalQueueState = "IN_QUEUE" | "IN_PROGRESS" | "COMPLETED";
5
+ /** A fal request ready to submit: the app id plus its input body. */
6
+ export interface FalMusicRequest {
7
+ app: string;
8
+ input: Record<string, unknown>;
9
+ }
10
+ export interface FalAudioOutput {
11
+ url: string;
12
+ contentType: string;
13
+ /** Lyrics / tags / seed the model reports back (ACE-Step). */
14
+ lyrics?: string;
15
+ tags?: string;
16
+ seed?: number;
17
+ }
18
+ /**
19
+ * fal.ai music — every Music Studio model except Lyria 2 (Vertex) plus the
20
+ * track operations (ACE-Step extend / remix / inpaint, Stable Audio
21
+ * audio-to-audio, Demucs stems, ElevenLabs Scribe lyric sync). Queue-only:
22
+ * this service exposes submit / status / result and leaves the poll loop to
23
+ * the MUSIC_JOBS worker, which persists the request id so a re-delivered job
24
+ * resumes instead of paying twice.
25
+ *
26
+ * Input builders are pure (job → request) so the provider-shape rules can be
27
+ * unit-tested without the network.
28
+ */
29
+ export declare class FalMusicService {
30
+ private readonly apiKey;
31
+ constructor();
32
+ private headers;
33
+ /**
34
+ * Status/result routes drop an app id's nested sub-path
35
+ * (`fal-ai/minimax-music/v2.5` → `fal-ai/minimax-music`), so a resumed job
36
+ * only needs the persisted app id + request id.
37
+ */
38
+ private routes;
39
+ submit(req: FalMusicRequest): Promise<string>;
40
+ status(app: string, requestId: string): Promise<FalQueueState>;
41
+ result(app: string, requestId: string): Promise<Record<string, unknown>>;
42
+ }
43
+ /**
44
+ * Text-to-music request for a `generate` job on a fal model. `lyrics` is what
45
+ * should be sung (the user's, or auto-written when the model needs them);
46
+ * empty for instrumentals or when the model writes its own.
47
+ */
48
+ export declare function buildGenerateRequest(job: IMusicJobModel, modelKey: MusicModelKey, durationSec: number, lyrics: string): FalMusicRequest;
49
+ /** What the worker knows about the track an op works on. */
50
+ export interface MusicSourceTrack {
51
+ audioUrl: string;
52
+ durationSec: number;
53
+ styleTags: string;
54
+ lyrics: string;
55
+ }
56
+ /** Request for a track operation (extend / remix / section / convert / stems). */
57
+ export declare function buildOpRequest(job: IMusicJobModel, source: MusicSourceTrack): FalMusicRequest;
58
+ export declare function buildLyricSyncRequest(audioUrl: string): FalMusicRequest;
59
+ export declare function parseAudioOutput(raw: Record<string, unknown>, app: string): FalAudioOutput;
60
+ export declare function parseStemsOutput(raw: Record<string, unknown>): Partial<Record<MusicStemName, string>>;
61
+ /** Word timings from ElevenLabs Scribe (audio events like "[singing]" and spacing dropped). */
62
+ export declare function parseLyricWords(raw: Record<string, unknown>): LyricWord[];
63
+ //# sourceMappingURL=falMusic.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"falMusic.service.d.ts","source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AAM,GACb,eAAe,CA2FjB;AAED,4DAA4D;AAC5D,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,EAAE,MAAM,EAAE,gBAAgB,GAAG,eAAe,CAwD7F;AAED,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,eAAe,CAEvE;AAID,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,cAAc,CAW1F;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,CAQrG;AAED,+FAA+F;AAC/F,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,CAKzE"}
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FalMusicService = void 0;
4
+ exports.buildGenerateRequest = buildGenerateRequest;
5
+ exports.buildOpRequest = buildOpRequest;
6
+ exports.buildLyricSyncRequest = buildLyricSyncRequest;
7
+ exports.parseAudioOutput = parseAudioOutput;
8
+ exports.parseStemsOutput = parseStemsOutput;
9
+ exports.parseLyricWords = parseLyricWords;
10
+ const musicStudio_1 = require("../../../../globals/musicStudio");
11
+ const errors_1 = require("../../../../utils/errors");
12
+ const logger_1 = require("../../../../utils/logger");
13
+ const musicLyrics_1 = require("../../../music/musicLyrics");
14
+ const transientRetry_1 = require("../../transientRetry");
15
+ const falUpscale_service_1 = require("./falUpscale.service");
16
+ const QUEUE_BASE_URL = "https://queue.fal.run";
17
+ /**
18
+ * fal.ai music — every Music Studio model except Lyria 2 (Vertex) plus the
19
+ * track operations (ACE-Step extend / remix / inpaint, Stable Audio
20
+ * audio-to-audio, Demucs stems, ElevenLabs Scribe lyric sync). Queue-only:
21
+ * this service exposes submit / status / result and leaves the poll loop to
22
+ * the MUSIC_JOBS worker, which persists the request id so a re-delivered job
23
+ * resumes instead of paying twice.
24
+ *
25
+ * Input builders are pure (job → request) so the provider-shape rules can be
26
+ * unit-tested without the network.
27
+ */
28
+ class FalMusicService {
29
+ constructor() {
30
+ if (!process.env.FAL_KEY) {
31
+ throw new Error("Missing FAL_KEY in environment variables");
32
+ }
33
+ this.apiKey = process.env.FAL_KEY;
34
+ }
35
+ headers(json) {
36
+ const h = { Authorization: `Key ${this.apiKey}` };
37
+ if (json)
38
+ h["Content-Type"] = "application/json";
39
+ return h;
40
+ }
41
+ /**
42
+ * Status/result routes drop an app id's nested sub-path
43
+ * (`fal-ai/minimax-music/v2.5` → `fal-ai/minimax-music`), so a resumed job
44
+ * only needs the persisted app id + request id.
45
+ */
46
+ routes(app, requestId) {
47
+ const [owner, name] = app.split("/");
48
+ const base = `${QUEUE_BASE_URL}/${owner}/${name}/requests/${requestId}`;
49
+ return { statusUrl: `${base}/status`, responseUrl: base };
50
+ }
51
+ async submit(req) {
52
+ return (0, transientRetry_1.withTransientRetry)(`fal:${req.app}:submit`, async () => {
53
+ const resp = await fetch(`${QUEUE_BASE_URL}/${req.app}`, {
54
+ method: "POST",
55
+ headers: this.headers(true),
56
+ body: JSON.stringify(req.input),
57
+ });
58
+ if (!resp.ok) {
59
+ const body = await resp.text();
60
+ if (resp.status === 422)
61
+ throw rejectedInput(body);
62
+ throw (0, falUpscale_service_1.classifyFalHttpError)(resp.status, body, `${req.app}:submit`);
63
+ }
64
+ const data = (await resp.json());
65
+ if (!data.request_id)
66
+ throw new Error(`fal ${req.app} did not return a request_id`);
67
+ return data.request_id;
68
+ }, {
69
+ onRetry: ({ attempt, maxAttempts, backoffMs, err }) => logger_1.logger.warn("fal music submit transient error — retrying", {
70
+ app: req.app,
71
+ attempt,
72
+ maxAttempts,
73
+ backoffMs,
74
+ message: err.message,
75
+ }),
76
+ });
77
+ }
78
+ async status(app, requestId) {
79
+ const resp = await fetch(this.routes(app, requestId).statusUrl, { headers: this.headers(false) });
80
+ if (!resp.ok)
81
+ throw (0, falUpscale_service_1.classifyFalHttpError)(resp.status, await resp.text(), `${app}:status`);
82
+ const data = (await resp.json());
83
+ if (data.error)
84
+ throw new Error(`fal ${app} failed: ${data.error}`);
85
+ const status = (data.status ?? "").toUpperCase();
86
+ if (status === "COMPLETED" || status === "IN_PROGRESS")
87
+ return status;
88
+ return "IN_QUEUE";
89
+ }
90
+ async result(app, requestId) {
91
+ const resp = await fetch(this.routes(app, requestId).responseUrl, { headers: this.headers(false) });
92
+ if (!resp.ok) {
93
+ const body = await resp.text();
94
+ if (resp.status === 422)
95
+ throw rejectedInput(body);
96
+ throw (0, falUpscale_service_1.classifyFalHttpError)(resp.status, body, `${app}:result`);
97
+ }
98
+ return (await resp.json());
99
+ }
100
+ }
101
+ exports.FalMusicService = FalMusicService;
102
+ /** fal 422s on content moderation as well as bad input — both are the user's to fix. */
103
+ function rejectedInput(body) {
104
+ const flagged = /safety|moderat|content policy|nsfw|inappropriate|copyright/i.test(body);
105
+ return new errors_1.UserFacingError(flagged
106
+ ? "The music model declined this prompt or these lyrics. Rephrase them (avoid real artist names and copyrighted lyrics) and try again."
107
+ : "The music model couldn't use these settings. Adjust the prompt, lyrics or length and try again.", flagged ? errors_1.USER_FACING_ERROR_CODES.CONTENT_POLICY_VIOLATION : errors_1.USER_FACING_ERROR_CODES.PROMPT_INVALID);
108
+ }
109
+ // ── Request builders ─────────────────────────────────────────────────────
110
+ function styleInput(job) {
111
+ return {
112
+ prompt: job.prompt,
113
+ genres: job.genres,
114
+ moods: job.moods,
115
+ bpm: job.bpm,
116
+ instrumental: job.instrumental,
117
+ vocalStyle: job.vocalStyle,
118
+ language: job.language,
119
+ };
120
+ }
121
+ /**
122
+ * Text-to-music request for a `generate` job on a fal model. `lyrics` is what
123
+ * should be sung (the user's, or auto-written when the model needs them);
124
+ * empty for instrumentals or when the model writes its own.
125
+ */
126
+ function buildGenerateRequest(job, modelKey, durationSec, lyrics) {
127
+ const model = musicStudio_1.MUSIC_MODELS[modelKey];
128
+ if (!model.falApp)
129
+ throw new Error(`${modelKey} is not a fal model`);
130
+ const style = styleInput(job);
131
+ const prompt = (0, musicLyrics_1.composeStylePrompt)(style, model.maxPromptChars);
132
+ const sing = !job.instrumental && model.vocals;
133
+ switch (modelKey) {
134
+ case "minimax-music-2.5":
135
+ return {
136
+ app: model.falApp,
137
+ input: {
138
+ prompt,
139
+ lyrics: sing ? lyrics : "",
140
+ is_instrumental: !sing,
141
+ lyrics_optimizer: sing && !lyrics,
142
+ audio_setting: { format: "mp3", bitrate: 256000, sample_rate: 44100 },
143
+ },
144
+ };
145
+ case "minimax-music-2":
146
+ return {
147
+ app: model.falApp,
148
+ input: {
149
+ prompt: prompt.length >= 10 ? prompt : `${prompt} song`.padEnd(10, "."),
150
+ lyrics_prompt: lyrics,
151
+ audio_setting: { format: "mp3", bitrate: 256000, sample_rate: 44100 },
152
+ },
153
+ };
154
+ case "elevenlabs-music": {
155
+ const sections = sing && lyrics ? (0, musicLyrics_1.toElevenLabsSections)(lyrics, durationSec) : [];
156
+ if (sections.length > 0) {
157
+ return {
158
+ app: model.falApp,
159
+ input: {
160
+ composition_plan: {
161
+ positive_global_styles: [prompt.slice(0, 500)],
162
+ negative_global_styles: [],
163
+ sections,
164
+ },
165
+ respect_sections_durations: true,
166
+ output_format: "mp3_44100_192",
167
+ },
168
+ };
169
+ }
170
+ return {
171
+ app: model.falApp,
172
+ input: {
173
+ prompt,
174
+ music_length_ms: durationSec * 1000,
175
+ force_instrumental: !sing,
176
+ output_format: "mp3_44100_192",
177
+ },
178
+ };
179
+ }
180
+ case "lyria-3":
181
+ return {
182
+ app: model.falApp,
183
+ input: {
184
+ prompt: (sing && lyrics ? `${prompt}\n\nLyrics:\n${lyrics}` : prompt).slice(0, model.maxPromptChars),
185
+ },
186
+ };
187
+ case "ace-step":
188
+ // No lyrics and a vocal track → prompt-to-audio, which writes tags + lyrics itself.
189
+ if (sing && !lyrics) {
190
+ return {
191
+ app: "fal-ai/ace-step/prompt-to-audio",
192
+ input: { prompt, duration: durationSec, instrumental: false },
193
+ };
194
+ }
195
+ return {
196
+ app: model.falApp,
197
+ input: { tags: (0, musicLyrics_1.composeStyleTags)(style), lyrics: sing ? lyrics : "[inst]", duration: durationSec },
198
+ };
199
+ case "diffrhythm":
200
+ return {
201
+ app: model.falApp,
202
+ input: {
203
+ lyrics: (0, musicLyrics_1.toLrc)(lyrics, durationSec),
204
+ style_prompt: prompt.slice(0, model.maxPromptChars),
205
+ music_duration: durationSec > 95 ? "285s" : "95s",
206
+ },
207
+ };
208
+ case "stable-audio-2.5":
209
+ return { app: model.falApp, input: { prompt, seconds_total: durationSec } };
210
+ case "beatoven":
211
+ return { app: model.falApp, input: { prompt, duration: durationSec } };
212
+ case "cassetteai":
213
+ return { app: model.falApp, input: { prompt, duration: Math.round(durationSec) } };
214
+ default:
215
+ throw new Error(`No fal request builder for ${modelKey}`);
216
+ }
217
+ }
218
+ /** Request for a track operation (extend / remix / section / convert / stems). */
219
+ function buildOpRequest(job, source) {
220
+ const tags = job.genres?.length || job.moods?.length ? (0, musicLyrics_1.composeStyleTags)(styleInput(job)) : source.styleTags;
221
+ const sourceLyrics = source.lyrics || "[inst]";
222
+ switch (job.op) {
223
+ case "extend":
224
+ return {
225
+ app: musicStudio_1.MUSIC_OP_APPS.extend,
226
+ input: {
227
+ audio_url: source.audioUrl,
228
+ tags,
229
+ lyrics: job.lyrics || sourceLyrics,
230
+ extend_after_duration: job.durationSec ?? 30,
231
+ },
232
+ };
233
+ case "remix":
234
+ return {
235
+ app: musicStudio_1.MUSIC_OP_APPS.remix,
236
+ input: {
237
+ audio_url: source.audioUrl,
238
+ edit_mode: job.remixMode ?? "remix",
239
+ tags,
240
+ original_tags: source.styleTags || tags,
241
+ lyrics: job.lyrics || sourceLyrics,
242
+ original_lyrics: sourceLyrics,
243
+ },
244
+ };
245
+ case "section":
246
+ return {
247
+ app: musicStudio_1.MUSIC_OP_APPS.section,
248
+ input: {
249
+ audio_url: source.audioUrl,
250
+ tags,
251
+ lyrics: job.lyrics || sourceLyrics,
252
+ start_time: job.sectionStartSec ?? 0,
253
+ end_time: job.sectionEndSec ?? Math.min(30, source.durationSec),
254
+ variance: 0.6,
255
+ },
256
+ };
257
+ case "convert":
258
+ return {
259
+ app: musicStudio_1.MUSIC_OP_APPS.convert,
260
+ input: {
261
+ prompt: (0, musicLyrics_1.composeStylePrompt)(styleInput(job), 2000),
262
+ audio_url: source.audioUrl,
263
+ strength: job.strength ?? 0.75,
264
+ total_seconds: Math.max(10, Math.min(190, Math.round(source.durationSec))),
265
+ },
266
+ };
267
+ case "stems":
268
+ return {
269
+ app: musicStudio_1.MUSIC_OP_APPS.stems,
270
+ input: { audio_url: source.audioUrl, model: "htdemucs_6s", output_format: "wav" },
271
+ };
272
+ default:
273
+ throw new Error(`No fal request for music op ${job.op}`);
274
+ }
275
+ }
276
+ function buildLyricSyncRequest(audioUrl) {
277
+ return { app: musicStudio_1.MUSIC_OP_APPS.lyricSync, input: { audio_url: audioUrl } };
278
+ }
279
+ // ── Output parsers ───────────────────────────────────────────────────────
280
+ function parseAudioOutput(raw, app) {
281
+ const file = (raw.audio ?? raw.audio_file);
282
+ if (!file?.url)
283
+ throw new Error(`fal ${app} returned no audio`);
284
+ const lyrics = typeof raw.lyrics === "string" && app.includes("ace-step") ? raw.lyrics : undefined;
285
+ return {
286
+ url: file.url,
287
+ contentType: file.content_type ?? "audio/mpeg",
288
+ ...(lyrics && lyrics.trim() !== "[inst]" ? { lyrics } : {}),
289
+ ...(typeof raw.tags === "string" ? { tags: raw.tags } : {}),
290
+ ...(typeof raw.seed === "number" ? { seed: raw.seed } : {}),
291
+ };
292
+ }
293
+ function parseStemsOutput(raw) {
294
+ const stems = {};
295
+ for (const name of musicStudio_1.MUSIC_STEMS) {
296
+ const url = raw[name]?.url;
297
+ if (url)
298
+ stems[name] = url;
299
+ }
300
+ if (Object.keys(stems).length === 0)
301
+ throw new Error("fal demucs returned no stems");
302
+ return stems;
303
+ }
304
+ /** Word timings from ElevenLabs Scribe (audio events like "[singing]" and spacing dropped). */
305
+ function parseLyricWords(raw) {
306
+ const words = Array.isArray(raw.words) ? raw.words : [];
307
+ return words
308
+ .filter((w) => w.type === "word" && typeof w.text === "string")
309
+ .map((w) => ({ text: String(w.text), start: Number(w.start) || 0, end: Number(w.end) || 0 }));
310
+ }
@@ -0,0 +1,39 @@
1
+ import { EVideoMode } from "../../types";
2
+ import { BaseAiGenProviderService } from "../baseAiGenProvider.service";
3
+ import { CreditUsageParams, VideoGenerationParams, VideoGenerationResult, VideoStatusParams, VideoStatusResult } from "../types";
4
+ /**
5
+ * Output resolution actually sent to fal. An explicit, allowed `resolution`
6
+ * wins; otherwise mode maps std→720p, pro→1080p (Kling's own equivalence).
7
+ * Flash is 720p-only. Exported so billing prices the SAME resolution the
8
+ * request carried — fal's default is 1080p, so never leave it implicit.
9
+ */
10
+ export declare function resolveFalKlingResolution(modelKey: string, resolution?: string, mode?: EVideoMode | string): "720p" | "1080p";
11
+ /**
12
+ * Generic fal.ai video-generation provider. Today it serves Kling 4.0 and
13
+ * Kling 4.0 Flash (configs in globals/aiModels/providers/falVideo.ts), routing
14
+ * each request to the matching fal sub-endpoint:
15
+ * reference images/videos → v4/reference-to-video (not on Flash)
16
+ * a start frame → v4[/flash]/image-to-video
17
+ * otherwise → v4[/flash]/text-to-video
18
+ *
19
+ * The stored task is `<queue app path>|<request_id>`: fal's queue
20
+ * status/result URLs depend on the app path, which differs per sub-endpoint,
21
+ * so the poller needs it back. The path is taken from the submit response's
22
+ * `status_url` when present (fal's own canonical form), else the endpoint id.
23
+ */
24
+ export declare class FalVideoService extends BaseAiGenProviderService {
25
+ private readonly apiKey;
26
+ constructor();
27
+ private headers;
28
+ private buildRequest;
29
+ generateVideo(params: VideoGenerationParams): Promise<VideoGenerationResult>;
30
+ checkVideoStatus({ task, outputFilename, outputFilePath, }: VideoStatusParams): Promise<VideoStatusResult>;
31
+ /**
32
+ * Per second at the resolution the request sends. With a reference video
33
+ * fal/Kling bill a lower rate on (output × 2) when the input is no longer
34
+ * than the output, else (input + output) seconds. An unknown input length
35
+ * falls back to output × 2 (the input ≤ output case).
36
+ */
37
+ getCreditUsed({ modelKey, mode, resolution, duration, multiClip, inputType, hasInputVideo, inputVideoDurationSec, creditFloor, }: CreditUsageParams): number;
38
+ }
39
+ //# sourceMappingURL=falVideo.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"falVideo.service.d.ts","sourceRoot":"","sources":["../../../../../src/services/aiGen/providers/fal/falVideo.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAoClB;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,EACnB,IAAI,CAAC,EAAE,UAAU,GAAG,MAAM,GACzB,MAAM,GAAG,OAAO,CAKlB;AAsBD;;;;;;;;;;;;GAYG;AACH,qBAAa,eAAgB,SAAQ,wBAAwB;IAC3D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;;IAUhC,OAAO,CAAC,OAAO;IAMf,OAAO,CAAC,YAAY;IA6Dd,aAAa,CAAC,MAAM,EAAE,qBAAqB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IA0C5E,gBAAgB,CAAC,EACrB,IAAI,EACJ,cAAc,EACd,cAAyB,GAC1B,EAAE,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAsDjD;;;;;OAKG;IACH,aAAa,CAAC,EACZ,QAAQ,EACR,IAAI,EACJ,UAAU,EACV,QAAY,EACZ,SAAiB,EACjB,SAAS,EACT,aAAa,EACb,qBAAqB,EACrB,WAAW,GACZ,EAAE,iBAAiB,GAAG,MAAM;CAwB9B"}