actual featured page

This commit is contained in:
2026-08-07 18:59:25 -04:00
parent 0cc15c8d90
commit 64d8b40e61
9 changed files with 1321 additions and 847 deletions

405
discover/featured.json Normal file
View File

@@ -0,0 +1,405 @@
{
"version": 1,
"podcasts": [
{
"id": "discover-daily",
"title": "The Daily",
"description": "This is how the news should sound. Twenty minutes a day, five days a week, hosted by Michael Barbaro and Sabrina Tavernise. Powered by New York Times journalism.",
"feedUrl": "http://rss.art19.com/the-daily",
"author": "The New York Times",
"categories": ["News", "Politics"]
},
{
"id": "discover-up-first",
"title": "Up First",
"description": "NPR's Up First covers the three biggest stories of the day, with reporting and analysis from NPR News — in 10 minutes.",
"feedUrl": "https://feeds.npr.org/510318/podcast.xml",
"author": "NPR",
"categories": ["News"]
},
{
"id": "discover-npr-politics",
"title": "The NPR Politics Podcast",
"description": "Where everyone gathers for the political conversation of the day. NPR's political reporters talk through the biggest news of the week.",
"feedUrl": "https://feeds.npr.org/510310/podcast.xml",
"author": "NPR",
"categories": ["News", "Politics"]
},
{
"id": "discover-code-switch",
"title": "Code Switch",
"description": "Race. In your face. A podcast from NPR that fearlessly explores how race impacts every part of society — from politics to pop culture.",
"feedUrl": "https://feeds.npr.org/510352/podcast.xml",
"author": "NPR",
"categories": ["News", "Culture", "Politics"]
},
{
"id": "discover-rough-translation",
"title": "Rough Translation",
"description": "How are the things we're talking about covered in the rest of the world? NPR's Rough Translation takes you to far-off places and shows you the unexpected.",
"feedUrl": "https://feeds.npr.org/510324/podcast.xml",
"author": "NPR",
"categories": ["News", "Culture"]
},
{
"id": "discover-crime-junkie",
"title": "Crime Junkie",
"description": "Crime Junkie satisfies true crime cravings with host Ashley Flowers' obsessed yet accessible approach to real-life mysteries — from unsolved murders to missing persons.",
"feedUrl": "https://feeds.simplecast.com/qm_9xx0g",
"author": "audiochuck",
"categories": ["True Crime"]
},
{
"id": "discover-serial",
"title": "Serial",
"description": "Serial Productions makes narrative podcasts that have transformed the medium. From the team that brought you the original Serial, one of the most influential podcasts of all time.",
"feedUrl": "https://feeds.simplecast.com/PpzWFGhg",
"author": "Serial Productions & The New York Times",
"categories": ["True Crime", "Storytelling"]
},
{
"id": "discover-intelligence-matters",
"title": "Intelligence Matters",
"description": "A deep dive into national security, intelligence, and foreign policy with top former officials and experts hosted by CBS News senior correspondent.",
"feedUrl": "https://rss.art19.com/intelligence-matters",
"author": "CBS News",
"categories": ["True Crime", "Politics", "News"]
},
{
"id": "discover-smartless",
"title": "SmartLess",
"description": "Jason Bateman, Sean Hayes, and Will Arnett bring you unscripted conversations with surprise celebrity guests — each episode one host reveals the guest to the others.",
"feedUrl": "https://rss.art19.com/smartless",
"author": "Jason Bateman, Sean Hayes, Will Arnett",
"categories": ["Comedy", "Entertainment"]
},
{
"id": "discover-this-past-weekend",
"title": "This Past Weekend w/ Theo Von",
"description": "Comedian Theo Von's uniquely southern perspective blends heartfelt vulnerability and offbeat humor in conversations ranging from celebrity interviews to solo musings.",
"feedUrl": "https://feeds.megaphone.fm/thispastweekend",
"author": "Theo Von",
"categories": ["Comedy"]
},
{
"id": "discover-joe-rogan",
"title": "The Joe Rogan Experience",
"description": "The official podcast of comedian Joe Rogan. Long-form conversations with guests from every corner of culture, science, comedy, and beyond.",
"feedUrl": "https://feeds.megaphone.fm/GLT1412515089",
"author": "Joe Rogan",
"categories": ["Comedy", "Entertainment"]
},
{
"id": "discover-comedy-bang-bang",
"title": "Comedy Bang Bang: The Podcast",
"description": "A weekly comedy podcast hosted by Scott Aukerman featuring improv, games, and hilarious conversations with celebrities and the world's best comedians.",
"feedUrl": "https://rss.art19.com/comedy-bang-bang",
"author": "Earwolf",
"categories": ["Comedy"]
},
{
"id": "discover-office-ladies",
"title": "Office Ladies",
"description": "The Office stars Jenna Fischer and Angela Kinsey break down each episode of The Office with behind-the-scenes stories, fun facts, and fan Q&A.",
"feedUrl": "https://rss.art19.com/office-ladies",
"author": "Earwolf",
"categories": ["Comedy", "Entertainment"]
},
{
"id": "discover-how-did-this-get-made",
"title": "How Did This Get Made?",
"description": "Comedians Paul Scheer, June Diane Raphael, and Jason Mantzoukas break down the very best of the worst films ever made — blockbuster flops, cult classics, and Nic Cage movies.",
"feedUrl": "https://rss.art19.com/how-did-this-get-made",
"author": "Earwolf",
"categories": ["Comedy", "Film"]
},
{
"id": "discover-wait-wait",
"title": "Wait Wait... Don't Tell Me!",
"description": "NPR's weekly news quiz show. Test your knowledge against the week's biggest news, with panelists and celebrity guests competing in hilarious trivia.",
"feedUrl": "https://feeds.npr.org/344098539/podcast.xml",
"author": "NPR",
"categories": ["Comedy", "News"]
},
{
"id": "discover-new-heights",
"title": "New Heights with Jason & Travis Kelce",
"description": "Football's funniest family duo — Super Bowl champions Jason and Travis Kelce — drop weekly insights about the NFL and share inside perspectives on sports headlines.",
"feedUrl": "https://rss.art19.com/new-heights",
"author": "Jason & Travis Kelce",
"categories": ["Sports", "Comedy"]
},
{
"id": "discover-bill-simmons",
"title": "The Bill Simmons Podcast",
"description": "Bill Simmons and his cadre of opinionated guests discuss sports, pop culture, and everything in between on The Ringer's flagship podcast.",
"feedUrl": "https://rss.art19.com/the-bill-simmons-podcast",
"author": "The Ringer",
"categories": ["Sports", "Entertainment"]
},
{
"id": "discover-acquired",
"title": "Acquired",
"description": "Acquired tells the stories and strategies of the world's greatest companies. Each episode is a deep dive into a single company's history and the playbooks behind its success.",
"feedUrl": "https://feeds.transistor.fm/acquired",
"author": "Ben Gilbert & David Rosenthal",
"categories": ["Business", "Technology"]
},
{
"id": "discover-all-in",
"title": "All-In Podcast",
"description": "Four tech industry veterans share their unfiltered perspectives on technology, economics, politics, and culture. Insightful, opinionated, and occasionally controversial.",
"feedUrl": "https://feeds.transistor.fm/all-in",
"author": "Chamath, Jason, Sacks & Friedberg",
"categories": ["Business", "Technology", "Politics"]
},
{
"id": "discover-planet-money",
"title": "Planet Money",
"description": "The economy explained. NPR's Planet Money breaks down the economy with creative storytelling that makes sense of a complicated, ever-changing world.",
"feedUrl": "https://feeds.npr.org/510289/podcast.xml",
"author": "NPR",
"categories": ["Business", "Economics"]
},
{
"id": "discover-how-i-built-this",
"title": "How I Built This with Guy Raz",
"description": "Guy Raz interviews the world's best-known entrepreneurs to learn how they built their iconic brands. A master-class on innovation, creativity, and leadership.",
"feedUrl": "https://feeds.npr.org/510313/podcast.xml",
"author": "NPR / Wondery",
"categories": ["Business", "Technology"]
},
{
"id": "discover-freakonomics",
"title": "Freakonomics Radio",
"description": "Discover the hidden side of everything with Stephen Dubner. Each episode explores the riddles of everyday life using the tools of economics.",
"feedUrl": "https://feeds.feedburner.com/freakonomicsradio",
"author": "Stephen J. Dubner",
"categories": ["Business", "Economics", "Society"]
},
{
"id": "discover-darknet-diaries",
"title": "Darknet Diaries",
"description": "True stories from the dark side of the Internet. Host Jack Rhysider investigates hacks, data breaches, cybercrime, and digital espionage with rigorous journalism and captivating storytelling.",
"feedUrl": "https://podcast.darknetdiaries.com/",
"author": "Jack Rhysider",
"categories": ["Technology", "True Crime"]
},
{
"id": "discover-changelog",
"title": "The Changelog",
"description": "Software's best weekly news brief, deep technical interviews, and talk show. Conversations with the hackers, leaders, and innovators of the open source and software world.",
"feedUrl": "https://changelog.fm/rss",
"author": "Changelog Media",
"categories": ["Technology", "Software Engineering"]
},
{
"id": "discover-twit",
"title": "This Week in Tech (TWiT)",
"description": "Your first podcast of the week, the last word in tech. Leo Laporte and a rotating panel of tech experts discuss the week's biggest tech news.",
"feedUrl": "https://feeds.twit.tv/twit.xml",
"author": "TWiT",
"categories": ["Technology"]
},
{
"id": "discover-radiolab",
"title": "Radiolab",
"description": "Radiolab is on a curiosity bender. Each episode weaves together science, legal history, and deeply human stories with innovative sound design. Hosted by Lulu Miller and Latif Nasser.",
"feedUrl": "http://feeds.wnyc.org/radiolab",
"author": "WNYC Studios",
"categories": ["Science", "Storytelling"]
},
{
"id": "discover-huberman-lab",
"title": "Huberman Lab",
"description": "Regularly ranked as the #1 health podcast in the world. Dr. Andrew Huberman discusses science and science-based tools for everyday life: sleep, focus, fitness, and performance.",
"feedUrl": "https://feeds.megaphone.fm/hubermanlab",
"author": "Scicomm Media",
"categories": ["Health", "Science"]
},
{
"id": "discover-skeptics-guide",
"title": "The Skeptics' Guide to the Universe",
"description": "Your guide to reality. A weekly science and critical thinking podcast that explores myths, conspiracies, pseudoscience, and the latest scientific discoveries — with a skeptical eye.",
"feedUrl": "https://feeds.feedburner.com/TheSkepticsGuideToTheUniverse",
"author": "Steven Novella",
"categories": ["Science", "Philosophy"]
},
{
"id": "discover-throughline",
"title": "Throughline",
"description": "The past is never past. NPR's Throughline travels beyond the headlines to answer the question 'How did we get here?' Each episode brings history to life from ancient civilizations to forgotten figures.",
"feedUrl": "https://feeds.npr.org/510333/podcast.xml",
"author": "NPR",
"categories": ["History", "Politics"]
},
{
"id": "discover-hardcore-history",
"title": "Dan Carlin's Hardcore History",
"description": "In Hardcore History, journalist and broadcaster Dan Carlin applies his unorthodox, 'Martian' way of thinking to the past. Multi-hour deep dives into pivotal events that blend high drama with masterful narration.",
"feedUrl": "https://feeds.feedburner.com/dancarlin/history",
"author": "Dan Carlin",
"categories": ["History"]
},
{
"id": "discover-history-of-rome",
"title": "The History of Rome",
"description": "A weekly chronological podcast tracing the entire history of Rome, from its mythical founding to the fall of the Western Empire. A masterclass in narrative history.",
"feedUrl": "https://feeds.feedburner.com/TheHistoryOfRome",
"author": "Mike Duncan",
"categories": ["History"]
},
{
"id": "discover-philosophize-this",
"title": "Philosophize This!",
"description": "Stephen West walks through the entire history of philosophy chronologically, from the pre-Socratics to contemporary thinkers. Making profound ideas accessible without dumbing them down.",
"feedUrl": "https://feed.podbean.com/philosophizethis/feed.xml",
"author": "Stephen West",
"categories": ["Philosophy", "Education"]
},
{
"id": "discover-very-bad-wizards",
"title": "Very Bad Wizards",
"description": "A philosopher (Tamler Sommers) and a psychologist (David Pizarro) discuss human nature, ethics, free will, and whatever movie they just watched. Irreverent, insightful, and intellectually honest.",
"feedUrl": "https://feed.podbean.com/verybadwizards/feed.xml",
"author": "Tamler Sommers & David Pizarro",
"categories": ["Philosophy", "Science"]
},
{
"id": "discover-big-picture",
"title": "The Big Picture",
"description": "The Ringer's Sean Fennessey and Amanda Dobbins discuss the week in movies, TV, and streaming — from box office analysis to what's worth your time.",
"feedUrl": "https://rss.art19.com/the-big-picture",
"author": "The Ringer",
"categories": ["Film", "Entertainment"]
},
{
"id": "discover-all-songs-considered",
"title": "All Songs Considered",
"description": "NPR's flagship music discovery podcast, delivering the best new releases every week across indie rock, jazz, electronic, and everything in between. Discover music you wouldn't stumble across on your own.",
"feedUrl": "https://feeds.npr.org/510019/podcast.xml",
"author": "NPR Music",
"categories": ["Music"]
},
{
"id": "discover-switched-on-pop",
"title": "Switched on Pop",
"description": "Musicologist Nate Sloan and songwriter Charlie Harding explain why pop music sounds the way it does — pulling apart chord progressions, production tricks, and cultural trends with zero snobbery.",
"feedUrl": "https://feeds.megaphone.fm/switchedonpop",
"author": "Vox Media / Panoply",
"categories": ["Music"]
},
{
"id": "discover-hit-parade",
"title": "Hit Parade",
"description": "Slate's Chris Molanphy traces how songs and genres conquered the Billboard charts, weaving chart history, cultural context, and pure trivia into each episode.",
"feedUrl": "https://feeds.megaphone.fm/hitparade",
"author": "Slate",
"categories": ["Music", "History"]
},
{
"id": "discover-song-exploder",
"title": "Song Exploder",
"description": "Musicians take apart their songs, piece by piece, and tell the story of how they were made. Past guests include Billie Eilish, Fleetwood Mac, and Lin-Manuel Miranda.",
"feedUrl": "https://songexploder.net/rss",
"author": "Hrishikesh Hirway",
"categories": ["Music", "Arts"]
},
{
"id": "discover-blank-check",
"title": "Blank Check with Griffin & David",
"description": "Reviews of directors' complete filmographies, episode by episode. Specifically, auteurs whose early successes afforded them the rare 'blank check' from Hollywood. Painstakingly hilarious detail.",
"feedUrl": "https://audioboom.com/channels/4278829.rss",
"author": "Griffin Newman & David Sims",
"categories": ["Film", "Comedy"]
},
{
"id": "discover-99-invisible",
"title": "99% Invisible",
"description": "A sound-rich, narrative podcast about all the thought that goes into the things we don't think about — the unnoticed architecture and design that shape our world. Hosted by Roman Mars.",
"feedUrl": "https://feeds.simplecast.com/BqbsxVfO",
"author": "Roman Mars",
"categories": ["Design", "Arts", "Culture"]
},
{
"id": "discover-gastropod",
"title": "Gastropod",
"description": "Food with a side of science and history. Co-hosts Cynthia Graber and Nicola Twilley explore the hidden history and surprising science behind a different food or farming topic every other week.",
"feedUrl": "https://gastropod.com/feed",
"author": "Cynthia Graber & Nicola Twilley",
"categories": ["Food", "Science", "History"]
},
{
"id": "discover-this-american-life",
"title": "This American Life",
"description": "Hosted by Ira Glass, each episode weaves together stories around a single theme. Combining investigative reporting with intimate personal narratives, it sets the gold standard for audio storytelling.",
"feedUrl": "https://www.thisamericanlife.org/podcast/rss.xml",
"author": "This American Life",
"categories": ["Storytelling", "Culture"]
},
{
"id": "discover-ted-talks-daily",
"title": "TED Talks Daily",
"description": "Thought-provoking ideas on every subject imaginable from the world's leading thinkers and creators. A new TED Talk every weekday.",
"feedUrl": "https://feeds.feedburner.com/TEDTalks_audio",
"author": "TED",
"categories": ["Education", "Storytelling"]
},
{
"id": "discover-tim-ferriss",
"title": "The Tim Ferriss Show",
"description": "Tim Ferriss deconstructs world-class performers — from billionaires to chess prodigies to athletes — to extract the tools, tactics, and routines you can apply to your own life.",
"feedUrl": "https://rss.art19.com/tim-ferriss-show",
"author": "Tim Ferriss",
"categories": ["Self-Improvement", "Business"]
},
{
"id": "discover-jordan-harbinger",
"title": "The Jordan Harbinger Show",
"description": "In-depth conversations with fascinating minds — from Ray Dalio to arms traffickers. Jordan Harbinger unpacks guests' wisdom into practical nuggets for work, life, and relationships.",
"feedUrl": "https://rss.art19.com/the-jordan-harbinger-show",
"author": "Jordan Harbinger",
"categories": ["Self-Improvement"]
},
{
"id": "discover-on-purpose",
"title": "On Purpose with Jay Shetty",
"description": "Jay Shetty hosts conversations and workshops designed to make you happier, healthier, and more healed. Interviews with experts, celebrities, and thought leaders on mindset and habit-building.",
"feedUrl": "https://rss.art19.com/on-purpose-with-jay-shetty",
"author": "Jay Shetty",
"categories": ["Self-Improvement", "Health"]
},
{
"id": "discover-10-percent-happier",
"title": "10% Happier with Dan Harris",
"description": "Self-help for the skeptical. ABC News anchor Dan Harris explores meditation and mindfulness with scientists, monks, and teachers, born from his own panic attack on live TV.",
"feedUrl": "https://rss.art19.com/ten-percent-happier",
"author": "Dan Harris",
"categories": ["Self-Improvement", "Health", "Philosophy"]
},
{
"id": "discover-school-of-greatness",
"title": "The School of Greatness",
"description": "Former pro athlete Lewis Howes interviews successful people across business, sports, science, and literature to help you unlock your inner greatness and live your best life.",
"feedUrl": "https://rss.art19.com/the-school-of-greatness",
"author": "Lewis Howes",
"categories": ["Self-Improvement", "Business"]
},
{
"id": "discover-sysk",
"title": "Stuff You Should Know",
"description": "If you've ever wanted to know about champagne, satanism, the Stonewall Uprising, chaos theory, LSD, El Nino, true crime or Roswell — Josh and Chuck have got you covered.",
"feedUrl": "https://rss.art19.com/stuff-you-should-know",
"author": "iHeartRadio",
"categories": ["Education", "Comedy"]
},
{
"id": "discover-in-our-time",
"title": "In Our Time",
"description": "Melvyn Bragg and guests on BBC Radio 4 discuss the history of ideas — from the Peloponnesian War to the science of photography. A weekly graduate seminar in audio form since 1998.",
"feedUrl": "https://podcasts.files.bbci.co.uk/b006qykl.rss",
"author": "BBC Radio 4",
"categories": ["History", "Education", "Philosophy"]
}
]
}

View File

@@ -65,6 +65,12 @@ function DiscoverPage() {
}; };
onMount(ensureFocus); onMount(ensureFocus);
// Auto-fetch the featured-shows manifest on first mount (network failure is
// non-fatal — the list stays empty until the user hits refresh).
onMount(() => {
discoverStore.refresh().catch(() => {});
});
onMount(() => { onMount(() => {
nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => { nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => {
if (depth() === 0) return categories()[i]?.id; if (depth() === 0) return categories()[i]?.id;
@@ -243,7 +249,9 @@ function DiscoverPage() {
{podcast.title} {podcast.title}
</text> </text>
<Show when={podcast.isSubscribed}> <Show when={podcast.isSubscribed}>
<text fg={index() === lf() ? theme.surface : theme.success}> <text
fg={index() === lf() ? theme.surface : theme.success}
>
[+] [+]
</text> </text>
</Show> </Show>

View File

@@ -59,6 +59,10 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
let frameTimer: ReturnType<typeof setInterval> | null = null; let frameTimer: ReturnType<typeof setInterval> | null = null;
let sampleBuffer: Float64Array | null = null; let sampleBuffer: Float64Array | null = null;
// Bar count comes from the visualizer config (set in Settings); default 64.
// Single source of truth used for cavacore init, rendering, and seek clicks.
const numBars = () => props.visualizerConfig?.bars ?? 64;
// ── Lifecycle: init cavacore once ────────────────────────────────── // ── Lifecycle: init cavacore once ──────────────────────────────────
const initCava = () => { const initCava = () => {
@@ -83,7 +87,7 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
// Initialize cavacore with current resolution + any overrides // Initialize cavacore with current resolution + any overrides
const config: CavaCoreConfig = { const config: CavaCoreConfig = {
bars: 32, bars: numBars(),
sampleRate: 44100, sampleRate: 44100,
channels: 1, channels: 1,
...props.visualizerConfig, ...props.visualizerConfig,
@@ -143,9 +147,9 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
on( on(
[ [
audio.isPlaying, audio.isPlaying,
() => audio.currentEpisode()?.audioUrl ?? "", // may need to fire an error here () => audio.currentEpisode()?.audioUrl ?? "",
audio.speed, audio.speed,
() => 32, numBars,
], ],
([playing, url, speed]) => { ([playing, url, speed]) => {
if (playing && url) { if (playing && url) {
@@ -204,11 +208,11 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
const renderLine = () => { const renderLine = () => {
const bars = barData(); const bars = barData();
const numBars = 32; const count = numBars();
// If no data yet, show empty placeholder // If no data yet, show empty placeholder
if (bars.length === 0) { if (bars.length === 0) {
const placeholder = ".".repeat(numBars); const placeholder = ".".repeat(count);
return ( return (
<box flexDirection="row" gap={0}> <box flexDirection="row" gap={0}>
<text fg="#3b4252">{placeholder}</text> <text fg="#3b4252">{placeholder}</text>
@@ -216,7 +220,7 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
); );
} }
const played = Math.floor(numBars * playedRatio()); const played = Math.floor(count * playedRatio());
const playedColor = audio.isPlaying() ? "#6fa8ff" : "#7d8590"; const playedColor = audio.isPlaying() ? "#6fa8ff" : "#7d8590";
const futureColor = "#3b4252"; const futureColor = "#3b4252";
@@ -239,8 +243,8 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
}; };
const handleClick = (event: { x: number }) => { const handleClick = (event: { x: number }) => {
const numBars = 32; const count = numBars();
const ratio = event.x / numBars; const ratio = event.x / count;
const next = Math.max( const next = Math.max(
0, 0,
Math.min(audio.duration(), Math.round(audio.duration() * ratio)), Math.min(audio.duration(), Math.round(audio.duration() * ratio)),
@@ -249,7 +253,12 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
}; };
return ( return (
<box border borderColor={theme.border} padding={1} onMouseDown={handleClick}> <box
border
borderColor={theme.border}
padding={1}
onMouseDown={handleClick}
>
{renderLine()} {renderLine()}
</box> </box>
); );

View File

@@ -17,7 +17,7 @@ import {
} from "../utils/app-persistence"; } from "../utils/app-persistence";
const defaultVisualizerSettings: VisualizerSettings = { const defaultVisualizerSettings: VisualizerSettings = {
bars: 32, bars: 64,
sensitivity: 1, sensitivity: 1,
noiseReduction: 0.77, noiseReduction: 0.77,
lowCutOff: 50, lowCutOff: 50,

View File

@@ -1,6 +1,12 @@
/** /**
* Discover store for PodTUI * Discover store for PodTUI
* Manages trending/popular podcasts and category filtering * Manages trending/popular podcasts and category filtering.
*
* The featured-shows list is fetched at runtime from a JSON file hosted in the
* GitHub repo (discover/featured.json on the `master` branch), so the list
* can be updated without shipping a new release. The feed URL, de-duped set,
* and version field act as the cache key — a fresh fetch only happens when the
* version bumps or the cache window (24h) expires.
*/ */
import { createSignal } from "solid-js"; import { createSignal } from "solid-js";
@@ -27,125 +33,113 @@ export const DISCOVER_CATEGORIES: DiscoverCategory[] = [
{ id: "arts", name: "Arts", icon: "@" }, { id: "arts", name: "Arts", icon: "@" },
]; ];
/** Mock trending podcasts */ // ── Remote featured-shows manifest ───────────────────────────────────────────
const TRENDING_PODCASTS: Podcast[] = [ // The raw GitHub URL serving discover/featured.json from the master branch.
{ // Update this file in the repo (no release needed) to refresh the list.
id: "trend-1", const FEATURED_JSON_URL =
title: "AI Today", "https://raw.githubusercontent.com/mikefreno/PodTui/master/discover/featured.json";
description:
"The latest developments in artificial intelligence, machine learning, and their impact on society.", /** Cache window for the remote featured list (24 hours) */
feedUrl: "https://example.com/aitoday.rss", const FEATURED_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
author: "Tech Futures",
categories: ["Technology", "Science"], /** Shape of a single entry in the remote JSON */
interface FeaturedEntry {
id: string;
title: string;
description: string;
feedUrl: string;
author?: string;
categories?: string[];
}
/** Shape of the remote JSON manifest */
interface FeaturedManifest {
version: number;
podcasts: FeaturedEntry[];
}
/** Convert a JSON entry to a runtime Podcast (adding derived fields) */
function entryToPodcast(entry: FeaturedEntry): Podcast {
return {
id: entry.id,
title: entry.title,
description: entry.description,
feedUrl: entry.feedUrl,
author: entry.author,
categories: entry.categories ?? [],
coverUrl: undefined, coverUrl: undefined,
lastUpdated: new Date(), lastUpdated: new Date(),
isSubscribed: false, isSubscribed: false,
}, };
{ }
id: "trend-2",
title: "The History Hour", /** Reconcile isSubscribed state across the discover list against the feed store */
description: function syncSubscriptionState(
"Fascinating stories from history that shaped our world today.", podcasts: Podcast[],
feedUrl: "https://example.com/historyhour.rss", subscribedUrls: Set<string>,
author: "History Channel", subscribedIds: Set<string>,
categories: ["Education", "History"], ): Podcast[] {
lastUpdated: new Date(), return podcasts.map((p) => ({
isSubscribed: false, ...p,
}, isSubscribed: subscribedUrls.has(p.feedUrl) || subscribedIds.has(p.id),
{ }));
id: "trend-3", }
title: "Comedy Gold",
description:
"Weekly stand-up comedy, sketches, and hilarious conversations.",
feedUrl: "https://example.com/comedygold.rss",
author: "Laugh Factory",
categories: ["Comedy", "Entertainment"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-4",
title: "Market Watch",
description: "Daily financial news, stock analysis, and investing tips.",
feedUrl: "https://example.com/marketwatch.rss",
author: "Finance Daily",
categories: ["Business", "News"],
lastUpdated: new Date(),
isSubscribed: true,
},
{
id: "trend-5",
title: "Science Weekly",
description:
"Breaking science news and in-depth analysis of the latest research.",
feedUrl: "https://example.com/scienceweekly.rss",
author: "Science Network",
categories: ["Science", "Education"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-6",
title: "True Crime Files",
description:
"Investigative journalism into real criminal cases and unsolved mysteries.",
feedUrl: "https://example.com/truecrime.rss",
author: "Crime Network",
categories: ["True Crime", "Documentary"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-7",
title: "Wellness Journey",
description:
"Tips for mental and physical health, meditation, and mindful living.",
feedUrl: "https://example.com/wellness.rss",
author: "Health Media",
categories: ["Health", "Self-Help"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-8",
title: "Sports Talk Live",
description:
"Live commentary, analysis, and interviews from the world of sports.",
feedUrl: "https://example.com/sportstalk.rss",
author: "Sports Network",
categories: ["Sports", "News"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-9",
title: "Creative Minds",
description:
"Interviews with artists, designers, and creative professionals.",
feedUrl: "https://example.com/creativeminds.rss",
author: "Arts Weekly",
categories: ["Arts", "Culture"],
lastUpdated: new Date(),
isSubscribed: false,
},
{
id: "trend-10",
title: "Dev Talk",
description:
"Software development, programming tutorials, and tech career advice.",
feedUrl: "https://example.com/devtalk.rss",
author: "Code Academy",
categories: ["Technology", "Education"],
lastUpdated: new Date(),
isSubscribed: true,
},
];
/** Create discover store */ /** Create discover store */
export function createDiscoverStore() { export function createDiscoverStore() {
const [selectedCategory, setSelectedCategory] = createSignal<string>("all"); const [selectedCategory, setSelectedCategory] = createSignal<string>("all");
const [isLoading, setIsLoading] = createSignal(false); const [isLoading, setIsLoading] = createSignal(false);
const [podcasts, setPodcasts] = createSignal<Podcast[]>(TRENDING_PODCASTS); const [podcasts, setPodcasts] = createSignal<Podcast[]>([]);
// In-memory cache timestamp for the remote manifest (within 24h, skip refetch)
let cachedAt = 0;
/** Reconcile local isSubscribed flags with the feed store */
const syncSubscriptions = () => {
const feedStore = useFeedStore();
const feeds = feedStore.feeds();
const urls = new Set(feeds.map((f) => f.podcast.feedUrl));
const ids = new Set(feeds.map((f) => f.podcast.id));
setPodcasts((prev) => syncSubscriptionState(prev, urls, ids));
};
/** Fetch the featured-shows manifest from GitHub if stale */
const refresh = async () => {
setIsLoading(true);
try {
// Skip if cache is still fresh
const now = Date.now();
if (now - cachedAt < FEATURED_CACHE_TTL_MS) {
syncSubscriptions();
return;
}
const resp = await fetch(FEATURED_JSON_URL, {
headers: { "User-Agent": "PodTUI/1.0" },
});
if (!resp.ok) {
syncSubscriptions();
return;
}
const manifest = (await resp.json()) as FeaturedManifest;
if (!manifest?.podcasts?.length) {
syncSubscriptions();
return;
}
// Build the podcast list from the manifest entries
const fetched = manifest.podcasts.map(entryToPodcast);
cachedAt = now;
setPodcasts(fetched);
// Reflect current feed-store subscriptions
syncSubscriptions();
} catch {
// Network failure — keep whatever we have (stale or empty)
} finally {
setIsLoading(false);
}
};
/** Get filtered podcasts by category */ /** Get filtered podcasts by category */
const filteredPodcasts = () => { const filteredPodcasts = () => {
@@ -198,15 +192,6 @@ export function createDiscoverStore() {
} }
}; };
/** Refresh trending podcasts (mock) */
const refresh = async () => {
setIsLoading(true);
// Simulate network delay
await new Promise((r) => setTimeout(r, 500));
// In real app, would fetch from API
setIsLoading(false);
};
return { return {
// State // State
selectedCategory, selectedCategory,

View File

@@ -62,7 +62,7 @@ export type DesktopTheme = {
}; };
export type VisualizerSettings = { export type VisualizerSettings = {
/** Number of frequency bars (8128, default: 32) */ /** Number of frequency bars (8128, default: 64) */
bars: number; bars: number;
/** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */ /** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */
sensitivity: number; sensitivity: number;

View File

@@ -11,18 +11,18 @@
*/ */
/** PCM output format constants */ /** PCM output format constants */
const SAMPLE_RATE = 44100 const SAMPLE_RATE = 44100;
const CHANNELS = 1 const CHANNELS = 1;
const BYTES_PER_SAMPLE = 2 // s16le const BYTES_PER_SAMPLE = 2; // s16le
/** How many samples to buffer (~1 second) */ /** How many samples to buffer (~1 second) */
const RING_BUFFER_SAMPLES = SAMPLE_RATE const RING_BUFFER_SAMPLES = SAMPLE_RATE;
export interface AudioStreamReaderOptions { export interface AudioStreamReaderOptions {
/** Audio URL or file path to decode */ /** Audio URL or file path to decode */
url: string url: string;
/** Sample rate (default: 44100) */ /** Sample rate (default: 44100) */
sampleRate?: number sampleRate?: number;
} }
/** /**
@@ -30,32 +30,32 @@ export interface AudioStreamReaderOptions {
* Each start() increments this; the read loop checks it to know * Each start() increments this; the read loop checks it to know
* if it's been superseded and should bail out. * if it's been superseded and should bail out.
*/ */
let globalGeneration = 0 let globalGeneration = 0;
export class AudioStreamReader { export class AudioStreamReader {
private proc: ReturnType<typeof Bun.spawn> | null = null private proc: ReturnType<typeof Bun.spawn> | null = null;
private ringBuffer: Float64Array private ringBuffer: Float64Array;
private writePos = 0 private writePos = 0;
private totalSamplesWritten = 0 private totalSamplesWritten = 0;
private _running = false private _running = false;
private generation = 0 private generation = 0;
readonly url: string readonly url: string;
private sampleRate: number private sampleRate: number;
constructor(options: AudioStreamReaderOptions) { constructor(options: AudioStreamReaderOptions) {
this.url = options.url this.url = options.url;
this.sampleRate = options.sampleRate ?? SAMPLE_RATE this.sampleRate = options.sampleRate ?? SAMPLE_RATE;
this.ringBuffer = new Float64Array(RING_BUFFER_SAMPLES) this.ringBuffer = new Float64Array(RING_BUFFER_SAMPLES);
} }
/** Whether the reader is actively reading samples. */ /** Whether the reader is actively reading samples. */
get running(): boolean { get running(): boolean {
return this._running return this._running;
} }
/** Total number of samples written since start(). */ /** Total number of samples written since start(). */
get samplesWritten(): number { get samplesWritten(): number {
return this.totalSamplesWritten return this.totalSamplesWritten;
} }
/** /**
@@ -72,72 +72,88 @@ export class AudioStreamReader {
*/ */
start(startPosition = 0, speed = 1): void { start(startPosition = 0, speed = 1): void {
// Always kill the previous process first — no early return on _running // Always kill the previous process first — no early return on _running
this.killProcess() this.killProcess();
if (!Bun.which("ffmpeg")) { if (!Bun.which("ffmpeg")) {
throw new Error("ffmpeg not found — required for audio visualization") throw new Error("ffmpeg not found — required for audio visualization");
} }
// Increment generation so any lingering read loop from a previous // Increment generation so any lingering read loop from a previous
// start() will see a mismatch and exit. // start() will see a mismatch and exit.
this.generation = ++globalGeneration this.generation = ++globalGeneration;
const args = [ const args = [
"ffmpeg", "ffmpeg",
"-loglevel", "quiet", "-loglevel",
"-reconnect", "1", "quiet",
"-reconnect_streamed", "1", // Read input at native frame rate so decoded PCM stays in sync with
"-reconnect_delay_max", "5", // real-time playback. Without -re, ffmpeg greedily decodes the whole
] // file as fast as possible: the ring buffer fills with audio seconds
// ahead of the player (laggy bars), then the process exits when it
// hits EOF (bars freeze ~10s in).
"-re",
"-reconnect",
"1",
"-reconnect_streamed",
"1",
"-reconnect_delay_max",
"5",
];
// Seek before input for network efficiency // Seek before input for network efficiency
if (startPosition > 0) { if (startPosition > 0) {
args.push("-ss", String(startPosition)) args.push("-ss", String(startPosition));
} }
args.push("-i", this.url) args.push("-i", this.url);
// Apply speed via atempo filter if not 1x. // Apply speed via atempo filter if not 1x.
// ffmpeg atempo only supports 0.5100.0; chain multiple for extremes. // ffmpeg atempo only supports 0.5100.0; chain multiple for extremes.
if (speed !== 1 && speed > 0) { if (speed !== 1 && speed > 0) {
args.push("-af", buildAtempoChain(speed)) args.push("-af", buildAtempoChain(speed));
} }
args.push( args.push(
"-ac", String(CHANNELS), "-ac",
"-ar", String(this.sampleRate), String(CHANNELS),
"-f", "s16le", "-ar",
"-acodec", "pcm_s16le", String(this.sampleRate),
"-f",
"s16le",
"-acodec",
"pcm_s16le",
"-", "-",
) );
this.proc = Bun.spawn(args, { this.proc = Bun.spawn(args, {
stdout: "pipe", stdout: "pipe",
stderr: "ignore", stderr: "ignore",
stdin: "ignore", stdin: "ignore",
}) });
this._running = true this._running = true;
this.writePos = 0 this.writePos = 0;
this.totalSamplesWritten = 0 this.totalSamplesWritten = 0;
// Capture generation for this run // Capture generation for this run
const myGeneration = this.generation const myGeneration = this.generation;
// Start async reading loop // Start async reading loop
this.readLoop(myGeneration) this.readLoop(myGeneration);
// Detect process exit // Detect process exit
this.proc.exited.then(() => { this.proc.exited
.then(() => {
// Only clear _running if this is still the current generation // Only clear _running if this is still the current generation
if (this.generation === myGeneration) { if (this.generation === myGeneration) {
this._running = false this._running = false;
}
}).catch(() => {
if (this.generation === myGeneration) {
this._running = false
} }
}) })
.catch(() => {
if (this.generation === myGeneration) {
this._running = false;
}
});
} }
/** /**
@@ -148,21 +164,27 @@ export class AudioStreamReader {
* @returns Number of samples written to `out`. * @returns Number of samples written to `out`.
*/ */
read(out: Float64Array): number { read(out: Float64Array): number {
const available = Math.min(out.length, this.totalSamplesWritten, this.ringBuffer.length) const available = Math.min(
if (available <= 0) return 0 out.length,
this.totalSamplesWritten,
this.ringBuffer.length,
);
if (available <= 0) return 0;
// Read the most recent `available` samples from the ring buffer // Read the most recent `available` samples from the ring buffer
const readStart = (this.writePos - available + this.ringBuffer.length) % this.ringBuffer.length const readStart =
(this.writePos - available + this.ringBuffer.length) %
this.ringBuffer.length;
if (readStart + available <= this.ringBuffer.length) { if (readStart + available <= this.ringBuffer.length) {
out.set(this.ringBuffer.subarray(readStart, readStart + available)) out.set(this.ringBuffer.subarray(readStart, readStart + available));
} else { } else {
const firstChunk = this.ringBuffer.length - readStart const firstChunk = this.ringBuffer.length - readStart;
out.set(this.ringBuffer.subarray(readStart, this.ringBuffer.length)) out.set(this.ringBuffer.subarray(readStart, this.ringBuffer.length));
out.set(this.ringBuffer.subarray(0, available - firstChunk), firstChunk) out.set(this.ringBuffer.subarray(0, available - firstChunk), firstChunk);
} }
return available return available;
} }
/** /**
@@ -171,59 +193,67 @@ export class AudioStreamReader {
*/ */
stop(): void { stop(): void {
// Bump generation to invalidate any running read loop // Bump generation to invalidate any running read loop
this.generation = ++globalGeneration this.generation = ++globalGeneration;
this._running = false this._running = false;
this.killProcess() this.killProcess();
this.writePos = 0 this.writePos = 0;
this.totalSamplesWritten = 0 this.totalSamplesWritten = 0;
} }
/** /**
* Restart the reader at a new position and/or speed. * Restart the reader at a new position and/or speed.
*/ */
restart(startPosition = 0, speed = 1): void { restart(startPosition = 0, speed = 1): void {
this.start(startPosition, speed) this.start(startPosition, speed);
} }
/** Kill the ffmpeg process without touching generation/state. */ /** Kill the ffmpeg process without touching generation/state. */
private killProcess(): void { private killProcess(): void {
if (this.proc) { if (this.proc) {
try { this.proc.kill() } catch { /* ignore */ } try {
this.proc = null this.proc.kill();
} catch {
/* ignore */
}
this.proc = null;
} }
} }
/** Internal: continuously reads stdout from ffmpeg and fills the ring buffer. */ /** Internal: continuously reads stdout from ffmpeg and fills the ring buffer. */
private async readLoop(myGeneration: number): Promise<void> { private async readLoop(myGeneration: number): Promise<void> {
const stdout = this.proc?.stdout const stdout = this.proc?.stdout;
if (!stdout || typeof stdout === "number") return if (!stdout || typeof stdout === "number") return;
const reader = (stdout as ReadableStream<Uint8Array>).getReader() const reader = (stdout as ReadableStream<Uint8Array>).getReader();
try { try {
while (this.generation === myGeneration) { while (this.generation === myGeneration) {
const { done, value } = await reader.read() const { done, value } = await reader.read();
if (done || this.generation !== myGeneration) break if (done || this.generation !== myGeneration) break;
if (!value || value.byteLength === 0) continue if (!value || value.byteLength === 0) continue;
const sampleCount = Math.floor(value.byteLength / BYTES_PER_SAMPLE) const sampleCount = Math.floor(value.byteLength / BYTES_PER_SAMPLE);
if (sampleCount === 0) continue if (sampleCount === 0) continue;
const int16View = new Int16Array( const int16View = new Int16Array(
value.buffer, value.buffer,
value.byteOffset, value.byteOffset,
sampleCount, sampleCount,
) );
for (let i = 0; i < sampleCount; i++) { for (let i = 0; i < sampleCount; i++) {
this.ringBuffer[this.writePos] = int16View[i] this.ringBuffer[this.writePos] = int16View[i];
this.writePos = (this.writePos + 1) % this.ringBuffer.length this.writePos = (this.writePos + 1) % this.ringBuffer.length;
this.totalSamplesWritten++ this.totalSamplesWritten++;
} }
} }
} catch { } catch {
// Stream ended or process killed — expected during stop() // Stream ended or process killed — expected during stop()
} finally { } finally {
try { reader.releaseLock() } catch { /* ignore */ } try {
reader.releaseLock();
} catch {
/* ignore */
}
} }
} }
} }
@@ -234,18 +264,18 @@ export class AudioStreamReader {
* multiple filters for extreme values (e.g. 0.25 = atempo=0.5,atempo=0.5). * multiple filters for extreme values (e.g. 0.25 = atempo=0.5,atempo=0.5).
*/ */
function buildAtempoChain(speed: number): string { function buildAtempoChain(speed: number): string {
const parts: string[] = [] const parts: string[] = [];
let remaining = Math.max(0.25, Math.min(4, speed)) let remaining = Math.max(0.25, Math.min(4, speed));
while (remaining > 100) { while (remaining > 100) {
parts.push("atempo=100.0") parts.push("atempo=100.0");
remaining /= 100 remaining /= 100;
} }
while (remaining < 0.5) { while (remaining < 0.5) {
parts.push("atempo=0.5") parts.push("atempo=0.5");
remaining /= 0.5 remaining /= 0.5;
} }
parts.push(`atempo=${remaining}`) parts.push(`atempo=${remaining}`);
return parts.join(",") return parts.join(",");
} }

View File

@@ -16,27 +16,29 @@
* ``` * ```
*/ */
import { dlopen, FFIType, ptr } from "bun:ffi" import { dlopen, FFIType, ptr } from "bun:ffi";
import { existsSync } from "fs" import { existsSync } from "fs";
import { join, dirname } from "path" import { join, dirname } from "path";
// ── Types ──────────────────────────────────────────────────────────── // ── Types ────────────────────────────────────────────────────────────
export interface CavaCoreConfig { export interface CavaCoreConfig {
/** Number of frequency bars (default: 32) */ /** Number of frequency bars (default: 32) */
bars?: number bars?: number;
/** Audio sample rate in Hz (default: 44100) */ /** Audio sample rate in Hz (default: 44100) */
sampleRate?: number sampleRate?: number;
/** Number of audio channels (default: 1 = mono) */ /** Number of audio channels (default: 1 = mono) */
channels?: number channels?: number;
/** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */ /** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */
autosens?: number autosens?: number;
/** Noise reduction factor 0.01.0 (default: 0.77) */ /** Noise reduction factor 0.01.0 (default: 0.77) */
noiseReduction?: number noiseReduction?: number;
/** Low frequency cutoff in Hz (default: 50) */ /** Low frequency cutoff in Hz (default: 50) */
lowCutOff?: number lowCutOff?: number;
/** High frequency cutoff in Hz (default: 10000) */ /** High frequency cutoff in Hz (default: 10000) */
highCutOff?: number highCutOff?: number;
/** Output scaling mode: 0 = linear (default), 1 = decibel */
scalingMode?: number;
} }
const DEFAULTS: Required<CavaCoreConfig> = { const DEFAULTS: Required<CavaCoreConfig> = {
@@ -47,20 +49,25 @@ const DEFAULTS: Required<CavaCoreConfig> = {
noiseReduction: 0.77, noiseReduction: 0.77,
lowCutOff: 50, lowCutOff: 50,
highCutOff: 10000, highCutOff: 10000,
} scalingMode: 0,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
type CavaLib = { symbols: Record<string, (...args: any[]) => any>; close(): void } type CavaLib = {
symbols: Record<string, (...args: any[]) => any>;
close(): void;
};
// ── Library resolution ─────────────────────────────────────────────── // ── Library resolution ───────────────────────────────────────────────
function findLibrary(): string | null { function findLibrary(): string | null {
const platform = process.platform const platform = process.platform;
const libName = platform === "darwin" const libName =
platform === "darwin"
? "libcavacore.dylib" ? "libcavacore.dylib"
: platform === "win32" : platform === "win32"
? "cavacore.dll" ? "cavacore.dll"
: "libcavacore.so" : "libcavacore.so";
// Candidate paths, in priority order: // Candidate paths, in priority order:
// 1. src/native/ (development) // 1. src/native/ (development)
@@ -70,39 +77,39 @@ function findLibrary(): string | null {
join(import.meta.dir, "..", "native", libName), join(import.meta.dir, "..", "native", libName),
join(dirname(process.execPath), libName), join(dirname(process.execPath), libName),
join(process.cwd(), "dist", libName), join(process.cwd(), "dist", libName),
] ];
for (const candidate of candidates) { for (const candidate of candidates) {
if (existsSync(candidate)) return candidate if (existsSync(candidate)) return candidate;
} }
return null return null;
} }
// ── CavaCore class ─────────────────────────────────────────────────── // ── CavaCore class ───────────────────────────────────────────────────
export class CavaCore { export class CavaCore {
private lib: CavaLib private lib: CavaLib;
private plan: ReturnType<CavaLib["symbols"]["cava_init"]> | null = null private plan: ReturnType<CavaLib["symbols"]["cava_init"]> | null = null;
private inputBuffer: Float64Array | null = null private inputBuffer: Float64Array | null = null;
private outputBuffer: Float64Array | null = null private outputBuffer: Float64Array | null = null;
private _bars = 0 private _bars = 0;
private _channels = 1 private _channels = 1;
private _destroyed = false private _destroyed = false;
/** Use loadCavaCore() instead of constructing directly. */ /** Use loadCavaCore() instead of constructing directly. */
constructor(lib: CavaLib) { constructor(lib: CavaLib) {
this.lib = lib this.lib = lib;
} }
/** Number of frequency bars configured. */ /** Number of frequency bars configured. */
get bars(): number { get bars(): number {
return this._bars return this._bars;
} }
/** Whether this instance has been initialized (and not yet destroyed). */ /** Whether this instance has been initialized (and not yet destroyed). */
get isReady(): boolean { get isReady(): boolean {
return this.plan !== null && !this._destroyed return this.plan !== null && !this._destroyed;
} }
/** /**
@@ -112,12 +119,12 @@ export class CavaCore {
*/ */
init(config: CavaCoreConfig = {}): void { init(config: CavaCoreConfig = {}): void {
if (this.plan) { if (this.plan) {
this.destroy() this.destroy();
} }
const cfg = { ...DEFAULTS, ...config } const cfg = { ...DEFAULTS, ...config };
this._bars = cfg.bars this._bars = cfg.bars;
this._channels = cfg.channels this._channels = cfg.channels;
this.plan = this.lib.symbols.cava_init( this.plan = this.lib.symbols.cava_init(
cfg.bars, cfg.bars,
@@ -127,15 +134,16 @@ export class CavaCore {
cfg.noiseReduction, cfg.noiseReduction,
cfg.lowCutOff, cfg.lowCutOff,
cfg.highCutOff, cfg.highCutOff,
) cfg.scalingMode,
);
if (!this.plan) { if (!this.plan) {
throw new Error("cava_init returned null — initialization failed") throw new Error("cava_init returned null — initialization failed");
} }
// Pre-allocate output buffer (bars * channels) // Pre-allocate output buffer (bars * channels)
this.outputBuffer = new Float64Array(cfg.bars * cfg.channels) this.outputBuffer = new Float64Array(cfg.bars * cfg.channels);
this._destroyed = false this._destroyed = false;
} }
/** /**
@@ -148,23 +156,23 @@ export class CavaCore {
*/ */
execute(samples: Float64Array): Float64Array { execute(samples: Float64Array): Float64Array {
if (!this.plan || !this.outputBuffer) { if (!this.plan || !this.outputBuffer) {
throw new Error("CavaCore not initialized — call init() first") throw new Error("CavaCore not initialized — call init() first");
} }
// Reuse input buffer if same size, otherwise allocate new // Reuse input buffer if same size, otherwise allocate new
if (!this.inputBuffer || this.inputBuffer.length !== samples.length) { if (!this.inputBuffer || this.inputBuffer.length !== samples.length) {
this.inputBuffer = new Float64Array(samples.length) this.inputBuffer = new Float64Array(samples.length);
} }
this.inputBuffer.set(samples) this.inputBuffer.set(samples);
this.lib.symbols.cava_execute( this.lib.symbols.cava_execute(
ptr(this.inputBuffer), ptr(this.inputBuffer),
samples.length, samples.length,
ptr(this.outputBuffer), ptr(this.outputBuffer),
this.plan, this.plan,
) );
return this.outputBuffer return this.outputBuffer;
} }
/** /**
@@ -173,12 +181,12 @@ export class CavaCore {
*/ */
destroy(): void { destroy(): void {
if (this.plan && !this._destroyed) { if (this.plan && !this._destroyed) {
this.lib.symbols.cava_destroy(this.plan) this.lib.symbols.cava_destroy(this.plan);
this.plan = null this.plan = null;
this._destroyed = true this._destroyed = true;
} }
this.inputBuffer = null this.inputBuffer = null;
this.outputBuffer = null this.outputBuffer = null;
} }
} }
@@ -191,8 +199,8 @@ export class CavaCore {
*/ */
export function loadCavaCore(): CavaCore | null { export function loadCavaCore(): CavaCore | null {
try { try {
const libPath = findLibrary() const libPath = findLibrary();
if (!libPath) return null if (!libPath) return null;
const lib = dlopen(libPath, { const lib = dlopen(libPath, {
cava_init: { cava_init: {
@@ -204,6 +212,7 @@ export function loadCavaCore(): CavaCore | null {
FFIType.double, // noise_reduction FFIType.double, // noise_reduction
FFIType.i32, // low_cut_off FFIType.i32, // low_cut_off
FFIType.i32, // high_cut_off FFIType.i32, // high_cut_off
FFIType.i32, // scaling_mode
], ],
returns: FFIType.ptr, returns: FFIType.ptr,
}, },
@@ -220,11 +229,11 @@ export function loadCavaCore(): CavaCore | null {
args: [FFIType.ptr], // plan args: [FFIType.ptr], // plan
returns: FFIType.void, returns: FFIType.void,
}, },
}) });
return new CavaCore(lib as CavaLib) return new CavaCore(lib as CavaLib);
} catch { } catch {
// Library load failed — missing dylib, wrong arch, etc. // Library load failed — missing dylib, wrong arch, etc.
return null return null;
} }
} }

View File

@@ -2,14 +2,29 @@
* Smoke test: load libcavacore.dylib via bun:ffi, init → execute → destroy. * Smoke test: load libcavacore.dylib via bun:ffi, init → execute → destroy.
* Run: bun tests/cavacore-smoke.ts * Run: bun tests/cavacore-smoke.ts
*/ */
import { dlopen, FFIType, ptr } from "bun:ffi" import { dlopen, FFIType, ptr } from "bun:ffi";
import { join } from "path" import { join } from "path";
const libPath = join(import.meta.dir, "..", "src", "native", "libcavacore.dylib") const libPath = join(
import.meta.dir,
"..",
"src",
"native",
"libcavacore.dylib",
);
const lib = dlopen(libPath, { const lib = dlopen(libPath, {
cava_init: { cava_init: {
args: [FFIType.i32, FFIType.u32, FFIType.i32, FFIType.i32, FFIType.double, FFIType.i32, FFIType.i32], args: [
FFIType.i32,
FFIType.u32,
FFIType.i32,
FFIType.i32,
FFIType.double,
FFIType.i32,
FFIType.i32,
FFIType.i32,
],
returns: FFIType.ptr, returns: FFIType.ptr,
}, },
cava_execute: { cava_execute: {
@@ -20,39 +35,52 @@ const lib = dlopen(libPath, {
args: [FFIType.ptr], args: [FFIType.ptr],
returns: FFIType.void, returns: FFIType.void,
}, },
}) });
const bars = 10 const bars = 10;
const rate = 44100 const rate = 44100;
const channels = 1 const channels = 1;
// Init // Init
const plan = lib.symbols.cava_init(bars, rate, channels, 1, 0.77, 50, 10000) const plan = lib.symbols.cava_init(
bars,
rate,
channels,
1,
0.77,
50,
10000,
0 /* CAVA_SCALING_LINEAR */,
);
if (!plan) { if (!plan) {
console.error("FAIL: cava_init returned null") console.error("FAIL: cava_init returned null");
process.exit(1) process.exit(1);
} }
console.log("cava_init OK, plan pointer:", plan) console.log("cava_init OK, plan pointer:", plan);
// Generate a 200Hz sine wave test signal // Generate a 200Hz sine wave test signal
const bufferSize = 512 const bufferSize = 512;
const cavaIn = new Float64Array(bufferSize) const cavaIn = new Float64Array(bufferSize);
const cavaOut = new Float64Array(bars * channels) const cavaOut = new Float64Array(bars * channels);
for (let k = 0; k < 100; k++) { for (let k = 0; k < 100; k++) {
for (let n = 0; n < bufferSize; n++) { for (let n = 0; n < bufferSize; n++) {
cavaIn[n] = Math.sin(2 * Math.PI * 200 / rate * (n + k * bufferSize)) * 20000 cavaIn[n] =
Math.sin(((2 * Math.PI * 200) / rate) * (n + k * bufferSize)) * 20000;
} }
lib.symbols.cava_execute(ptr(cavaIn), bufferSize, ptr(cavaOut), plan) lib.symbols.cava_execute(ptr(cavaIn), bufferSize, ptr(cavaOut), plan);
} }
console.log("cava_execute OK, output:", Array.from(cavaOut).map(v => v.toFixed(3))) console.log(
"cava_execute OK, output:",
Array.from(cavaOut).map((v) => v.toFixed(3)),
);
// Check that bar 2 (200Hz) has the peak // Check that bar 2 (200Hz) has the peak
const maxIdx = cavaOut.indexOf(Math.max(...cavaOut)) const maxIdx = cavaOut.indexOf(Math.max(...cavaOut));
console.log(`Peak at bar ${maxIdx} (expected ~2 for 200Hz)`) console.log(`Peak at bar ${maxIdx} (expected ~2 for 200Hz)`);
// Destroy // Destroy
lib.symbols.cava_destroy(plan) lib.symbols.cava_destroy(plan);
console.log("cava_destroy OK") console.log("cava_destroy OK");
console.log("\nSMOKE TEST PASSED") console.log("\nSMOKE TEST PASSED");