/** * ======================================================== * Name: Flonnect Video to HLS / M3U8 Converter Engine [CommonJS] * Target: https://flonnect.com/media-tools/hls-converter * * Cara Download: * curl -sL "https://code.vamxapi.my.id/snippet/raw/flonnect-hls-converter" -o flonnect-hls-converter.js * * Cara Eksekusi: * node flonnect-hls-converter.js "/path/to/video.mp4" * node flonnect-hls-converter.js "https://example.com/video.mp4" * * Author: Vamz Spectre * Source: https://vamxapi.my.id * ======================================================== */ const fs = require('fs'); const path = require('path'); const os = require('os'); const { execFileSync } = require('child_process'); function formatBytes(bytes) { if (!bytes || bytes <= 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } function probeVideo(filePath) { try { const raw = execFileSync( 'ffprobe', [ '-v', 'error', '-show_entries', 'format=duration,size,bit_rate:stream=width,height,codec_name,codec_type', '-of', 'json', filePath ], { encoding: 'utf8' } ); const parsed = JSON.parse(raw); const streams = parsed.streams || []; const videoStream = streams.find((s) => s.codec_type === 'video') || {}; const audioStream = streams.find((s) => s.codec_type === 'audio') || {}; const duration = parseFloat(parsed.format?.duration || '0'); const size = parseInt(parsed.format?.size || '0', 10); return { duration_seconds: parseFloat(duration.toFixed(2)), width: videoStream.width || null, height: videoStream.height || null, resolution: videoStream.width && videoStream.height ? `${videoStream.width}x${videoStream.height}` : null, video_codec: videoStream.codec_name || 'unknown', audio_codec: audioStream.codec_name || 'none', size_bytes: size, size_formatted: formatBytes(size) }; } catch (err) { return { duration_seconds: null, video_codec: 'unknown', audio_codec: 'unknown', error: err.message }; } } async function downloadRemoteVideo(url) { const parsed = new URL(url); const ext = path.extname(parsed.pathname) || '.mp4'; const tempPath = path.join(os.tmpdir(), `flonnect_src_${Date.now()}${ext}`); const res = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0.0.0' } }); if (!res.ok) { throw new Error(`Gagal mengunduh remote video (${res.status}): ${url}`); } const arrayBuffer = await res.arrayBuffer(); fs.writeFileSync(tempPath, Buffer.from(arrayBuffer)); return tempPath; } async function convertVideoToHls(inputSource, options = {}) { let sourcePath = (inputSource || '').trim(); if (!sourcePath) { throw new Error('Input video (file path atau URL) wajib disertakan!'); } let isRemote = false; if (sourcePath.startsWith('http://') || sourcePath.startsWith('https://')) { isRemote = true; sourcePath = await downloadRemoteVideo(sourcePath); } else if (!fs.existsSync(sourcePath)) { throw new Error(`File video tidak ditemukan di: "${sourcePath}"`); } try { const videoInfo = probeVideo(sourcePath); const segmentTime = options.segmentTime || 4; const mode = options.mode || 'copy'; const createZip = options.createZip !== false; const baseName = path.basename(sourcePath, path.extname(sourcePath)); const outDir = options.outputDir || path.join(process.cwd(), `hls_${baseName}_${Date.now()}`); if (!fs.existsSync(outDir)) { fs.mkdirSync(outDir, { recursive: true }); } const playlistName = 'index.m3u8'; const playlistPath = path.join(outDir, playlistName); if (mode === 'adaptive' && videoInfo.height && videoInfo.height >= 480) { const ffmpegArgs = [ '-i', sourcePath, '-filter_complex', '[v:0]split=2[v1][v2];[v1]scale=w=1280:h=720:force_original_aspect_ratio=decrease[v1out];[v2]scale=w=854:h=480:force_original_aspect_ratio=decrease[v2out]', '-map', '[v1out]', '-c:v:0', 'libx264', '-crf:v:0', '23', '-preset:v:0', 'fast', '-map', 'a:0?', '-c:a:0', 'aac', '-b:a:0', '128k', '-map', '[v2out]', '-c:v:1', 'libx264', '-crf:v:1', '25', '-preset:v:1', 'fast', '-map', 'a:0?', '-c:a:1', 'aac', '-b:a:1', '96k', '-f', 'hls', '-hls_time', String(segmentTime), '-hls_playlist_type', 'vod', '-hls_segment_filename', path.join(outDir, 'v%v/segment%d.ts'), '-master_pl_name', 'master.m3u8', '-var_stream_map', 'v:0,a:0 v:1,a:1', path.join(outDir, 'v%v/prog_index.m3u8'), '-y' ]; execFileSync('ffmpeg', ffmpegArgs, { encoding: 'utf8', stdio: 'pipe' }); } else { const segmentPattern = path.join(outDir, 'segment_%03d.ts'); const ffmpegArgs = [ '-i', sourcePath, '-codec:', 'copy', '-start_number', '0', '-hls_time', String(segmentTime), '-hls_list_size', '0', '-f', 'hls', '-hls_segment_filename', segmentPattern, playlistPath, '-y' ]; try { execFileSync('ffmpeg', ffmpegArgs, { encoding: 'utf8', stdio: 'pipe' }); } catch { const reencodeArgs = [ '-i', sourcePath, '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-start_number', '0', '-hls_time', String(segmentTime), '-hls_list_size', '0', '-f', 'hls', '-hls_segment_filename', segmentPattern, playlistPath, '-y' ]; execFileSync('ffmpeg', reencodeArgs, { encoding: 'utf8', stdio: 'pipe' }); } } const allFiles = fs.readdirSync(outDir, { recursive: true }); const segments = allFiles.filter((f) => f.endsWith('.ts')); const playlists = allFiles.filter((f) => f.endsWith('.m3u8')); let zipPath = null; let zipSize = null; if (createZip) { zipPath = `${outDir}.zip`; try { execFileSync('zip', ['-r', zipPath, '.'], { cwd: outDir, encoding: 'utf8' }); if (fs.existsSync(zipPath)) { zipSize = fs.statSync(zipPath).size; } } catch {} } const mainM3u8 = playlists.includes('master.m3u8') ? path.join(outDir, 'master.m3u8') : playlistPath; return { status: true, source: isRemote ? inputSource : path.basename(inputSource), video_info: videoInfo, hls: { master_playlist: mainM3u8, playlist_files: playlists, segment_duration: segmentTime, total_segments: segments.length, segments_sample: segments.slice(0, 5), output_directory: outDir, zip_archive: zipPath, zip_size_formatted: zipSize ? formatBytes(zipSize) : null } }; } finally { if (isRemote && fs.existsSync(sourcePath)) { try { fs.unlinkSync(sourcePath); } catch {} } } } module.exports = { convertVideoToHls, probeVideo, formatBytes }; const cliArg = process.argv[2] ? process.argv[2].trim() : null; async function runCli() { if (!cliArg) { console.log( JSON.stringify( { status: false, message: 'Parameter video (file path atau URL) belum ditentukan.', usage: 'node flonnect-hls-converter.js [options]', options: [ '--time= Durasi per chunk TS (default: 4)', '--adaptive Aktifkan multi-bitrate HLS (720p/480p/360p)', '--no-zip Jangan kompres ke .zip' ], examples: [ 'node flonnect-hls-converter.js "./video.mp4"', 'node flonnect-hls-converter.js "https://files.catbox.moe/sample.mp4"', 'node flonnect-hls-converter.js "./video.mp4" --time=4 --adaptive' ] }, null, 2 ) ); process.exit(1); } const options = {}; for (let i = 3; i < process.argv.length; i++) { const arg = process.argv[i]; if (arg.startsWith('--time=')) { options.segmentTime = parseFloat(arg.split('=')[1]); } if (arg === '--adaptive') options.mode = 'adaptive'; if (arg === '--no-zip') options.createZip = false; } const res = await convertVideoToHls(cliArg, options); console.log(JSON.stringify(res, null, 2)); } if ( process.argv[1] && (process.argv[1].endsWith('flonnect-hls-converter.js') || process.argv[1].endsWith('flonnect-hls-converter.cjs')) ) { runCli().catch((err) => { console.error(JSON.stringify({ status: false, error: err.message }, null, 2)); process.exit(1); }); }