'use strict'; /* * poster-lagu-3d.js — Pembuat Poster Lagu Tiga Dimensi dalam SATU file. * 4 kartu pemutar musik 3D di sekeliling fotomu, karakter menimpa kartu, * cover otomatis dari Deezer/iTunes. * * Pasang: npm i @napi-rs/canvas (wajib, Node 18+) * npm i @gradio/client (opsional, buat efek karakter menimpa kartu lewat BRIA RMBG) * Font: taruh Poppins-Bold.ttf, Poppins-Medium.ttf, Poppins-Regular.ttf di folder ./fonts (opsional, * tanpa itu dipakai font sistem). * * Lewat terminal: * node poster-lagu-3d.js foto.jpg "blank ruangBria taylor swift" "raimu laode iqro" "about you the 1975" "good life g-eazy kehlani" * opsi: --nocut (tanpa efek karakter menimpa kartu) --out hasil.png * * Lewat kode: * const { buatPosterLagu } = require('./poster-lagu-3d'); * const png = await buatPosterLagu({ photo: fs.readFileSync('foto.jpg'), songs: ['blank ruangBria taylor swift', ...] }); * * Catatan: BRIA RMBG berlisensi non-komersial. Tidak ada API key / token yang tertanam di file ini. * Env opsional: POSTER_COVER_ORDER (deezer,itunes), POSTER_ITUNES_COUNTRIES (ID,US), BRIA_SPACE, BATAS_WAKTU_BRIA, HF_TOKEN (diawali hf_). */ const fs = require('fs'); const path = require('path'); const { createCanvas, loadImage, GlobalFonts, ImageData } = require('@napi-rs/canvas'); /* ================================================================== */ /* 1. CARI LAGU + COVER (Deezer / iTunes) */ /* ================================================================== */ const BATAS_WAKTU_NET = 15000; const AGEN_PENGGUNA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'; const SKOR_PAS = 0.6; // skor "cocok" const SKOR_MINIMAL = 0.45; // di bawah ini dianggap salah lagu const URUTAN_SUMBER = String(process.env.POSTER_COVER_ORDER || 'deezer,itunes').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean); const DAFTAR_NEGARA = String(process.env.POSTER_ITUNES_COUNTRIES || 'ID,US').split(',').map((x) => x.trim().toUpperCase()).filter(Boolean); const tidurSebentar = (batasMs) => new Promise((r) => setTimeout(r, batasMs)); /** "a\nb | c; d" -> ['a','b','c','d'] (maks 4). Satu baris saja -> pisah dengan koma. */ function uraikanDaftarLagu(text) { const t = String(text || '').trim(); const potonganTeks = /[\n|;]/.test(t) ? t.split(/[\n|;]+/) : t.split(/[,,]+/); const semuaJudul = potonganTeks.map((s) => s.replace(/^\s*\d{1,2}\s*[.)]\s*/, '').trim()).filter(Boolean); return { songs: semuaJudul.slice(0, 4), extra: Math.max(0, semuaJudul.length - 4) }; } const normalkanTeks = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, ' ').trim(); const pecahKata = (s) => normalkanTeks(s).split(' ').filter(Boolean); function jarakSuntingSatu(a, b) { if (Math.abs(a.length - b.length) > 1) return false; let i = 0, j = 0, dataPiksel = 0; while (i < a.length && j < b.length) { if (a[i] === b[j]) { i++; j++; continue; } if (++dataPiksel > 1) return false; if (a.length > b.length) i++; else if (a.length < b.length) j++; else { i++; j++; } } return dataPiksel + (a.length - i) + (b.length - j) <= 1; } function kataMirip(a, b) { if (a === b) return true; if (a.length >= 3 && b.length >= 3 && (a.startsWith(b) || b.startsWith(a))) return true; return a.length >= 4 && b.length >= 4 && jarakSuntingSatu(a, b); } const POLA_VERSI_LAIN = /karaoke|instrumental|tribute|made famous|lullaby|piano version|8d|slowed|sped up|nightcore/i; /** berapa kata input yang muncul di judul+artis hasil (urutan bebas, salah ketik kecil dimaafkan) */ function hitungKecocokan(query, title, artist, album = '') { const q = pecahKata(query), kolamKata = pecahKata(`${title} ${artist}`); if (!q.length) return 0; const sudahTerpakai = new Set(); let jumlahCocok = 0; for (const t of q) { const k = kolamKata.findIndex((p, i) => !sudahTerpakai.has(i) && kataMirip(t, p)); if (k >= 0) { sudahTerpakai.add(k); jumlahCocok++; } } let s = jumlahCocok / q.length; if (POLA_VERSI_LAIN.test(`${title} ${album}`) && !POLA_VERSI_LAIN.test(query)) s -= 0.2; return Math.max(0, s); } async function ambilJson(alamatHasil) { const r = await fetch(alamatHasil, { signal: AbortSignal.timeout(BATAS_WAKTU_NET), headers: { 'User-Agent': AGEN_PENGGUNA } }); if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); } const cekBerkasGambar = (b) => b.length > 1000 && ((b[0] === 0xff && b[1] === 0xd8) || b.readUInt32BE(0) === 0x89504e47); async function unduhGambar(daftarUrl) { for (const u of daftarUrl.filter(Boolean)) { try { const r = await fetch(u, { signal: AbortSignal.timeout(BATAS_WAKTU_NET), headers: { 'User-Agent': AGEN_PENGGUNA } }); if (!r.ok) continue; const b = Buffer.from(await r.arrayBuffer()); if (cekBerkasGambar(b)) return b; } catch { /* coba URL berikutnya */ } } return null; } // iTunes dibatasi ~20 permintaan/menit: antre dengan jeda minimal let ekorAntreItunes = Promise.resolve(); function ambilSlotItunes() { const run = ekorAntreItunes.then(() => tidurSebentar(3200)); ekorAntreItunes = run.catch(() => {}); return run; } async function cariDiDeezer(q) { const j = await ambilJson(`https://api.deezer.com/search?${new URLSearchParams({ q, limit: '6' })}`); if (j.error) throw new Error('Deezer: ' + (j.error.message || j.error.type)); return (j.data || []).map((x) => ({ title: x.title, artist: x.artist && x.artist.name, album: x.album && x.album.title, duration: x.duration || 0, covers: [x.album && x.album.cover_xl, x.album && x.album.cover_big, x.album && x.album.cover_medium], src: 'Deezer', })); } async function cariDiItunes(q, negara) { await ambilSlotItunes(); const j = await ambilJson(`https://itunes.apple.com/search?${new URLSearchParams({ term: q, entity: 'dataLagu', limit: '6', negara })}`); return (j.results || []).map((x) => ({ title: x.trackName, artist: x.artistName, album: x.collectionName, duration: x.trackTimeMillis ? Math.round(x.trackTimeMillis / 1000) : 0, covers: x.artworkUrl100 ? [x.artworkUrl100.replace(/\d+x\d+bb/, '1200x1200bb'), x.artworkUrl100.replace(/\d+x\d+bb/, '600x600bb')] : [], src: 'iTunes ' + negara, })); } const ambilTerbaik = (q, hasilCari) => hasilCari.map((it, i) => ({ ...it, score: hitungKecocokan(q, it.title, it.artist, it.album) - i * 0.001 })).sort((a, b) => b.score - a.score)[0] || null; /** @returns {Promise<{title,artist,duration,cover:Buffer|null,source,found,hitungKecocokan}>} — gagal semua -> cover null (kartu pakai gradasi) */ async function temukanLagu(query) { let cadanganTerbaik = null; const daftarUpaya = []; for (const s of URUTAN_SUMBER) { if (s === 'deezer') daftarUpaya.push(() => cariDiDeezer(query)); else if (s === 'itunes') for (const c of DAFTAR_NEGARA) daftarUpaya.push(() => cariDiItunes(query, c)); } for (const run of daftarUpaya) { let hasilCari; try { hasilCari = await run(); } catch (e) { console.error('[poster-lagu] cari lagu gagal:', e.message); continue; } const b = ambilTerbaik(query, hasilCari); if (!b || b.score < SKOR_MINIMAL) continue; const cover = await unduhGambar(b.covers); if (b.score >= SKOR_PAS && cover) return { title: b.title, artist: b.artist || '', duration: b.duration, cover, source: b.src, found: true, score: +b.score.toFixed(2) }; if (!cadanganTerbaik || b.score > cadanganTerbaik.score) cadanganTerbaik = { ...b, cover }; } if (cadanganTerbaik) return { title: cadanganTerbaik.title, artist: cadanganTerbaik.artist || '', duration: cadanganTerbaik.duration, cover: cadanganTerbaik.cover, source: cadanganTerbaik.src, found: true, score: +cadanganTerbaik.score.toFixed(2) }; return { title: query, artist: '', duration: 0, cover: null, source: '-', found: false, score: 0 }; } /* ================================================================== */ /* 2. HAPUS BACKGROUND (BRIA RMBG 2.0, cadangan 1.4) */ /* ================================================================== */ const BRIA_PILIHAN = (process.env.BRIA_SPACE || '').trim(); const RUANG_BRIA = BRIA_PILIHAN ? [BRIA_PILIHAN] : ['briaai/BRIA-RMBG-2.0', 'briaai/BRIA-RMBG-1.4']; const jalurApiBria = (s) => (process.env.BRIA_API || (/2\.0/.test(s) ? '/image' : '/run')).trim(); const BATAS_WAKTU_BRIA = Number(process.env.BRIA_TIMEOUT) || 90000; const UKURAN_MAKS_MASUK = 10 * 1024 * 1024, UKURAN_MAKS_KELUAR = 20 * 1024 * 1024; const TANDA_PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]); const HOST_BRIA = ['hf.space', 'huggingface.co', 'hf.co']; const hostBoleh = (h) => HOST_BRIA.some((x) => h === x || h.endsWith('.' + x)); let ruangBriaTerpakai = ''; const labelBria = () => (ruangBriaTerpakai ? 'BRIA RMBG ' + (ruangBriaTerpakai.match(/(\d+\.\d+)\s*$/) || [, '?'])[1] : 'BRIA RMBG'); function beriBatasWaktu(janjiProses, batasMs, namaProses) { let t; return Promise.race([janjiProses, new Promise((_, rej) => { t = setTimeout(() => rej(new Error(`${namaProses} kelamaan merespons (>${Math.round(batasMs / 1000)} dtk)`)), batasMs); })]).finally(() => clearTimeout(t)); } async function unduhDariBria(alamatHasil) { let nilaiBerjalan = alamatHasil; for (let jumlahLompat = 0; jumlahLompat <= 3; jumlahLompat++) { let u; try { u = new URL(nilaiBerjalan); } catch { throw new Error('alamat hasil BRIA tidak valid'); } if (u.protocol !== 'https:' || !hostBoleh(u.hostname.toLowerCase())) throw new Error(`alamat hasil BRIA ditolak (${u.hostname})`); const res = await fetch(u.href, { redirect: 'manual', signal: AbortSignal.timeout(45000) }); if (res.status >= 300 && res.status < 400 && res.headers.get('location')) { nilaiBerjalan = new URL(res.headers.get('location'), u.href).href; continue; } if (!res.ok) throw new Error(`unduh hasil BRIA gagal (HTTP ${res.status})`); const penyanggaHasil = Buffer.from(await res.arrayBuffer()); if (penyanggaHasil.length > UKURAN_MAKS_KELUAR) throw new Error('hasil BRIA terlalu besar'); return penyanggaHasil; } throw new Error('terlalu banyak redirect dari server BRIA'); } /** @returns {Promise} PNG transparan */ async function potongLatar(gambarMasukan, mime = 'image/jpeg') { if (!Buffer.isBuffer(gambarMasukan) || !gambarMasukan.length) throw new Error('Input harus berupa gambar.'); if (gambarMasukan.length > UKURAN_MAKS_MASUK) throw new Error('Gambar terlalu besar (maks 10 MB).'); let modulGradio; try { modulGradio = await import('@gradio/client'); } catch { throw new Error('modul "@gradio/client" belum terpasang (npm i @gradio/client)'); } const Client = modulGradio.Client || (modulGradio.default && modulGradio.default.Client); if (!Client) throw new Error('modul "@gradio/client" tidak punya Client (versi tidak cocok)'); const opsiKlien = {}; const tokenAkses = String(process.env.HF_TOKEN || '').trim(); if (/^hf_/.test(tokenAkses)) opsiKlien.hf_token = tokenAkses; let dataHasilBria, galatTerakhir; for (const ruangBria of RUANG_BRIA) { try { dataHasilBria = await beriBatasWaktu((async () => { const client = await Client.connect(ruangBria, opsiKlien); const result = await client.predict(jalurApiBria(ruangBria), { image: new Blob([new Uint8Array(gambarMasukan)], { type: mime }) }); const data = Array.isArray(result && result.data) ? result.data : []; return data[1] && data[1].url ? data[1] : data.find((dataPiksel) => dataPiksel && dataPiksel.url && /\.png(\?|$)/i.test(dataPiksel.url)); })(), BATAS_WAKTU_BRIA, 'BRIA'); if (dataHasilBria && dataHasilBria.url) { ruangBriaTerpakai = ruangBria; break; } galatTerakhir = new Error('BRIA tidak mengembalikan gambar transparan'); } catch (e) { galatTerakhir = e; console.error(`[bria] ${ruangBria} gagal: ${String((e && e.message) || e).slice(0, 120)}`); } } if (!(dataHasilBria && dataHasilBria.url)) throw new Error(String((galatTerakhir && galatTerakhir.message) || galatTerakhir).slice(0, 200)); const dataHasil = await unduhDariBria(dataHasilBria.url); if (!dataHasil.subarray(0, 4).equals(TANDA_PNG)) throw new Error('hasil BRIA bukan gambar PNG'); return dataHasil; } /* ================================================================== */ /* 3. RENDER POSTER */ /* ================================================================== */ const FOLDER_FONT = [path.join(__dirname, 'fonts'), '/usr/share/fonts/truetype/liberation', '/usr/share/fonts/truetype/dejavu']; function daftarkanFontKeluarga(namaFont, daftarNamaFont) { for (const n of daftarNamaFont) for (const dataPiksel of FOLDER_FONT) { const f = path.join(dataPiksel, n); if (fs.existsSync(f)) { try { GlobalFonts.registerFromPath(f, namaFont); return true; } catch { /* coba berikutnya */ } } } return false; } daftarkanFontKeluarga('PosTebal', ['Poppins-Bold.ttf', 'LiberationSans-Bold.ttf', 'DejaVuSans-Bold.ttf']); daftarkanFontKeluarga('PosSedang', ['Poppins-Medium.ttf', 'LiberationSans-Regular.ttf', 'DejaVuSans.ttf']); daftarkanFontKeluarga('PosBiasa', ['Poppins-Regular.ttf', 'LiberationSans-Regular.ttf', 'DejaVuSans.ttf']); /* Pose 4 kartu (kanvas 1080x1920): bidang 3D diputar (yaw/pitch/roll, derajat) lalu diproyeksikan ber-perspektif. * front: true -> kartu digambar DI DEPAN karakter. Posisi ini acuan untuk foto uji; kalau ada karakter, posisi * digeser/diskalakan otomatis mengikuti letak & tinggi karakter (autoFit). */ const POSE_AWAL = [ { cx: 274, cy: 494, yaw: -18, pitch: -4, roll: 4, scale: 0.82 }, // kiri atas { cx: 842, cy: 434, yaw: 18, pitch: -4, roll: -3, scale: 0.84 }, // kanan atas (lebih tinggi) { cx: 258, cy: 1216, yaw: -18, pitch: 5, roll: 3, scale: 0.82 }, // kiri bawah { cx: 850, cy: 1241, yaw: 18, pitch: 5, roll: -4, scale: 0.84 } // kanan bawah (lebih turun) ]; const ACUAN_KARAKTER = { cx: 595, top: 260, h: 1390 }; // acuan letak karakter di foto uji const PANJANG_FOKUS = 1700; const KETEBALAN = 16; function pembangkitAcak(a) { return function () { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } const hashTeks = (s) => { let h = 2166136261; for (const c of String(s)) { h ^= c.charCodeAt(0); h = Math.imul(h, 16777619); } return h >>> 0; }; const formatWaktu = (sec) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`; function jalurKotakBulat(g, x, y, w, h, r) { g.beginPath(); g.moveTo(x + r, y); g.arcTo(x + w, y, x + w, y + h, r); g.arcTo(x + w, y + h, x, y + h, r); g.arcTo(x, y + h, x, y, r); g.arcTo(x, y, x + w, y, r); g.closePath(); } function potongTeksPas(g, text, maxW) { text = String(text || ''); if (g.measureText(text).width <= maxW) return text; while (text.length > 1 && g.measureText(text + '…').width > maxW) text = text.slice(0, -1); return text.trimEnd() + '…'; } function gambarPasPenuh(g, gambarMasukan, x, y, w, h) { const s = Math.max(w / gambarMasukan.width, h / gambarMasukan.height); const sw = w / s, sh = h / s; g.drawImage(gambarMasukan, (gambarMasukan.width - sw) / 2, (gambarMasukan.height - sh) / 2, sw, sh, x, y, w, h); } async function muatGambar(titikAsal) { if (!titikAsal) return null; try { return await loadImage(titikAsal); } catch { return null; } } function sampulPengganti(title, artist) { const pengacak = pembangkitAcak(hashTeks(title + artist)); const ronaSatu = Math.floor(pengacak() * 360), ronaDua = (ronaSatu + 40 + Math.floor(pengacak() * 120)) % 360; const c = createCanvas(600, 600), g = c.getContext('2d'); const gr = g.createLinearGradient(0, 0, 600, 600); gr.addColorStop(0, `hsl(${ronaSatu},70%,48%)`); gr.addColorStop(1, `hsl(${ronaDua},75%,22%)`); g.fillStyle = gr; g.fillRect(0, 0, 600, 600); for (let i = 0; i < 5; i++) { g.beginPath(); g.arc(pengacak() * 600, pengacak() * 600, 70 + pengacak() * 190, 0, Math.PI * 2); g.fillStyle = `hsla(${(ronaSatu + pengacak() * 90) % 360},80%,65%,${0.10 + pengacak() * 0.14})`; g.fill(); } g.fillStyle = 'rgba(255,255,255,0.92)'; g.font = '700 64px PosTebal'; g.textBaseline = 'alphabetic'; const words = String(title).split(' '); let line = ''; const lines = []; for (const w of words) { const t = line ? line + ' ' + w : w; if (g.measureText(t).width > 500 && line) { lines.push(line); line = w; } else line = t; } lines.push(line); const start = 540 - (lines.length - 1) * 70; lines.slice(-3).forEach((l, i) => g.fillText(l, 50, start + i * 70)); return c; } function ikonHati(g, cx, cy, s, a = 0.85) { const t = s / 2; g.beginPath(); g.moveTo(cx, cy + t * 0.95); g.bezierCurveTo(cx - t * 2.1, cy - t * 0.1, cx - t * 1.0, cy - t * 1.55, cx, cy - t * 0.45); g.bezierCurveTo(cx + t * 1.0, cy - t * 1.55, cx + t * 2.1, cy - t * 0.1, cx, cy + t * 0.95); g.closePath(); g.lineWidth = 2.6; g.lineJoin = 'round'; g.strokeStyle = `rgba(255,255,255,${a})`; g.stroke(); } function ikonSegitiga(g, x, y, w, h, dir) { g.beginPath(); if (dir > 0) { g.moveTo(x, y); g.lineTo(x + w, y + h / 2); g.lineTo(x, y + h); } else { g.moveTo(x + w, y); g.lineTo(x, y + h / 2); g.lineTo(x + w, y + h); } g.closePath(); g.lineJoin = 'round'; g.lineWidth = 4; g.fill(); g.stroke(); } function ikonPengeras(g, x, y, a = 0.75) { g.fillStyle = `rgba(255,255,255,${a})`; g.strokeStyle = `rgba(255,255,255,${a})`; g.beginPath(); g.moveTo(x, y - 5); g.lineTo(x + 6, y - 5); g.lineTo(x + 13, y - 11); g.lineTo(x + 13, y + 11); g.lineTo(x + 6, y + 5); g.lineTo(x, y + 5); g.closePath(); g.fill(); g.lineWidth = 2.4; g.lineCap = 'round'; g.beginPath(); g.arc(x + 14, y, 7, -0.9, 0.9); g.stroke(); g.beginPath(); g.arc(x + 14, y, 13, -0.9, 0.9); g.stroke(); } /* ---- 1 kartu (datar) ---- */ const LEBAR_KARTU = 420, TINGGI_KARTU = 700, MARGIN_KARTU = 4, RADIUS_SUDUT = 46; function buatKartuLagu(dataLagu, cover, pengacak, skalaRender = 2) { const c = createCanvas((LEBAR_KARTU + MARGIN_KARTU * 2) * skalaRender, (TINGGI_KARTU + MARGIN_KARTU * 2) * skalaRender), g = c.getContext('2d'); g.scale(skalaRender, skalaRender); g.translate(MARGIN_KARTU, MARGIN_KARTU); const gradasiBadan = g.createLinearGradient(0, 0, 0, TINGGI_KARTU); gradasiBadan.addColorStop(0, 'rgba(66,68,77,0.98)'); gradasiBadan.addColorStop(1, 'rgba(26,27,32,0.98)'); jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.fillStyle = gradasiBadan; g.fill(); g.save(); g.shadowColor = 'rgba(0,0,0,0.5)'; g.shadowBlur = 18; g.shadowOffsetY = 6; jalurKotakBulat(g, 30, 30, 360, 360, 30); g.fillStyle = '#111'; g.fill(); g.restore(); g.save(); jalurKotakBulat(g, 30, 30, 360, 360, 30); g.clip(); gambarPasPenuh(g, cover, 30, 30, 360, 360); const gradasiSampul = g.createLinearGradient(30, 30, 390, 390); gradasiSampul.addColorStop(0, 'rgba(255,255,255,0.12)'); gradasiSampul.addColorStop(0.4, 'rgba(255,255,255,0)'); g.fillStyle = gradasiSampul; g.fillRect(30, 30, 360, 360); g.restore(); g.fillStyle = '#fff'; g.font = '41px PosTebal'; g.textBaseline = 'alphabetic'; g.fillText(potongTeksPas(g, dataLagu.title, 308), 30, 462); g.fillStyle = 'rgba(255,255,255,0.68)'; g.font = '27px PosBiasa'; g.fillText(potongTeksPas(g, dataLagu.artist, 308), 30, 500); ikonHati(g, 372, 456, 26); const durasiLagu = dataLagu.duration || Math.floor(150 + pengacak() * 110); const p = dataLagu.progress != null ? dataLagu.progress : 0.22 + pengacak() * 0.5; const px0 = 30, px1 = 390, py = 556; g.lineCap = 'round'; g.lineWidth = 5; g.strokeStyle = 'rgba(255,255,255,0.25)'; g.beginPath(); g.moveTo(px0, py); g.lineTo(px1, py); g.stroke(); const posisiProgres = px0 + (px1 - px0) * p; g.strokeStyle = 'rgba(255,255,255,0.92)'; g.beginPath(); g.moveTo(px0, py); g.lineTo(posisiProgres, py); g.stroke(); g.fillStyle = '#fff'; g.beginPath(); g.arc(posisiProgres, py, 8, 0, Math.PI * 2); g.fill(); g.fillStyle = 'rgba(255,255,255,0.6)'; g.font = '18px PosBiasa'; g.fillText(formatWaktu(durasiLagu * p), 30, 592); g.textAlign = 'right'; g.fillText('-' + formatWaktu(durasiLagu * (1 - p)), 390, 592); g.textAlign = 'left'; g.fillStyle = '#fff'; g.strokeStyle = '#fff'; ikonSegitiga(g, 112, 612, 26, 30, -1); ikonSegitiga(g, 134, 612, 26, 30, -1); g.lineWidth = 0; jalurKotakBulat(g, 192, 610, 12, 34, 4); g.fill(); jalurKotakBulat(g, 216, 610, 12, 34, 4); g.fill(); ikonSegitiga(g, 262, 612, 26, 30, 1); ikonSegitiga(g, 284, 612, 26, 30, 1); const posisiVolume = 674, levelVolume = 0.3 + pengacak() * 0.5; ikonPengeras(g, 30, posisiVolume, 0.6); g.lineWidth = 4; g.lineCap = 'round'; g.strokeStyle = 'rgba(255,255,255,0.25)'; g.beginPath(); g.moveTo(74, posisiVolume); g.lineTo(346, posisiVolume); g.stroke(); g.strokeStyle = 'rgba(255,255,255,0.8)'; g.beginPath(); g.moveTo(74, posisiVolume); g.lineTo(74 + 272 * levelVolume, posisiVolume); g.stroke(); ikonPengeras(g, 362, posisiVolume, 0.6); g.save(); jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.clip(); const gradasiKilap = g.createLinearGradient(0, 0, LEBAR_KARTU, TINGGI_KARTU * 0.55); gradasiKilap.addColorStop(0, 'rgba(255,255,255,0.16)'); gradasiKilap.addColorStop(0.45, 'rgba(255,255,255,0.03)'); gradasiKilap.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gradasiKilap; g.fillRect(0, 0, LEBAR_KARTU, TINGGI_KARTU); g.fillStyle = 'rgba(255,255,255,0.05)'; g.beginPath(); g.moveTo(LEBAR_KARTU * 0.55, 0); g.lineTo(LEBAR_KARTU * 0.8, 0); g.lineTo(LEBAR_KARTU * 0.25, TINGGI_KARTU); g.lineTo(0, TINGGI_KARTU); g.closePath(); g.fill(); g.restore(); const gradasiTepi = g.createLinearGradient(0, 0, LEBAR_KARTU, TINGGI_KARTU); gradasiTepi.addColorStop(0, 'rgba(255,255,255,0.45)'); gradasiTepi.addColorStop(0.5, 'rgba(255,255,255,0.08)'); gradasiTepi.addColorStop(1, 'rgba(255,255,255,0.25)'); jalurKotakBulat(g, 1.5, 1.5, LEBAR_KARTU - 3, TINGGI_KARTU - 3, RADIUS_SUDUT); g.lineWidth = 2.5; g.strokeStyle = gradasiTepi; g.stroke(); return c; } /* ---- proyeksi 3D ---- */ const keRadian = (dataPiksel) => dataPiksel * Math.PI / 180; function buatProyeksi(poseKartu, W, H) { const cr = Math.cos(keRadian(poseKartu.roll)), sr = Math.sin(keRadian(poseKartu.roll)); const cp = Math.cos(keRadian(poseKartu.pitch)), sp = Math.sin(keRadian(poseKartu.pitch)); const cy = Math.cos(keRadian(poseKartu.yaw)), sy = Math.sin(keRadian(poseKartu.yaw)); const rot = (x, y, z) => { let t = x * cr - y * sr; y = x * sr + y * cr; x = t; t = y * cp - z * sp; z = y * sp + z * cp; y = t; t = x * cy + z * sy; z = -x * sy + z * cy; x = t; return [x, y, z]; }; const world = (u, v, w) => { const r = rot(u * poseKartu.scale, v * poseKartu.scale, w * poseKartu.scale); return [r[0] + (poseKartu.cx - W / 2), r[1] + (poseKartu.cy - H / 2), r[2] + PANJANG_FOKUS]; }; const screen = (proyeksiKartu) => [W / 2 + PANJANG_FOKUS * proyeksiKartu[0] / proyeksiKartu[2], H / 2 + PANJANG_FOKUS * proyeksiKartu[1] / proyeksiKartu[2]]; return { rot, world, screen, pt: (u, v, w = 0) => screen(world(u, v, w)) }; } function hitungHomografi(titikAsal, titikSasaran) { const A = [], b = []; for (let i = 0; i < 4; i++) { const [x, y] = titikAsal[i], [u, v] = titikSasaran[i]; A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); b.push(u); A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); b.push(v); } const n = 8; for (let i = 0; i < n; i++) { let m = i; for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[m][i])) m = r; [A[i], A[m]] = [A[m], A[i]]; [b[i], b[m]] = [b[m], b[i]]; for (let r = i + 1; r < n; r++) { const f = A[r][i] / A[i][i]; for (let c = i; c < n; c++) A[r][c] -= f * A[i][c]; b[r] -= f * b[i]; } } const h = new Array(n); for (let i = n - 1; i >= 0; i--) { let s = b[i]; for (let c = i + 1; c < n; c++) s -= A[i][c] * h[c]; h[i] = s / A[i][i]; } return h; } /** gambar `kartuMentah` ke 4 titik tujuan dengan perspektif asli (invers homografi + 2x2 supersample) */ function gambarPerspektif(ctx, kartuMentah, titikTujuan) { const sw = kartuMentah.width, sh = kartuMentah.height; const pikselSumber = kartuMentah.getContext('2d').getImageData(0, 0, sw, sh).data; const xs = titikTujuan.map((p) => p[0]), ys = titikTujuan.map((p) => p[1]); const x0 = Math.floor(Math.min(...xs)) - 2, y0 = Math.floor(Math.min(...ys)) - 2; const bw = Math.ceil(Math.max(...xs)) - x0 + 3, bh = Math.ceil(Math.max(...ys)) - y0 + 3; const h = hitungHomografi(titikTujuan, [[0, 0], [sw, 0], [sw, sh], [0, sh]]); const dataHasil = new Uint8ClampedArray(bw * bh * 4); const sampelSub = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]]; for (let y = 0; y < bh; y++) { for (let x = 0; x < bw; x++) { let R = 0, G = 0, B = 0, A = 0; for (const [ox, oy] of sampelSub) { const X = x0 + x + ox, Y = y0 + y + oy; const w = h[6] * X + h[7] * Y + 1; const u = (h[0] * X + h[1] * Y + h[2]) / w - 0.5, v = (h[3] * X + h[4] * Y + h[5]) / w - 0.5; if (u < 0 || v < 0 || u >= sw - 1 || v >= sh - 1) continue; const iu = u | 0, iv = v | 0, fu = u - iu, fv = v - iv; const i00 = (iv * sw + iu) * 4, i10 = i00 + 4, i01 = i00 + sw * 4, i11 = i01 + 4; const w00 = (1 - fu) * (1 - fv), w10 = fu * (1 - fv), w01 = (1 - fu) * fv, w11 = fu * fv; const a00 = pikselSumber[i00 + 3] * w00, a10 = pikselSumber[i10 + 3] * w10, a01 = pikselSumber[i01 + 3] * w01, a11 = pikselSumber[i11 + 3] * w11; R += pikselSumber[i00] * a00 + pikselSumber[i10] * a10 + pikselSumber[i01] * a01 + pikselSumber[i11] * a11; G += pikselSumber[i00 + 1] * a00 + pikselSumber[i10 + 1] * a10 + pikselSumber[i01 + 1] * a01 + pikselSumber[i11 + 1] * a11; B += pikselSumber[i00 + 2] * a00 + pikselSumber[i10 + 2] * a10 + pikselSumber[i01 + 2] * a01 + pikselSumber[i11 + 2] * a11; A += a00 + a10 + a01 + a11; } if (A > 0) { const opsiKerja = (y * bw + x) * 4; dataHasil[opsiKerja] = R / A; dataHasil[opsiKerja + 1] = G / A; dataHasil[opsiKerja + 2] = B / A; dataHasil[opsiKerja + 3] = A / 4; } } } const kanvasSementara = createCanvas(bw, bh); kanvasSementara.getContext('2d').putImageData(new ImageData(dataHasil, bw, bh), 0, 0); ctx.drawImage(kanvasSementara, x0, y0); } function titikGarisLuar() { const hw = LEBAR_KARTU / 2 - 1.5, hh = TINGGI_KARTU / 2 - 1.5, daftarTitik = []; const daftarSudut = [[-hw + RADIUS_SUDUT, -hh + RADIUS_SUDUT, Math.PI], [hw - RADIUS_SUDUT, -hh + RADIUS_SUDUT, Math.PI * 1.5], [hw - RADIUS_SUDUT, hh - RADIUS_SUDUT, 0], [-hw + RADIUS_SUDUT, hh - RADIUS_SUDUT, Math.PI * 0.5]]; for (const [cx, cy, a0] of daftarSudut) { for (let i = 0; i <= 10; i++) { const a = a0 + (Math.PI / 2) * (i / 10); daftarTitik.push({ u: cx + RADIUS_SUDUT * Math.cos(a), v: cy + RADIUS_SUDUT * Math.sin(a), nx: Math.cos(a), ny: Math.sin(a) }); } } return daftarTitik; } const GARIS_LUAR = titikGarisLuar(); /** bayangan saja (bentuk digeser jauh keluar kanvas, hanya bayangannya yang tampak) */ function gambarBayangan(g, q, warnaBayang, blurBayang, geserY = 0) { const OFF = 6000; g.save(); g.beginPath(); g.moveTo(q[0][0] - OFF, q[0][1]); for (let i = 1; i < q.length; i++) g.lineTo(q[i][0] - OFF, q[i][1]); g.closePath(); g.shadowColor = warnaBayang; g.shadowBlur = blurBayang; g.shadowOffsetX = OFF; g.shadowOffsetY = geserY; g.fillStyle = '#000'; g.fill(); g.restore(); } /** 1 kartu 3D: bayangan -> sisi tebal -> muka kartu -> rim; mengembalikan posisi pojok kanan atas */ function gambarKartuTigaDimensi(ctx, kartuMentah, poseKartu, W, H) { const proyeksiKartu = buatProyeksi(poseKartu, W, H); const hw = LEBAR_KARTU / 2 + MARGIN_KARTU, hh = TINGGI_KARTU / 2 + MARGIN_KARTU; const titikTujuan = [proyeksiKartu.pt(-hw, -hh), proyeksiKartu.pt(hw, -hh), proyeksiKartu.pt(hw, hh), proyeksiKartu.pt(-hw, hh)]; const q = [proyeksiKartu.pt(-LEBAR_KARTU / 2, -TINGGI_KARTU / 2), proyeksiKartu.pt(LEBAR_KARTU / 2, -TINGGI_KARTU / 2), proyeksiKartu.pt(LEBAR_KARTU / 2, TINGGI_KARTU / 2), proyeksiKartu.pt(-LEBAR_KARTU / 2, TINGGI_KARTU / 2)]; gambarBayangan(ctx, q, 'rgba(0,0,0,0.6)', 60, 22); const L = [-0.5, -0.7, -0.5]; const ln = Math.hypot(...L); const daftarSisi = []; for (let i = 0; i < GARIS_LUAR.length; i++) { const a = GARIS_LUAR[i], b = GARIS_LUAR[(i + 1) % GARIS_LUAR.length]; const titikDuniaA = proyeksiKartu.world(a.u, a.v, 0); const n = proyeksiKartu.rot(a.nx, a.ny, 0); const arahKamera = [-titikDuniaA[0], -titikDuniaA[1], -titikDuniaA[2]]; const hasilRapikan = Math.hypot(...arahKamera); const nilaiVis = (n[0] * arahKamera[0] + n[1] * arahKamera[1] + n[2] * arahKamera[2]) / hasilRapikan; if (nilaiVis <= 0) continue; const lit = Math.max(0, -(n[0] * L[0] + n[1] * L[1] + n[2] * L[2]) / ln); daftarSisi.push({ poly: [proyeksiKartu.pt(a.u, a.v, 0), proyeksiKartu.pt(b.u, b.v, 0), proyeksiKartu.pt(b.u, b.v, KETEBALAN), proyeksiKartu.pt(a.u, a.v, KETEBALAN)], lit }); } ctx.save(); ctx.lineJoin = 'round'; for (const f of daftarSisi) { const k = Math.pow(f.lit, 0.8); const r = Math.round(30 + 170 * k), gg = Math.round(32 + 178 * k), bb = Math.round(38 + 190 * k); ctx.fillStyle = ctx.strokeStyle = `rgb(${r},${gg},${bb})`; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(...f.poly[0]); for (let i = 1; i < 4; i++) ctx.lineTo(...f.poly[i]); ctx.closePath(); ctx.fill(); ctx.stroke(); } ctx.restore(); gambarPerspektif(ctx, kartuMentah, titikTujuan); ctx.save(); const t0 = proyeksiKartu.pt(-LEBAR_KARTU / 2, -TINGGI_KARTU / 2), t1 = proyeksiKartu.pt(LEBAR_KARTU / 2, TINGGI_KARTU / 2); const rg = ctx.createLinearGradient(t0[0], t0[1], t1[0], t1[1]); rg.addColorStop(0, 'rgba(255,255,255,0.55)'); rg.addColorStop(0.5, 'rgba(255,255,255,0.10)'); rg.addColorStop(1, 'rgba(255,255,255,0.3)'); ctx.strokeStyle = rg; ctx.lineWidth = 2; ctx.lineJoin = 'round'; ctx.beginPath(); GARIS_LUAR.forEach((opsiKerja, i) => { const p = proyeksiKartu.pt(opsiKerja.u, opsiKerja.v, 0); i ? ctx.lineTo(...p) : ctx.moveTo(...p); }); ctx.closePath(); ctx.stroke(); ctx.restore(); return { corner: proyeksiKartu.pt(LEBAR_KARTU / 2 - 6, -TINGGI_KARTU / 2 + 6, 0), scale: poseKartu.scale }; } /* ---- kilau bintang 4 sudut di pojok kanan atas kartu ---- */ function kilauSilang(g, panjangKilau, tebalKilau, rot, a) { g.save(); g.rotate(rot); const gr = g.createLinearGradient(-panjangKilau, 0, panjangKilau, 0); gr.addColorStop(0, 'rgba(255,255,255,0)'); gr.addColorStop(0.5, `rgba(255,255,255,${a})`); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.beginPath(); g.moveTo(-panjangKilau, 0); g.quadraticCurveTo(0, -tebalKilau, panjangKilau, 0); g.quadraticCurveTo(0, tebalKilau, -panjangKilau, 0); g.closePath(); g.fill(); g.restore(); } function gambarKilau(g, x, y, r, a = 1) { g.save(); g.translate(x, y); g.globalCompositeOperation = 'lighter'; const halo = g.createRadialGradient(0, 0, 0, 0, 0, r * 0.95); halo.addColorStop(0, `rgba(255,255,255,${0.7 * a})`); halo.addColorStop(0.3, `rgba(220,235,255,${0.22 * a})`); halo.addColorStop(1, 'rgba(220,235,255,0)'); g.fillStyle = halo; g.beginPath(); g.arc(0, 0, r * 0.95, 0, Math.PI * 2); g.fill(); kilauSilang(g, r * 1.5, r * 0.05, 0, 0.85 * a); kilauSilang(g, r * 1.8, r * 0.05, Math.PI / 2, 0.85 * a); g.globalCompositeOperation = 'source-over'; const rx = r * 0.78, ry = r * 1.05, k = r * 0.05; g.fillStyle = '#fff'; g.shadowColor = 'rgba(255,255,255,0.95)'; g.shadowBlur = r * 0.35; g.beginPath(); g.moveTo(0, -ry); g.quadraticCurveTo(k, -k, rx, 0); g.quadraticCurveTo(k, k, 0, ry); g.quadraticCurveTo(-k, k, -rx, 0); g.quadraticCurveTo(-k, -k, 0, -ry); g.closePath(); g.fill(); g.restore(); } /* ---- rapikan potongan karakter ---- */ function beriLabelKomponen(topengBiner, W, H) { const N = W * H, lab = new Int32Array(N), tumpukanData = new Int32Array(N), info = [null]; let n = 0; for (let i = 0; i < N; i++) { if (!topengBiner[i] || lab[i]) continue; n++; let sp = 0, size = 0, border = false; tumpukanData[sp++] = i; lab[i] = n; while (sp) { const p = tumpukanData[--sp]; size++; const x = p % W, y = (p - x) / W; if (x === 0 || y === 0 || x === W - 1 || y === H - 1) border = true; let q; if (x > 0 && topengBiner[q = p - 1] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } if (x < W - 1 && topengBiner[q = p + 1] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } if (y > 0 && topengBiner[q = p - W] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } if (y < H - 1 && topengBiner[q = p + W] && !lab[q]) { lab[q] = n; tumpukanData[sp++] = q; } } info.push({ size, border }); } return { lab, info }; } /** buang serpihan, tutup lubang kecil, tegasin setengah transparan, kikis halo, haluskan tepi. * Warna diambil dari foto asli kalau sebangun (tanpa halo bekas pemotong). */ function bersihkanPotongan(gambarPotongan, gambarLatarAsli, W, H, opsiKerja = {}) { const N = W * H; const c = createCanvas(W, H), g = c.getContext('2d'); gambarPasPenuh(g, gambarPotongan, 0, 0, W, H); const dataPiksel = g.getImageData(0, 0, W, H).data; const a = new Uint8ClampedArray(N); for (let i = 0; i < N; i++) a[i] = dataPiksel[i * 4 + 3]; const topengBiner = new Uint8Array(N); for (let i = 0; i < N; i++) topengBiner[i] = a[i] > 40 ? 1 : 0; let L = beriLabelKomponen(topengBiner, W, H), big = 0; for (let k = 1; k < L.info.length; k++) big = Math.max(big, L.info[k].size); const minSize = Math.max(500, big * 0.004); for (let i = 0; i < N; i++) if (L.lab[i] && L.info[L.lab[i]].size < minSize) a[i] = 0; for (let i = 0; i < N; i++) topengBiner[i] = a[i] <= 40 ? 1 : 0; L = beriLabelKomponen(topengBiner, W, H); const holeMax = opsiKerja.holeMax || 700; for (let i = 0; i < N; i++) if (L.lab[i] && !L.info[L.lab[i]].border && L.info[L.lab[i]].size <= holeMax) a[i] = 255; for (let i = 0; i < N; i++) { const v = a[i]; a[i] = v <= 30 ? 0 : v >= 225 ? 255 : Math.round((v - 30) * 255 / 195); } let nilaiBerjalan = a; const jumlahErosi = opsiKerja.erode == null ? 1 : opsiKerja.erode; for (let r = 0; r < jumlahErosi; r++) { const alfaBaru = new Uint8ClampedArray(N); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const p = y * W + x; let v = nilaiBerjalan[p]; if (x > 0 && nilaiBerjalan[p - 1] < v) v = nilaiBerjalan[p - 1]; if (x < W - 1 && nilaiBerjalan[p + 1] < v) v = nilaiBerjalan[p + 1]; if (y > 0 && nilaiBerjalan[p - W] < v) v = nilaiBerjalan[p - W]; if (y < H - 1 && nilaiBerjalan[p + W] < v) v = nilaiBerjalan[p + W]; alfaBaru[p] = v; } nilaiBerjalan = alfaBaru; } const alfaFinal = new Uint8ClampedArray(N); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const p = y * W + x, v = nilaiBerjalan[p]; const l = x > 0 ? nilaiBerjalan[p - 1] : v, rt = x < W - 1 ? nilaiBerjalan[p + 1] : v; const u = y > 0 ? nilaiBerjalan[p - W] : v, dn = y < H - 1 ? nilaiBerjalan[p + W] : v; alfaFinal[p] = (4 * v + l + rt + u + dn) >> 3; } let rgb = dataPiksel; const rasioAspek = gambarPotongan.width / gambarPotongan.height; if (gambarLatarAsli && Math.abs(gambarLatarAsli.width / gambarLatarAsli.height - rasioAspek) / rasioAspek < 0.02) { const bc = createCanvas(W, H), bg2 = bc.getContext('2d'); gambarPasPenuh(bg2, gambarLatarAsli, 0, 0, W, H); rgb = bg2.getImageData(0, 0, W, H).data; } const dataHasil = new Uint8ClampedArray(N * 4); const hitungBaris = new Uint32Array(H), hitungKolom = new Uint32Array(W); let totalPiksel = 0; for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const p = y * W + x, q = p * 4; dataHasil[q] = rgb[q]; dataHasil[q + 1] = rgb[q + 1]; dataHasil[q + 2] = rgb[q + 2]; dataHasil[q + 3] = alfaFinal[p]; if (alfaFinal[p] > 128) { hitungBaris[y]++; hitungKolom[x]++; totalPiksel++; } } let top = 0; while (top < H && hitungBaris[top] < 6) top++; let bot = H - 1; while (bot > top && hitungBaris[bot] < 6) bot--; let akumulasiKolom = 0, tengahX = W / 2; for (let x = 0; x < W; x++) { akumulasiKolom += hitungKolom[x]; if (akumulasiKolom >= totalPiksel / 2) { tengahX = x; break; } } const layer = createCanvas(W, H); layer.getContext('2d').putImageData(new ImageData(dataHasil, W, H), 0, 0); return { layer, top, bot, cx: tengahX, ok: totalPiksel > N * 0.01 && bot > top }; } /** geser + skala posisi kartu mengikuti letak & tinggi karakter di foto */ function sesuaikanPose(poseDasar, statistikPotongan) { const k = Math.min(1.3, Math.max(0.75, (statistikPotongan.bot - statistikPotongan.top) / ACUAN_KARAKTER.h)); return poseDasar.map((p) => Object.assign({}, p, { cx: Math.round(statistikPotongan.cx + (p.cx - ACUAN_KARAKTER.cx) * k), cy: Math.round(statistikPotongan.top + (p.cy - ACUAN_KARAKTER.top) * k), scale: +(p.scale * k).toFixed(3) })); } /** * @param {object} p * @param {string|Buffer} p.background foto latar (path / Buffer) * @param {string|Buffer} [p.character] PNG potongan karakter (transparan, sebangun dengan foto) -> menimpa kartu * @param {{title,artist,cover?,duration?,progress?}[]} p.songs 4 lagu (kurang dari 4 diulang) * @param {object} [p.options] { width, height, darken, sparkles, charShadow, autoFit, erode, seed, format:'png'|'jpg', poses } * @returns {Promise} */ async function rakitPosterLagu({ background, character, songs, options = {} }) { const opsiKerja = Object.assign({ width: 1080, height: 1920, darken: 0.1, sparkles: true, charShadow: true, autoFit: true, erode: 1, seed: Date.now() % 100000, format: 'png', poses: POSE_AWAL }, options); const pengacak = pembangkitAcak(opsiKerja.seed); const { width: W, height: H } = opsiKerja; const canvas = createCanvas(W, H), ctx = canvas.getContext('2d'); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; const gambarLatarFoto = await muatGambar(background); if (gambarLatarFoto) gambarPasPenuh(ctx, gambarLatarFoto, 0, 0, W, H); else { ctx.fillStyle = '#0b0f1a'; ctx.fillRect(0, 0, W, H); } if (opsiKerja.darken > 0) { ctx.fillStyle = `rgba(0,0,0,${opsiKerja.darken})`; ctx.fillRect(0, 0, W, H); } const daftarLaguFinal = []; for (let i = 0; i < 4; i++) daftarLaguFinal.push(songs[i % songs.length]); const daftarKartuRender = []; for (let i = 0; i < 4; i++) { const s = daftarLaguFinal[i]; const cover = (await muatGambar(s.cover)) || sampulPengganti(s.title, s.artist); daftarKartuRender.push(buatKartuLagu(s, cover, pengacak)); } const daftarSudut = []; const sumberKarakter = await muatGambar(character); let lapisanKarakterFinal = null; if (sumberKarakter) { try { const hasilRapikan = bersihkanPotongan(sumberKarakter, gambarLatarFoto, W, H, { erode: opsiKerja.erode }); if (hasilRapikan.ok) { lapisanKarakterFinal = hasilRapikan.layer; if (opsiKerja.autoFit) opsiKerja.poses = sesuaikanPose(opsiKerja.poses, hasilRapikan); } } catch (e) { console.error('[poster-lagu] rapikan potongan gagal:', e.message); } if (!lapisanKarakterFinal) { lapisanKarakterFinal = createCanvas(W, H); gambarPasPenuh(lapisanKarakterFinal.getContext('2d'), sumberKarakter, 0, 0, W, H); } } // kilau digambar SEBELUM karakter supaya tertimpa karakter const ukuranKilau = [34, 42, 30, 38]; const gambarSemuaKilau = (front) => { if (!opsiKerja.sparkles) return; for (let i = 0; i < 4; i++) { if (!!opsiKerja.poses[i].front === front && daftarSudut[i]) gambarKilau(ctx, daftarSudut[i].corner[0], daftarSudut[i].corner[1], ukuranKilau[i] * daftarSudut[i].scale / 0.93, 1); } }; for (let i = 0; i < 4; i++) if (!opsiKerja.poses[i].front) daftarSudut[i] = gambarKartuTigaDimensi(ctx, daftarKartuRender[i], opsiKerja.poses[i], W, H); gambarSemuaKilau(false); if (lapisanKarakterFinal) { ctx.save(); if (opsiKerja.charShadow) { ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 26; ctx.shadowOffsetY = 6; } ctx.drawImage(lapisanKarakterFinal, 0, 0, W, H); ctx.restore(); } for (let i = 0; i < 4; i++) if (opsiKerja.poses[i].front) daftarSudut[i] = gambarKartuTigaDimensi(ctx, daftarKartuRender[i], opsiKerja.poses[i], W, H); gambarSemuaKilau(true); return opsiKerja.format === 'jpg' ? canvas.toBuffer('image/jpeg', 92) : canvas.toBuffer('image/png'); } /* ================================================================== */ /* 4. PINTU UTAMA */ /* ================================================================== */ /** * Semua langkah sekaligus: cari lagu+cover, hapus background (opsional), render. * @param {object} p * @param {Buffer|string} p.photo foto (Buffer / path) * @param {string[]} p.songs tulis bebas: "judul artis", "artis judul", atau "judul" saja (maks 4) * @param {boolean} [p.cut=true] false = tanpa efek karakter menimpa kartu * @param {'png'|'jpg'} [p.format='png'] * @returns {Promise} */ async function buatPosterLagu({ photo, songs, cut = true, format = 'png' }) { const penyanggaFoto = Buffer.isBuffer(photo) ? photo : fs.readFileSync(photo); const daftarKueri = (Array.isArray(songs) ? songs : uraikanDaftarLagu(songs).songs).slice(0, 4); if (!daftarKueri.length) throw new Error('Minimal satu lagu.'); const janjiLagu = Promise.all(daftarKueri.map((q) => temukanLagu(q))); let penyanggaPotongan; const janjiPotong = !cut ? Promise.resolve() : (async () => { try { const formatPng = penyanggaFoto.subarray(0, 4).equals(TANDA_PNG); penyanggaPotongan = await potongLatar(penyanggaFoto, formatPng ? 'image/png' : 'image/jpeg'); const [a, b] = await Promise.all([loadImage(penyanggaFoto), loadImage(penyanggaPotongan)]); if (Math.abs(a.width / a.height - b.width / b.height) / (a.width / a.height) >= 0.02) throw new Error('ukuran hasil potongan beda dengan foto'); console.log('[poster-lagu] karakter menimpa kartu:', labelBria()); } catch (e) { penyanggaPotongan = undefined; console.error('[poster-lagu] tanpa efek karakter menimpa kartu:', e.message); } })(); const [laguTerpilih] = await Promise.all([janjiLagu, janjiPotong]); laguTerpilih.forEach((r, i) => console.log(`[poster-lagu] ${i + 1}. ${r.found ? `${r.title} — ${r.artist} (${r.source})` : `${r.title} (tidak ketemu, cover cadangan)`}`)); return rakitPosterLagu({ background: penyanggaFoto, character: penyanggaPotongan, songs: laguTerpilih.map((r) => ({ title: r.title, artist: r.artist, cover: r.cover || undefined, duration: r.duration || undefined })), options: { format }, }); } module.exports = { buatPosterLagu, rakitPosterLagu, temukanLagu, uraikanDaftarLagu, potongLatar, POSE_AWAL }; /* ---- terminal: node poster-lagu-3d.js foto.jpg "lagu 1" "lagu 2" ... [--nocut] [--out hasil.png] ---- */ if (require.main === module) { (async () => { const daftarArgumen = process.argv.slice(2); const ambilOpsi = (flag) => { const i = daftarArgumen.indexOf(flag); if (i < 0) return null; daftarArgumen.splice(i, 1); return true; }; const tanpaPotong = ambilOpsi('--nocut'); let dataHasil = 'poster-lagu.png'; const indeksOpsiOut = daftarArgumen.indexOf('--out'); if (indeksOpsiOut >= 0) { dataHasil = daftarArgumen[indeksOpsiOut + 1] || dataHasil; daftarArgumen.splice(indeksOpsiOut, 2); } const [photo, ...songs] = daftarArgumen; if (!photo || !songs.length) { console.log('Pakai: node poster-lagu-3d.js foto.jpg "judul artis" "judul artis" ... [--nocut] [--out hasil.png]'); process.exit(1); } const penyanggaHasil = await buatPosterLagu({ photo, songs, cut: !tanpaPotong, format: /\.jpe?g$/i.test(dataHasil) ? 'jpg' : 'png' }); fs.writeFileSync(dataHasil, penyanggaHasil); console.log('Selesai ->', dataHasil); })().catch((e) => { console.error('Gagal:', e.message); process.exit(1); }); }