reikernx commited on
Commit
d583afa
Β·
verified Β·
1 Parent(s): dacd764

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +425 -117
server.js CHANGED
@@ -161,30 +161,110 @@ app.get('/constituent/health', (req, res) => {
161
  });
162
 
163
  // ═══════════════════════════════════════════════════════════════════════════
164
- // ADD MOVIE API
165
- // Called by main server when a user (who owns this constituent) adds a movie.
166
  // Only the constituent's owner can trigger this.
167
- // Body: { streamId, movieLink, movieTitle, thumbnail, tmdbInfo? }
 
 
 
 
 
168
  // ═══════════════════════════════════════════════════════════════════════════
169
 
170
- app.post('/constituent/add-movie', requireMainServer, async (req, res) => {
171
- const { streamId, movieLink, movieTitle, thumbnail, tmdbInfo } = req.body;
 
 
 
172
 
173
- if (!streamId || !movieLink || !movieTitle) {
174
- return res.status(400).json({ success: false, error: 'streamId, movieLink, and movieTitle are required' });
 
 
 
 
 
 
175
  }
 
 
 
 
 
 
 
 
176
 
177
- // Only owner's streams are allowed
 
 
178
  if (streamId !== constituentConfig.ownerId) {
179
  return res.status(403).json({ success: false, error: 'Only the constituent owner can add movies to this server' });
180
  }
181
 
182
- res.json({ success: true, message: 'Movie queued for download and encoding', streamId, title: movieTitle });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- // Process asynchronously so we don't block the response
185
  setImmediate(async () => {
186
  try {
187
- const result = await showplayEnqueueLink(streamId, movieLink, movieTitle, thumbnail || DEFAULT_ARTWORK, tmdbInfo || null);
188
  console.log(`βœ… Movie added to stream ${streamId}: ${result.title}`);
189
  } catch (err) {
190
  console.error(`❌ Failed to add movie to stream ${streamId}:`, err.message);
@@ -192,6 +272,125 @@ app.post('/constituent/add-movie', requireMainServer, async (req, res) => {
192
  });
193
  });
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  // ─── Queue status for a stream ────────────────────────────────────────────────
196
  app.get('/constituent/queue/:streamId', requireMainServer, (req, res) => {
197
  const { streamId } = req.params;
@@ -367,19 +566,20 @@ function buildLivePlaylistAt(streamId, elapsed) {
367
  const state = hlsState[streamId];
368
  if (!state || !state.segments.length) return null;
369
  const segs = state.segments;
370
- let startIdx = Math.max(0, segs.length - HLS_PLAYLIST_WINDOW);
371
  for (let i = 0; i < segs.length; i++) {
372
  if (segs[i].streamEnd > elapsed) { startIdx = i; break; }
373
  }
374
- const window = segs.slice(startIdx, startIdx + HLS_PLAYLIST_WINDOW);
375
- const lines = [
376
- '#EXTM3U',
377
- '#EXT-X-VERSION:3',
378
- `#EXT-X-TARGETDURATION:10`,
379
- `#EXT-X-MEDIA-SEQUENCE:${state.mediaSeq + startIdx}`,
380
- '#EXT-X-DISCONTINUITY-SEQUENCE:0',
381
- ];
382
  for (const seg of window) {
 
 
 
 
383
  lines.push(`#EXTINF:${seg.duration.toFixed(6)},`);
384
  lines.push(seg.uri);
385
  }
@@ -416,141 +616,237 @@ function parseM3u8Durations(playlistPath) {
416
  }
417
 
418
  function watchForSegments(streamId, dir, segPrefix, songHlsStart, onFirstSeg, ownerSid, state) {
419
- let cursor = songHlsStart, firstFlushed = false;
420
- let lastEntryCount = 0;
421
  const playlistPath = path.join(dir, segPrefix + '.m3u8');
422
- const STABLE_NEEDED = 3;
423
- let stableCount = 0;
424
 
425
- const iv = setInterval(() => {
 
426
  const entries = parseM3u8Durations(playlistPath);
427
- if (!entries.length) return;
428
-
 
429
  for (const { file, dur } of entries) {
 
430
  const segPath = path.join(dir, file);
431
- if (!fs.existsSync(segPath)) continue;
 
432
  const seg = { uri: `/hls/${streamId}/${file}`, _path: segPath, streamStart: cursor, streamEnd: cursor + dur, duration: dur, ownerSid };
433
- state.segments.push(seg);
434
- state.totalDuration = cursor + dur;
435
  cursor += dur;
436
-
 
437
  if (!firstFlushed) {
438
  firstFlushed = true;
439
- const q0 = streams[streamId]?.queue[0];
440
- const sidMatch = q0?._sid === ownerSid;
441
- const startMatch = typeof q0._hlsStart === 'number' && songHlsStart === q0._hlsStart;
442
- if (sidMatch && startMatch) {
443
- streams[streamId].songStartTime = Date.now();
 
 
 
 
 
 
 
 
 
444
  }
445
- onFirstSeg();
446
  }
447
  }
 
 
 
 
 
448
 
 
 
 
449
  if (entries.length === lastEntryCount && !activeFFmpeg[streamId]) {
450
- stableCount++;
451
- if (stableCount >= STABLE_NEEDED) { clearInterval(iv); }
452
- } else { stableCount = 0; }
453
- lastEntryCount = entries.length;
454
- }, 500);
 
 
 
 
 
 
 
455
  }
456
 
457
  async function generateSegmentsForSong(streamId, songInfo, isVideo, state) {
458
- const dir = ensureHlsDir(streamId);
459
- const songPath = path.join(SONGS_DIR, songInfo.fileName);
460
- const segPrefix = `seg_${streamId}_${Date.now()}`;
461
- const myGen = hlsGeneration[streamId] || 0;
462
-
463
- return new Promise((resolve, reject) => {
464
- const segPattern = path.join(dir, segPrefix + '_%03d.ts');
465
- const playlistPath = path.join(dir, segPrefix + '.m3u8');
466
- const songHlsStart = state.totalDuration;
467
 
468
- let resolved = false;
469
- function safeResolve(v) { if (!resolved) { resolved = true; resolve(v); } }
 
 
 
470
 
471
- watchForSegments(
472
- streamId, dir, segPrefix, songHlsStart,
473
- () => safeResolve({ hlsStart: songHlsStart }),
474
- songInfo._sid, state
475
- );
476
 
 
477
  const cmd = ffmpeg(songPath);
478
- if (!isVideo) {
479
- cmd.audioCodec('aac').audioBitrate('128k').noVideo();
 
 
 
 
 
 
 
 
480
  } else {
481
- cmd.videoCodec('libx264').audioCodec('aac').audioBitrate('128k')
482
- .outputOptions(['-preset', 'ultrafast', '-tune', 'zerolatency', '-crf', '23',
483
- '-vf', 'scale=854:480:force_original_aspect_ratio=decrease,pad=854:480:(ow-iw)/2:(oh-ih)/2']);
484
  }
485
- cmd.outputOptions([
486
- '-f', 'hls',
487
- '-hls_time', '8',
488
- '-hls_list_size', '0',
489
- '-hls_segment_type', 'mpegts',
490
- `-hls_segment_filename`, segPattern,
491
- '-hls_flags', 'independent_segments',
492
- ]).output(playlistPath);
493
-
494
- activeFFmpeg[streamId] = cmd;
495
-
496
- cmd.on('error', (err) => {
497
- delete activeFFmpeg[streamId];
498
- if (hlsGeneration[streamId] !== myGen) { safeResolve({ hlsStart: songHlsStart }); return; }
499
- console.error(`FFmpeg error [${streamId}]:`, err.message);
500
- if (state) state.generating = false;
501
- if (!resolved) reject(err);
502
- });
503
- cmd.on('end', () => {
504
- delete activeFFmpeg[streamId];
505
- if (state) state.generating = false;
506
- safeResolve({ hlsStart: songHlsStart });
507
- });
508
- cmd.run();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
  });
510
  }
511
 
512
  async function appendSongToHls(streamId, songInfo) {
513
- if (!hlsMutex[streamId]) hlsMutex[streamId] = Promise.resolve();
514
- hlsMutex[streamId] = hlsMutex[streamId].then(async () => {
515
- const myGen = hlsGeneration[streamId] || 0;
516
- if (!hlsState[streamId]) {
517
- hlsState[streamId] = { segments: [], totalDuration: 0, mediaSeq: 0, generating: false };
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  }
519
- const state = hlsState[streamId];
520
  state.generating = true;
521
- const isVideo = !!songInfo.meta.videoUrl;
 
522
  try {
523
- const { hlsStart } = await generateSegmentsForSong(streamId, songInfo, isVideo, state);
524
- if (hlsGeneration[streamId] !== myGen) return;
525
- songInfo._hlsStart = hlsStart;
526
- songInfo._hlsEnd = state.totalDuration;
527
- songInfo._hlsPregened = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  } catch (err) {
529
- console.error(`appendSongToHls error [${streamId}]:`, err.message);
530
- if (state) state.generating = false;
531
  }
532
  });
533
- return hlsMutex[streamId];
 
534
  }
535
 
536
  async function preGenerateNextSong(streamId) {
537
  const stream = streams[streamId];
538
  if (!stream || stream.queue.length < 2) return;
539
- const next = stream.queue[1];
540
- if (next._hlsPregened || next._hlsPregenInProgress) return;
541
- next._hlsPregenInProgress = true;
 
 
542
  try {
543
- await appendSongToHls(streamId, next);
544
- next._hlsPregened = true;
545
  } catch (err) {
546
- next._hlsPregenInProgress = false;
547
- console.error(`Pre-gen failed for "${next.meta.title}":`, err.message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
  }
549
  }
550
 
551
  function advanceToNextSong(streamId, autoAdvance = false) {
552
  const stream = streams[streamId];
553
  if (!stream) return false;
 
 
554
  killActiveFFmpeg(streamId);
555
  const finishedSong = stream.queue.shift();
556
  const filePath = path.join(SONGS_DIR, finishedSong.fileName);
@@ -568,6 +864,7 @@ function advanceToNextSong(streamId, autoAdvance = false) {
568
  delete hlsState[streamId]; delete hlsMutex[streamId];
569
  }
570
  hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
 
571
  io.to(`stream:${streamId}`).emit('message', { type: 'stream_ended', message: 'Queue is empty.' });
572
  return false;
573
  }
@@ -580,6 +877,7 @@ function advanceToNextSong(streamId, autoAdvance = false) {
580
  stream.songStartTime = Date.now();
581
  stream.lastActivity = Date.now();
582
  stream.isActive = true;
 
583
  sendStreamUpdate(streamId);
584
  preGenerateNextSong(streamId).catch(console.error);
585
  } else {
@@ -617,12 +915,17 @@ function enqueueToStream(streamId, songInfo) {
617
  stream.lastActivity = Date.now();
618
  const position = stream.queue.length;
619
  if (!stream.isActive && position === 1 && !stream._showplayInProgress) {
620
- if (hlsState[streamId]) {
621
- const hlsDir = path.join(HLS_DIR, streamId);
622
- if (fs.existsSync(hlsDir)) { try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {} }
623
- delete hlsState[streamId]; delete hlsMutex[streamId];
 
 
 
 
 
 
624
  }
625
- hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
626
  stream.streamTimeOffset = 0;
627
  stream.songStartTime = null;
628
  stream.isActive = true;
@@ -764,14 +1067,19 @@ setInterval(async () => {
764
  const current = stream.queue[0];
765
  if (!current) continue;
766
  let songDuration;
767
- if (current.meta.duration > 0) songDuration = current.meta.duration;
768
- else if (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') songDuration = current._hlsEnd - current._hlsStart;
769
- else continue;
 
 
 
 
770
  if (songDuration < 5 || !stream.songStartTime) continue;
771
  const elapsed = (Date.now() - stream.songStartTime) / 1000;
772
  if (elapsed >= songDuration + 3) {
773
  if (stream._advancingFromSid === current._sid) continue;
774
  stream._advancingFromSid = current._sid;
 
775
  advanceToNextSong(streamId, true);
776
  if (stream._advancingFromSid === current._sid) delete stream._advancingFromSid;
777
  }
 
161
  });
162
 
163
  // ═══════════════════════════════════════════════════════════════════════════
164
+ // SHOWPLAY API β€” search by title name (no raw link needed)
165
+ // Called by main server when a user (who owns this constituent) adds a movie or episode.
166
  // Only the constituent's owner can trigger this.
167
+ //
168
+ // POST /constituent/add-movie β€” body: { streamId, title }
169
+ // Searches iktracks for the title, picks the first movie result, downloads it.
170
+ //
171
+ // POST /constituent/add-episode β€” body: { streamId, title, season, episode }
172
+ // Searches iktracks for the series, finds the matching S/E, downloads it.
173
  // ═══════════════════════════════════════════════════════════════════════════
174
 
175
+ const IKTRACKS_BASE = 'https://iktracks.vercel.app';
176
+
177
+ function spSeriesName(title) {
178
+ return (title || '').replace(/\s*\(?\d{4}\)?\s*$/, '').trim() || title;
179
+ }
180
 
181
+ function extractAllEpisodes(details) {
182
+ const allEps = [];
183
+ for (const season of (details.seasons || [])) {
184
+ for (const ep of (season.episodes || [])) {
185
+ if (ep && ep.downloadLink) {
186
+ allEps.push({ season: season.season, episode: ep.episode, downloadLink: ep.downloadLink });
187
+ }
188
+ }
189
  }
190
+ return allEps;
191
+ }
192
+
193
+ app.post('/constituent/add-movie', requireMainServer, async (req, res) => {
194
+ // Supports two modes:
195
+ // 1. { streamId, movieLink, movieTitle, thumbnail?, tmdbInfo? } β€” direct link from server.js
196
+ // 2. { streamId, title } β€” search by name (legacy / direct constituent use)
197
+ const { streamId, movieLink, movieTitle, title: titleOnly, thumbnail, tmdbInfo } = req.body;
198
 
199
+ if (!streamId) {
200
+ return res.status(400).json({ success: false, error: 'streamId is required' });
201
+ }
202
  if (streamId !== constituentConfig.ownerId) {
203
  return res.status(403).json({ success: false, error: 'Only the constituent owner can add movies to this server' });
204
  }
205
 
206
+ // ── Mode 1: direct link provided ───────────────────────────────────────────
207
+ if (movieLink && movieTitle) {
208
+ res.json({ success: true, message: 'Movie queued for download and encoding', streamId, title: movieTitle });
209
+ setImmediate(async () => {
210
+ try {
211
+ const result = await showplayEnqueueLink(streamId, movieLink, movieTitle, thumbnail || DEFAULT_ARTWORK, tmdbInfo || null);
212
+ console.log(`βœ… Movie added to stream ${streamId}: ${result.title}`);
213
+ } catch (err) {
214
+ console.error(`❌ Failed to add movie to stream ${streamId}:`, err.message);
215
+ }
216
+ });
217
+ return;
218
+ }
219
+
220
+ // ── Mode 2: search by title ────────────────────────────────────────────────
221
+ const title = titleOnly || movieTitle;
222
+ if (!title) {
223
+ return res.status(400).json({ success: false, error: 'Either (movieLink + movieTitle) or title is required' });
224
+ }
225
+
226
+ // Search for the title
227
+ let searchResults;
228
+ try {
229
+ const r = await axios.get(`${IKTRACKS_BASE}/search?query=${encodeURIComponent(title)}`, { timeout: 15000 });
230
+ searchResults = (r.data?.results || []).filter(r => r && r.link);
231
+ } catch (err) {
232
+ return res.status(500).json({ success: false, error: `Search failed: ${err.message}` });
233
+ }
234
+ if (!searchResults.length) {
235
+ return res.status(404).json({ success: false, error: `No results found for "${title}"` });
236
+ }
237
+
238
+ // Pick the first movie result (prefer type==='movie', fall back to first result)
239
+ const movieResult = searchResults.find(r => r.type === 'movie') || searchResults[0];
240
+
241
+ // Fetch details to get the download link
242
+ let details;
243
+ try {
244
+ const r = await axios.get(`${IKTRACKS_BASE}/details?url=${encodeURIComponent(movieResult.link)}`, { timeout: 15000 });
245
+ details = r.data;
246
+ if (!details) throw new Error('Empty details response');
247
+ } catch (err) {
248
+ return res.status(500).json({ success: false, error: `Details fetch failed: ${err.message}` });
249
+ }
250
+
251
+ if (details.type === 'series') {
252
+ return res.status(400).json({ success: false, error: 'This title is a series. Use /constituent/add-episode instead.' });
253
+ }
254
+
255
+ const link = details.downloadLinks?.[0]?.downloadLink;
256
+ if (!link) {
257
+ return res.status(404).json({ success: false, error: 'No download link found for this title' });
258
+ }
259
+
260
+ const pendingTitle = details.title || movieResult.title || title;
261
+ const pendingThumb = details.thumbnail || movieResult.thumbnail || DEFAULT_ARTWORK;
262
+
263
+ res.json({ success: true, message: 'Movie queued for download and encoding', streamId, title: pendingTitle });
264
 
 
265
  setImmediate(async () => {
266
  try {
267
+ const result = await showplayEnqueueLink(streamId, link, pendingTitle, pendingThumb, tmdbInfo || null);
268
  console.log(`βœ… Movie added to stream ${streamId}: ${result.title}`);
269
  } catch (err) {
270
  console.error(`❌ Failed to add movie to stream ${streamId}:`, err.message);
 
272
  });
273
  });
274
 
275
+ // POST /constituent/add-episode β€” body: { streamId, title, season, episode }
276
+ app.post('/constituent/add-episode', requireMainServer, async (req, res) => {
277
+ const { streamId, title, season, episode } = req.body;
278
+
279
+ if (!streamId || !title) {
280
+ return res.status(400).json({ success: false, error: 'streamId and title are required' });
281
+ }
282
+ if (season == null || episode == null) {
283
+ return res.status(400).json({ success: false, error: 'season and episode are required' });
284
+ }
285
+ if (streamId !== constituentConfig.ownerId) {
286
+ return res.status(403).json({ success: false, error: 'Only the constituent owner can add episodes to this server' });
287
+ }
288
+
289
+ // Search for the series
290
+ let searchResults;
291
+ try {
292
+ const r = await axios.get(`${IKTRACKS_BASE}/search?query=${encodeURIComponent(title)}`, { timeout: 15000 });
293
+ searchResults = (r.data?.results || []).filter(r => r && r.link);
294
+ } catch (err) {
295
+ return res.status(500).json({ success: false, error: `Search failed: ${err.message}` });
296
+ }
297
+ if (!searchResults.length) {
298
+ return res.status(404).json({ success: false, error: `No results found for "${title}"` });
299
+ }
300
+
301
+ // Pick best series result
302
+ const seriesResult = searchResults.find(r => r.type === 'series') || searchResults[0];
303
+
304
+ // Fetch details
305
+ let details;
306
+ try {
307
+ const r = await axios.get(`${IKTRACKS_BASE}/details?url=${encodeURIComponent(seriesResult.link)}`, { timeout: 15000 });
308
+ details = r.data;
309
+ if (!details) throw new Error('Empty details response');
310
+ } catch (err) {
311
+ return res.status(500).json({ success: false, error: `Details fetch failed: ${err.message}` });
312
+ }
313
+
314
+ const allEps = extractAllEpisodes(details);
315
+ if (!allEps.length) {
316
+ return res.status(404).json({ success: false, error: 'No downloadable episodes found for this title' });
317
+ }
318
+
319
+ const ep = allEps.find(e => String(e.season) === String(season) && String(e.episode) === String(episode));
320
+ if (!ep) {
321
+ return res.status(404).json({ success: false, error: `Episode S${season}E${episode} not found` });
322
+ }
323
+
324
+ const seriesName = spSeriesName(details.title || seriesResult.title || title);
325
+ const epLabel = `S${String(ep.season).padStart(2,'0')} E${String(ep.episode).padStart(2,'0')}`;
326
+ const pendingTitle = `${seriesName} β€’ ${epLabel}`;
327
+ const thumbnail = details.thumbnail || seriesResult.thumbnail || DEFAULT_ARTWORK;
328
+
329
+ res.json({ success: true, message: 'Episode queued for download and encoding', streamId, title: pendingTitle });
330
+
331
+ setImmediate(async () => {
332
+ try {
333
+ const result = await showplayEnqueueLink(streamId, ep.downloadLink, pendingTitle, thumbnail, null);
334
+ console.log(`βœ… Episode added to stream ${streamId}: ${result.title}`);
335
+ } catch (err) {
336
+ console.error(`❌ Failed to add episode to stream ${streamId}:`, err.message);
337
+ }
338
+ });
339
+ });
340
+
341
+ // POST /constituent/add-song β€” body: { streamId, songUrl, title, thumbnail? }
342
+ // Accepts a direct audio URL + title, downloads and enqueues without searching.
343
+ app.post('/constituent/add-song', requireMainServer, async (req, res) => {
344
+ const { streamId, songUrl, title, thumbnail } = req.body;
345
+
346
+ if (!streamId || !songUrl || !title) {
347
+ return res.status(400).json({ success: false, error: 'streamId, songUrl, and title are required' });
348
+ }
349
+ if (streamId !== constituentConfig.ownerId) {
350
+ return res.status(403).json({ success: false, error: 'Only the constituent owner can add songs to this server' });
351
+ }
352
+
353
+ res.json({ success: true, message: 'Song queued for download and encoding', streamId, title });
354
+
355
+ setImmediate(async () => {
356
+ try {
357
+ if (!streams[streamId]) {
358
+ streams[streamId] = { queue: [], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: false };
359
+ }
360
+
361
+ // Download the audio
362
+ const fileName = crypto.randomUUID() + '.mp3';
363
+ const filePath = require('path').join(SONGS_DIR, fileName);
364
+ const writer = require('fs').createWriteStream(filePath);
365
+ const response = await axios({ url: songUrl, method: 'GET', responseType: 'stream', httpsAgent: httpsAgentNoVerify });
366
+ response.data.pipe(writer);
367
+ await new Promise((resolve, reject) => {
368
+ writer.on('finish', resolve);
369
+ writer.on('error', (e) => { writer.destroy(); reject(e); });
370
+ response.data.on('error', reject);
371
+ });
372
+
373
+ const mediaMeta = await getAudioMeta(filePath);
374
+ const songInfo = {
375
+ fileName,
376
+ meta: {
377
+ title,
378
+ thumbnail: thumbnail || DEFAULT_ARTWORK,
379
+ duration: mediaMeta.duration || 0,
380
+ views: 'N/A',
381
+ published: 'N/A',
382
+ source: songUrl,
383
+ videoUrl: null,
384
+ },
385
+ };
386
+ enqueueToStream(streamId, songInfo);
387
+ console.log(`βœ… Song added to stream ${streamId}: ${title}`);
388
+ } catch (err) {
389
+ console.error(`❌ Failed to add song to stream ${streamId}:`, err.message);
390
+ }
391
+ });
392
+ });
393
+
394
  // ─── Queue status for a stream ────────────────────────────────────────────────
395
  app.get('/constituent/queue/:streamId', requireMainServer, (req, res) => {
396
  const { streamId } = req.params;
 
566
  const state = hlsState[streamId];
567
  if (!state || !state.segments.length) return null;
568
  const segs = state.segments;
569
+ let startIdx = -1;
570
  for (let i = 0; i < segs.length; i++) {
571
  if (segs[i].streamEnd > elapsed) { startIdx = i; break; }
572
  }
573
+ if (startIdx === -1) return null;
574
+ const window = segs.slice(startIdx, startIdx + HLS_PLAYLIST_WINDOW);
575
+ const mediaSeq = state.mediaSeq + startIdx;
576
+ const lines = ['#EXTM3U','#EXT-X-VERSION:3','#EXT-X-TARGETDURATION:10',`#EXT-X-MEDIA-SEQUENCE:${mediaSeq}`];
577
+ let prevSid = null;
 
 
 
578
  for (const seg of window) {
579
+ if (prevSid !== null && seg.ownerSid && seg.ownerSid !== prevSid) {
580
+ lines.push('#EXT-X-DISCONTINUITY');
581
+ }
582
+ prevSid = seg.ownerSid || prevSid;
583
  lines.push(`#EXTINF:${seg.duration.toFixed(6)},`);
584
  lines.push(seg.uri);
585
  }
 
616
  }
617
 
618
  function watchForSegments(streamId, dir, segPrefix, songHlsStart, onFirstSeg, ownerSid, state) {
619
+ let cursor = songHlsStart, firstFlushed = false;
620
+ const stitched = new Set();
621
  const playlistPath = path.join(dir, segPrefix + '.m3u8');
622
+ let pollCount = 0;
623
+ console.log(`πŸ‘ watchForSegments created: ownerSid=${ownerSid?.slice(0,8)} songHlsStart=${songHlsStart} playlistPath=${playlistPath}`);
624
 
625
+ const flush = () => {
626
+ pollCount++;
627
  const entries = parseM3u8Durations(playlistPath);
628
+ if (pollCount <= 3 || entries.length > 0) {
629
+ console.log(`πŸ‘ watch poll #${pollCount} [${ownerSid?.slice(0,8)}]: playlist=${fs.existsSync(playlistPath)} entries=${entries.length} stitched=${stitched.size} firstFlushed=${firstFlushed}`);
630
+ }
631
  for (const { file, dur } of entries) {
632
+ if (stitched.has(file)) continue;
633
  const segPath = path.join(dir, file);
634
+ try { if (fs.statSync(segPath).size < 188) continue; } catch { continue; }
635
+ stitched.add(file);
636
  const seg = { uri: `/hls/${streamId}/${file}`, _path: segPath, streamStart: cursor, streamEnd: cursor + dur, duration: dur, ownerSid };
 
 
637
  cursor += dur;
638
+ state.segments.push(seg);
639
+ state.totalDuration = cursor;
640
  if (!firstFlushed) {
641
  firstFlushed = true;
642
+ state.generating = false;
643
+ if (streams[streamId]?.queue.length > 0) {
644
+ const q0 = streams[streamId].queue[0];
645
+ const sidMatch = ownerSid ? q0._sid === ownerSid : true;
646
+ const startMatch = typeof q0._hlsStart === 'number' && songHlsStart === q0._hlsStart;
647
+ console.log(`πŸ”‘ Ownership check: sid=${q0._sid?.slice(0,8)}==${ownerSid?.slice(0,8)}:${sidMatch} hlsStart=${q0._hlsStart}==${songHlsStart}:${startMatch}`);
648
+ if (sidMatch && startMatch) {
649
+ streams[streamId].songStartTime = Date.now();
650
+ console.log(`⏱️ songStartTime reset for "${q0.meta.title}" [${q0._sid}] (first segment ready)`);
651
+ } else if (sidMatch && q0._hlsStart === undefined) {
652
+ // brief window before _hlsStart is set β€” harmless
653
+ } else {
654
+ console.log(`⚠️ watchForSegments ownership mismatch β€” skipping songStartTime reset. watcher=[${ownerSid}@${songHlsStart}] queue[0]=[${q0._sid}@${q0._hlsStart}]`);
655
+ }
656
  }
657
+ if (onFirstSeg) onFirstSeg();
658
  }
659
  }
660
+ };
661
+
662
+ let lastEntryCount = -1;
663
+ let stablePolls = 0;
664
+ const STABLE_NEEDED = 3;
665
 
666
+ const iv = setInterval(() => {
667
+ flush();
668
+ const entries = parseM3u8Durations(playlistPath);
669
  if (entries.length === lastEntryCount && !activeFFmpeg[streamId]) {
670
+ stablePolls++;
671
+ if (stablePolls >= STABLE_NEEDED) {
672
+ console.log(`πŸ›‘ watchForSegments auto-stop [${ownerSid?.slice(0,8)}]: stable for ${STABLE_NEEDED} polls, FFmpeg done`);
673
+ clearInterval(iv);
674
+ }
675
+ } else {
676
+ stablePolls = 0;
677
+ lastEntryCount = entries.length;
678
+ }
679
+ }, 800);
680
+ const markDone = () => { flush(); clearInterval(iv); return cursor; };
681
+ return { stop: () => clearInterval(iv), markDone };
682
  }
683
 
684
  async function generateSegmentsForSong(streamId, songInfo, isVideo, state) {
685
+ const dir = ensureHlsDir(streamId);
686
+ const songPath = path.join(SONGS_DIR, songInfo.fileName);
687
+ const segPrefix = `seg_${streamId}_${Date.now()}`;
 
 
 
 
 
 
688
 
689
+ console.log(`🎬 FFmpeg starting: ${songPath} isVideo=${isVideo}`);
690
+ if (!fs.existsSync(songPath)) throw new Error(`Source file missing: ${songPath}`);
691
+ const fileStat = fs.statSync(songPath);
692
+ if (fileStat.size === 0) throw new Error('Source file is empty');
693
+ console.log(`πŸ“ Source file: ${(fileStat.size / 1024 / 1024).toFixed(1)}MB`);
694
 
695
+ const segPattern = path.join(dir, segPrefix + '_%03d.ts');
696
+ const playlistPath = path.join(dir, segPrefix + '.m3u8');
697
+ const songHlsStart = state.totalDuration;
698
+ console.log(`🎯 segPrefix=${segPrefix} songHlsStart=${songHlsStart} ownerSid=${songInfo._sid?.slice(0,8)}`);
 
699
 
700
+ return new Promise((resolve, reject) => {
701
  const cmd = ffmpeg(songPath);
702
+ if (isVideo) {
703
+ cmd.outputOptions([
704
+ '-map','0:v:0','-map','0:a:0',
705
+ '-c:v','libx264','-preset','ultrafast','-crf','28',
706
+ '-profile:v','main','-level','3.1','-pix_fmt','yuv420p',
707
+ '-vf','scale=854:480',
708
+ '-c:a','aac','-b:a','128k',
709
+ '-f','segment','-segment_time','8',
710
+ '-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts',
711
+ ]);
712
  } else {
713
+ cmd.outputOptions(['-vn','-c:a','aac','-b:a','128k','-f','segment','-segment_time','8','-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts']);
 
 
714
  }
715
+ let watcher = null;
716
+ cmd.output(segPattern)
717
+ .on('start', () => {
718
+ activeFFmpeg[streamId] = cmd;
719
+ console.log(`🎬 FFmpeg process started [${streamId}] gen=${hlsGeneration[streamId]}`);
720
+ watcher = watchForSegments(streamId, dir, segPrefix, songHlsStart, () => {
721
+ console.log(`⚑ First segment ready for stream ${streamId}`);
722
+ sendStreamUpdate(streamId);
723
+ }, songInfo._sid, state);
724
+ })
725
+ .on('stderr', line => {
726
+ if (line.includes('Error') || line.includes('error') || line.includes('Invalid')) {
727
+ console.error(`FFmpeg stderr: ${line}`);
728
+ }
729
+ })
730
+ .on('end', () => {
731
+ console.log(`βœ… FFmpeg done for ${streamId}`);
732
+ delete activeFFmpeg[streamId];
733
+ if (!watcher) { resolve(0); return; }
734
+ const finalCursor = watcher.markDone();
735
+ console.log(`πŸ“ Final cursor from playlist: ${finalCursor.toFixed(3)}s`);
736
+ state.totalDuration = finalCursor;
737
+ try { fs.unlinkSync(playlistPath); } catch {}
738
+ resolve(finalCursor);
739
+ })
740
+ .on('error', (err) => {
741
+ console.log(`πŸ’₯ FFmpeg error for ${streamId}: ${err.message}`);
742
+ delete activeFFmpeg[streamId];
743
+ if (err.message && (err.message.includes('SIGKILL') || err.message.includes('killed'))) {
744
+ console.log(`⚑ FFmpeg killed cleanly for ${streamId} (skip)`);
745
+ if (watcher) watcher.stop();
746
+ resolve(0);
747
+ return;
748
+ }
749
+ console.error(`❌ FFmpeg error for ${streamId}:`, err.message);
750
+ if (watcher) watcher.stop();
751
+ reject(err);
752
+ })
753
+ .run();
754
  });
755
  }
756
 
757
  async function appendSongToHls(streamId, songInfo) {
758
+ if (!hlsState[streamId]) {
759
+ hlsState[streamId] = { mediaSeq: 0, segments: [], totalDuration: 0, generating: true };
760
+ console.log(`πŸ“¦ appendSongToHls: created fresh hlsState for ${streamId}`);
761
+ }
762
+ const myGeneration = hlsGeneration[streamId] || 0;
763
+ const prev = hlsMutex[streamId] || Promise.resolve();
764
+ console.log(`πŸ“Œ appendSongToHls queued: "${songInfo.meta.title}" [${songInfo._sid?.slice(0,8)}] gen=${myGeneration}`);
765
+ const next = prev.then(async () => {
766
+ const currentGen = hlsGeneration[streamId] || 0;
767
+ if (currentGen !== myGeneration) {
768
+ console.log(`⏩ Skipping stale appendSongToHls for "${songInfo.meta.title}" (gen ${myGeneration} vs ${currentGen})`);
769
+ return;
770
+ }
771
+ const isVideo = !!(songInfo.meta && songInfo.meta.videoUrl);
772
+ const state = hlsState[streamId];
773
+ if (!state) {
774
+ console.log(`⏩ Skipping appendSongToHls for "${songInfo.meta.title}" β€” hlsState gone`);
775
+ return;
776
  }
 
777
  state.generating = true;
778
+ songInfo._hlsStart = state.totalDuration;
779
+ console.log(`πŸ“ _hlsStart set to ${songInfo._hlsStart.toFixed(2)}s for "${songInfo.meta.title}"`);
780
  try {
781
+ const finalCursor = await generateSegmentsForSong(streamId, songInfo, isVideo, state);
782
+ if (typeof finalCursor === 'number' && finalCursor > 0) {
783
+ songInfo._hlsEnd = finalCursor;
784
+ const actualDuration = finalCursor - songInfo._hlsStart;
785
+ if (actualDuration > 0 && Math.abs(actualDuration - (songInfo.meta.duration || 0)) > 30) {
786
+ console.log(`πŸ“ Correcting meta.duration for "${songInfo.meta.title}": ${(songInfo.meta.duration || 0).toFixed(1)}s β†’ ${actualDuration.toFixed(1)}s`);
787
+ songInfo.meta.duration = actualDuration;
788
+ }
789
+ songInfo._hlsDurationTrusted = true;
790
+ } else {
791
+ songInfo._hlsEnd = state.totalDuration;
792
+ console.log(`⚑ Encode killed for "${songInfo.meta.title}" β€” hlsEnd set to ${songInfo._hlsEnd?.toFixed(2)}s`);
793
+ }
794
+ state.generating = false;
795
+ console.log(`πŸ“Ί HLS done for "${songInfo.meta.title}": hlsStart=${songInfo._hlsStart?.toFixed(2)}s hlsEnd=${songInfo._hlsEnd?.toFixed(2)}s segs=${state.segments.length}`);
796
+ const finalGen = hlsGeneration[streamId] || 0;
797
+ const liveStream = streams[streamId];
798
+ if (finalGen === myGeneration && liveStream && liveStream.queue[0]?._sid === songInfo._sid) {
799
+ if (!liveStream.songStartTime) {
800
+ liveStream.songStartTime = Date.now();
801
+ console.log(`⏱️ songStartTime set post-encode for "${songInfo.meta.title}" [${songInfo._sid}]`);
802
+ sendStreamUpdate(streamId);
803
+ }
804
+ preGenerateNextSong(streamId).catch(console.error);
805
+ }
806
  } catch (err) {
807
+ console.error(`HLS generation failed for stream ${streamId}:`, err);
808
+ if (hlsState[streamId]) hlsState[streamId].generating = false;
809
  }
810
  });
811
+ hlsMutex[streamId] = next;
812
+ return next;
813
  }
814
 
815
  async function preGenerateNextSong(streamId) {
816
  const stream = streams[streamId];
817
  if (!stream || stream.queue.length < 2) return;
818
+ const nextSong = stream.queue[1];
819
+ if (!nextSong || nextSong._hlsPregened || nextSong._hlsPregenInProgress) return;
820
+ nextSong._hlsPregenInProgress = true;
821
+ const sid = nextSong._sid;
822
+ console.log(`πŸ”„ Pre-generating HLS for next: ${nextSong.meta.title} [${sid}]`);
823
  try {
824
+ await appendSongToHls(streamId, nextSong);
 
825
  } catch (err) {
826
+ nextSong._hlsPregenInProgress = false;
827
+ console.error(`Pre-gen failed for "${nextSong.meta.title}":`, err.message);
828
+ return;
829
+ }
830
+ const streamNow = streams[streamId];
831
+ const stillQueued = streamNow && streamNow.queue.some(s => s._sid === sid);
832
+ const encodingFinished = typeof nextSong._hlsEnd === 'number' && typeof nextSong._hlsStart === 'number' && nextSong._hlsEnd > nextSong._hlsStart;
833
+ if (stillQueued && encodingFinished) {
834
+ nextSong._hlsPregened = true;
835
+ console.log(`βœ… Pre-gen confirmed for "${nextSong.meta.title}" [${sid}]: hlsStart=${nextSong._hlsStart.toFixed(2)}s hlsEnd=${nextSong._hlsEnd.toFixed(2)}s`);
836
+ } else {
837
+ nextSong._hlsPregened = false;
838
+ nextSong._hlsPregenInProgress = false;
839
+ delete nextSong._hlsStart;
840
+ delete nextSong._hlsEnd;
841
+ console.log(`⚠️ Pre-gen invalidated for "${nextSong.meta.title}" [${sid}]`);
842
  }
843
  }
844
 
845
  function advanceToNextSong(streamId, autoAdvance = false) {
846
  const stream = streams[streamId];
847
  if (!stream) return false;
848
+ if (autoAdvance) stream._notifyOnStart = true;
849
+ else delete stream._notifyOnStart;
850
  killActiveFFmpeg(streamId);
851
  const finishedSong = stream.queue.shift();
852
  const filePath = path.join(SONGS_DIR, finishedSong.fileName);
 
864
  delete hlsState[streamId]; delete hlsMutex[streamId];
865
  }
866
  hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
867
+ console.log(`πŸ”„ Stream ${streamId} queue empty β€” HLS state reset for fresh start`);
868
  io.to(`stream:${streamId}`).emit('message', { type: 'stream_ended', message: 'Queue is empty.' });
869
  return false;
870
  }
 
877
  stream.songStartTime = Date.now();
878
  stream.lastActivity = Date.now();
879
  stream.isActive = true;
880
+ delete stream._notifyOnStart;
881
  sendStreamUpdate(streamId);
882
  preGenerateNextSong(streamId).catch(console.error);
883
  } else {
 
915
  stream.lastActivity = Date.now();
916
  const position = stream.queue.length;
917
  if (!stream.isActive && position === 1 && !stream._showplayInProgress) {
918
+ // Stream was idle/ended β€” ensure HLS state is fresh so this song starts at t=0.
919
+ if (!hlsState[streamId] || hlsState[streamId].totalDuration > 0) {
920
+ if (hlsState[streamId]) {
921
+ const hlsDir = path.join(HLS_DIR, streamId);
922
+ if (fs.existsSync(hlsDir)) {
923
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
924
+ }
925
+ delete hlsState[streamId]; delete hlsMutex[streamId];
926
+ }
927
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
928
  }
 
929
  stream.streamTimeOffset = 0;
930
  stream.songStartTime = null;
931
  stream.isActive = true;
 
1067
  const current = stream.queue[0];
1068
  if (!current) continue;
1069
  let songDuration;
1070
+ if (current._hlsDurationTrusted && typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1071
+ songDuration = current._hlsEnd - current._hlsStart;
1072
+ } else if (current.meta.duration > 0) {
1073
+ songDuration = current.meta.duration;
1074
+ } else if (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1075
+ songDuration = current._hlsEnd - current._hlsStart;
1076
+ } else continue;
1077
  if (songDuration < 5 || !stream.songStartTime) continue;
1078
  const elapsed = (Date.now() - stream.songStartTime) / 1000;
1079
  if (elapsed >= songDuration + 3) {
1080
  if (stream._advancingFromSid === current._sid) continue;
1081
  stream._advancingFromSid = current._sid;
1082
+ console.log(`⏭️ Auto-advance "${current.meta.title}": elapsed=${elapsed.toFixed(1)}s duration=${songDuration.toFixed(1)}s`);
1083
  advanceToNextSong(streamId, true);
1084
  if (stream._advancingFromSid === current._sid) delete stream._advancingFromSid;
1085
  }