Search YouTube from a pane and play picks in the pane or a floating mpv window

Search YouTube and watch videos inside a Claude Code pane, with sound, without leaving the terminal.

/youtube <search> lists results. Pick one and it plays in the pane./youtube <link> plays that video directly. It accepts youtu.be, watch?v=, /shorts/, /embed/ and /live/ links.window button opens the video in an mpv window instead.ffmpeg and ffplay from FFmpeg: brew install yt-dlp ffmpegwindow button: brew install mpvEach time you run /youtube, the mod checks Homebrew for a newer yt-dlp and upgrades it. YouTube changes often, and an old yt-dlp is the most common reason videos stop playing.
Clone the repo, then load it as a plugin folder:
git clone https://github.com/brogrammerMW/claude-youtube-mod.git
claude --plugin-dir ./claude-youtube-mod
To load it in every session, add the folder to a local plugin marketplace and install it with claude plugin install.
| Key | Action |
|---|---|
k | Pause / play |
j | Back 10 seconds |
l | Forward 10 seconds |
s | Stop |
m | Open in an mpv window |
v | Switch view: auto, pixels, blocks |
Tab | Move between the search bar, buttons and results |
↑ ↓ | Scroll to the description and links |
The j, k, l, s, m and v keys only work while the search bar is empty, so you can type searches freely.
Pause and skip. Pausing ends the pipeline and remembers the spot. Play and skips start a new one there: ffmpeg drops everything before that spot as fast as the download allows, then plays in real time. A skip far into a long video waits for that much to download.
If in-pane playback fails, the pane says why. mpv only opens when you press window.
claude plugin validate .
claude plugin test .
Playback logic lives in hooks/player.ts and is tested in hooks/player.test.ts. The engine wiring and drawing live in hooks/register.tsx.
The in-pane video approach follows refact0r/claude-surf (MIT). See NOTICE.md.
hooks/register.tsx 600 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register } from 'claude-code'
3
4import type { Video } from '../types'
5import {
6 blankCells, cellBox, clock, compact, decodeSize, decoderArgv, detailsArgv, downloadArgv, fitBox, FPS, linksIn,
7 lookupArgv, nextOverride, parseFormats, parseMeta, pickMode, rgbToBlocks, seekTarget, soundArgv, videoIdFrom,
8} from './player'
9import type { FrameSize, Formats, Meta, Override, PlayerMode, TermEnv } from './player'
10
11const PANE = 'youtube'
12// Theme color names, so the pane follows the person's light, dark or color-blind theme.
13// Red is the one accent: YouTube's own mark for "this is playing".
14const C = { accent: 'error', text: 'text', dim: 'inactive', faint: 'subtle', link: 'suggestion', ok: 'success' }
15const DETAIL_ROWS = 4 // title, meta strip, controls, one spacer stay visible under the video
16const FRAME_ROWS = 4 // the centered heading and the search bar above, plus the screen border's top and bottom
17const FRAME_COLS = 2 // the screen border's left and right
18const MAX_DESCRIPTION = 4000
19const results = atom({ plugin: 'youtube', key: 'results' } as const, [])
20const status = atom({ plugin: 'youtube', key: 'status' } as const, 'Type a search and press Enter.')
21const playing = atom({ plugin: 'youtube', key: 'playing' } as const, '')
22const mode = atom({ plugin: 'youtube', key: 'mode' } as const, 'blocks' as PlayerMode)
23const hasDraft = atom({ plugin: 'youtube', key: 'hasDraft' } as const, false)
24const submits = atom({ plugin: 'youtube', key: 'submits' } as const, 0)
25const override = atom({ plugin: 'youtube', key: 'override' } as const, 'auto' as Override)
26const paused = atom({ plugin: 'youtube', key: 'paused' } as const, false)
27const SKIP_SECONDS = 10
28
29export function parseResults(stdout: string): Video[] {
30 return stdout
31 .split('\n')
32 .map(line => line.split('\t'))
33 .filter(cols => cols.length >= 2 && /^[\w-]{11}$/.test(cols[0] ?? ''))
34 .map(([id = '', title = '', channel = '', duration = '']) => ({
35 id,
36 title,
37 channel: channel === 'NA' ? '' : channel,
38 duration: duration === 'NA' ? 'live' : duration,
39 }))
40}
41
42async function search($: Engine, query: string) {
43 const q = query.trim()
44 if (!q) return
45 await update($, status, () => `Searching "${q}"…`)
46 try {
47 const { exitCode, stdout, stderr } = await $.process.run(
48 ['yt-dlp', `ytsearch10:${q}`, '--flat-playlist', '--no-warnings',
49 '--print', '%(id)s\t%(title)s\t%(channel)s\t%(duration_string)s'],
50 { timeoutMs: 45_000 },
51 )
52 const found = parseResults(stdout)
53 await update($, results, () => found)
54 await update($, status, () =>
55 exitCode !== 0 ? `yt-dlp failed: ${stderr.trim().split('\n').pop()}`
56 : found.length === 0 ? 'No results.'
57 : `${found.length} results for "${q}". Pick one to play.`)
58 } catch (err) {
59 await update($, status, () => `Search failed: ${String(err)} (is yt-dlp installed? brew install yt-dlp)`)
60 }
61}
62
63async function playMpv($: Engine, v: Video) {
64 const url = `https://www.youtube.com/watch?v=${v.id}`
65 await update($, status, () => `Playing: ${v.title}`)
66 // The child lives as long as this loop; mpv closing ends it.
67 void (async () => {
68 let failure = ''
69 try {
70 const player = $.process.spawn({
71 argv: ['mpv', '--force-window=immediate', '--ontop', '--autofit=640x360',
72 '--geometry=100%:0%', `--title=${v.title}`, url],
73 })
74 let stderr = ''
75 for (let step = await player.next(); ; step = await player.next()) {
76 if (step.done) {
77 if (step.value.code !== 0) failure = stderr.trim().split('\n').pop() || `mpv exited ${step.value.code}`
78 break
79 }
80 if (step.value.stream === 'stderr') stderr = (stderr + step.value.text).slice(-2000)
81 }
82 } catch (err) {
83 failure = `mpv did not start: ${String(err)}`
84 }
85 if (failure) {
86 // mpv failed (missing, or YouTube refused the stream): use YouTube's own player in the browser.
87 await update($, status, () => `mpv failed (${failure.slice(0, 120)}); opened in browser instead.`)
88 await $.process.run(['open', url])
89 }
90 })()
91}
92
93// ---- In-pane player (approach: refact0r/claude-surf, see NOTICE.md) ----
94
95type Handle = ReturnType<Engine['process']['spawn']>
96type Run = {
97 id: number
98 video: Video
99 pageUrl: string
100 dir: string
101 mode: PlayerMode
102 meta?: Meta
103 /** The fixed size ffmpeg decodes at: the pane scales it, so resizing restarts nothing. */
104 size?: FrameSize
105 /** yt-dlp's saved details file and the chosen formats: what a new leg starts from. */
106 info: string
107 formats?: Formats
108 /** One leg = one set of children playing from `offset`. Pause and skips end it; play and skips start the next. */
109 leg: number
110 offset: number
111 /** When the current leg's first frame showed: position = offset + time since. */
112 startedAt?: number
113 paused: boolean
114 /** The current leg's frame file: a new name per leg, so an old leg's frame never counts as new. */
115 framePath: string
116 /** Downloads, decoder and sound player of the current leg, all ended when it ends. */
117 children: Handle[]
118 /** Last error lines per child, for the message when playback fails. */
119 errors: Record<string, string>
120 ticker?: { cancel: () => void }
121 decoderAt: number
122 gotFrame: boolean
123 lastMtime: number
124 generation: number
125 denies: number
126 busy: boolean
127}
128
129const FIRST_FRAME_MS = 20_000
130const POLL_MS = 15
131const DENY_LIMIT = 6 // ponytail: a deny also means "not mounted yet" during a redraw; 6 frames (~0.4s) is past that race
132const BLACK_PIXEL = { rgba: 'AAAA/w==', width: 1, height: 1 }
133
134let run: Run | undefined
135let runCounter = 0
136let envCache: TermEnv | undefined
137// What the last render drew: the only size a blit may name.
138let shown: { mode: PlayerMode; cols: number; rows: number } | undefined
139
140async function readEnv($: Engine): Promise<TermEnv> {
141 return {
142 termProgram: await $.env.get('TERM_PROGRAM'),
143 term: await $.env.get('TERM'),
144 kittyWindow: await $.env.get('KITTY_WINDOW_ID'),
145 }
146}
147
148// Drains a child's pieces; resolves with its exit code (null when killed). Rejects if it cannot start.
149async function pump(child: Handle, onPiece: (stream: 'stdout' | 'stderr', text: string) => void): Promise<number | null> {
150 for (let step = await child.next(); ; step = await child.next()) {
151 if (step.done) return step.value.code
152 onPiece(step.value.stream, step.value.text)
153 }
154}
155
156const lastLine = (text: string) => text.trim().split('\n').pop() ?? ''
157
158// Starts one child for this run and keeps its stderr tail; resolves with its exit code.
159async function child($: Engine, r: Run, name: string, argv: string[]): Promise<number | null> {
160 const h = $.process.spawn({ argv })
161 r.children.push(h)
162 const errors = r.errors // this leg's: an ended child must not blame the next leg
163 let stderr = ''
164 try {
165 return await pump(h, (stream, text) => { if (stream === 'stderr') stderr = (stderr + text).slice(-1000) })
166 } catch (err) {
167 stderr = String(err)
168 return -1
169 } finally {
170 if (stderr.trim()) errors[name] = lastLine(stderr)
171 }
172}
173
174// The player's search bar: hotkeys stay armed only while it is empty.
175async function draftChanged($: Engine, value: string) {
176 const has = value.length > 0
177 if ((await read($, hasDraft)) !== has) await update($, hasDraft, () => has)
178}
179
180async function submitFromPlayer($: Engine, value: string) {
181 await update($, hasDraft, () => false)
182 await update($, submits, n => n + 1) // a new key redraws the bar empty
183 return submitQuery($, value)
184}
185
186// The search bars: a YouTube link plays that video, anything else searches.
187async function submitQuery($: Engine, value: string) {
188 const id = videoIdFrom(value)
189 return id ? playLink($, id) : search($, value)
190}
191
192// A pasted link plays that video directly: look up its title, list it, start the player.
193async function playLink($: Engine, id: string) {
194 await update($, status, () => 'Opening the linked video…')
195 let video: Video = { id, title: `youtu.be/${id}`, channel: '', duration: '' }
196 try {
197 const { stdout } = await $.process.run(
198 ['yt-dlp', `https://www.youtube.com/watch?v=${id}`, '--no-warnings', '--skip-download',
199 '--print', '%(id)s\t%(title)s\t%(channel)s\t%(duration_string)s'],
200 { timeoutMs: 30_000 },
201 )
202 video = parseResults(stdout)[0] ?? video
203 } catch (err) {
204 $.ui.log(`youtube: title lookup failed: ${String(err)}`, { to: 'debug' })
205 }
206 await update($, results, () => [video])
207 await startPlayback($, video)
208}
209
210async function startPlayback($: Engine, v: Video) {
211 await stopPlayback($)
212 envCache ??= await readEnv($)
213 const tmp = ((await $.env.get('TMPDIR')) ?? '/tmp').replace(/\/+$/, '')
214 const m = pickMode(envCache, await read($, override))
215 const id = ++runCounter
216 const dir = `${tmp}/yt-pane-${Date.now().toString(36)}`
217 const r: Run = {
218 id, video: v, pageUrl: `https://www.youtube.com/watch?v=${v.id}`, mode: m, dir,
219 info: `${dir}/info.info.json`, leg: 0, offset: 0, paused: false,
220 framePath: `${dir}/frame.rgb`, children: [], errors: {}, decoderAt: Date.now(),
221 gotFrame: false, lastMtime: 0, generation: 0, denies: 0, busy: false,
222 }
223 run = r
224 const alive = () => run?.id === id
225 await update($, mode, () => m)
226 await update($, playing, () => v.title)
227 await update($, paused, () => false)
228 await update($, status, () => `Looking up "${v.title}"…`)
229 try {
230 await $.fs.write(`${dir}/.keep`, '')
231 } catch (err) {
232 return failInPane($, r, `no temp folder: ${String(err)}`)
233 }
234
235 // 1. Online, once: yt-dlp saves the video's details file. 2. Offline: formats and details from it.
236 const info = r.info
237 try {
238 const looked = await $.process.run(lookupArgv(r.pageUrl, `${dir}/info`), { timeoutMs: 45_000 })
239 if (!alive()) return
240 if (looked.exitCode !== 0) return failInPane($, r, lastLine(looked.stderr) || 'yt-dlp could not look the video up')
241 const details = await $.process.run(detailsArgv(info), { timeoutMs: 20_000 })
242 if (!alive()) return
243 const formats = details.exitCode === 0 ? parseFormats(details.stdout) : undefined
244 if (!formats) return failInPane($, r, lastLine(details.stderr) || 'no playable format')
245 r.meta = parseMeta(details.stdout)
246 r.size = decodeSize(r.meta ? r.meta.width / r.meta.height : 16 / 9)
247 r.formats = formats
248 await update($, status, () => `${m === 'pixels' ? 'pixels' : 'blocks'} · ${FPS} fps`)
249 await startLeg($, r, 0)
250 } catch (err) {
251 return failInPane($, r, String(err))
252 }
253 // Poll well above the frame rate: polling at the frame rate beats against ffmpeg's writes,
254 // showing a frame late and skipping the next every second or so. tick redraws only on a new frame.
255 r.ticker = $.clock.every(POLL_MS, () => void tick($, r))
256}
257
258// Ends the current leg: its children stop, and nothing they report afterwards counts.
259function endLeg(r: Run) {
260 r.leg++
261 // A silent child never wakes a read loop, so each handle is closed explicitly.
262 for (const h of r.children) void h.return({ code: null, signal: null }).catch(() => undefined)
263 r.children = []
264}
265
266// Starts playing `at` seconds in, through new named pipes:
267// yt-dlp → video / audio → ffmpeg → frames + PCM → ffplay.
268// ponytail: each leg downloads from the start and ffmpeg drops what comes before `at`, so a far
269// skip waits for that much download; fine at 480p, byte-range seeking if long videos feel slow.
270async function startLeg($: Engine, r: Run, at: number) {
271 const f = r.formats
272 if (!f || !r.size) return
273 endLeg(r)
274 const leg = r.leg
275 Object.assign(r, { offset: at, startedAt: undefined, paused: false, gotFrame: false, lastMtime: 0, errors: {} })
276 r.framePath = `${r.dir}/frame-${leg}.rgb`
277 const pipes = { video: `${r.dir}/video-${leg}.pipe`, audio: `${r.dir}/audio-${leg}.pipe`, pcm: `${r.dir}/pcm-${leg}.pipe` }
278 const made = await $.process.run(['mkfifo', pipes.video, pipes.pcm, ...(f.muxed ? [] : [pipes.audio])])
279 if (run?.id !== r.id || r.leg !== leg) return
280 if (made.exitCode !== 0) return failInPane($, r, lastLine(made.stderr) || 'could not make the pipes')
281 void child($, r, 'sound', soundArgv(pipes.pcm))
282 void child($, r, 'video download', downloadArgv(r.info, f.video, pipes.video))
283 if (!f.muxed) void child($, r, 'audio download', downloadArgv(r.info, f.audio, pipes.audio))
284 r.decoderAt = Date.now()
285 void watchDecoder($, r, leg, decoderArgv(pipes.video, f.muxed ? undefined : pipes.audio, r.size, r.framePath, pipes.pcm, at))
286}
287
288const position = (r: Run) =>
289 r.paused || r.startedAt === undefined ? r.offset : r.offset + (Date.now() - r.startedAt) / 1000
290
291const total = (r: Run) => (r.meta?.seconds !== undefined ? ` / ${clock(r.meta.seconds)}` : '')
292
293async function togglePause($: Engine) {
294 const r = run
295 if (!r?.formats) return
296 if (r.paused) {
297 await update($, paused, () => false)
298 await update($, status, () => `▶ ${clock(r.offset)}${total(r)}`)
299 return startLeg($, r, r.offset)
300 }
301 const at = position(r)
302 endLeg(r)
303 Object.assign(r, { paused: true, offset: at })
304 await update($, paused, () => true)
305 await update($, status, () => `Paused at ${clock(at)}${total(r)}`)
306}
307
308// Skips while paused only move the spot play resumes from.
309async function skip($: Engine, delta: number) {
310 const r = run
311 if (!r?.formats) return
312 const at = seekTarget(position(r), delta, r.meta?.seconds)
313 await update($, status, () => `${delta < 0 ? '◀◀' : '▶▶'} ${clock(at)}${total(r)}${r.paused ? ' · paused' : ''}`)
314 if (r.paused) r.offset = at
315 else await startLeg($, r, at)
316}
317
318// The decoder's end is the leg's end: finished, or failed with the most telling error line.
319async function watchDecoder($: Engine, r: Run, leg: number, argv: string[]) {
320 const code = await child($, r, 'decoder', argv)
321 if (run?.id !== r.id || r.leg !== leg) return // stopped, paused or skipped by us: not a failure
322 if (code === 0) return stopPlayback($, `Finished: ${r.video.title}`)
323 const why = r.errors['video download'] ?? r.errors['audio download'] ?? r.errors.decoder ?? `ffmpeg exited ${code}`
324 return failInPane($, r, why)
325}
326
327async function tick($: Engine, r: Run) {
328 if (run?.id !== r.id || r.busy || !r.size) return
329 r.busy = true
330 try {
331 const stat = await $.fs.stat(r.framePath).catch(() => undefined)
332 if (run?.id !== r.id) return
333 if (!stat) {
334 if (!r.paused && !r.gotFrame && Date.now() - r.decoderAt > FIRST_FRAME_MS) await failInPane($, r, 'no picture after 20 s')
335 return
336 }
337 r.startedAt ??= Date.now()
338 const box = shown
339 if (!box || box.mode !== r.mode || stat.mtimeMs === r.lastMtime) return
340 r.lastMtime = stat.mtimeMs
341 r.gotFrame = true
342 const { width, height } = r.size
343 let result
344 if (r.mode === 'pixels') {
345 // The terminal reads the file and scales it into the box itself.
346 result = await $.ui.blit({
347 requestId: PANE, key: 'video', columns: box.cols, rows: box.rows,
348 source: { file: r.framePath, format: 'rgb', width, height, generation: ++r.generation },
349 })
350 } else {
351 const { base64 } = await $.fs.read(r.framePath, { as: 'bytes' })
352 const rgb = Uint8Array.fromBase64(base64)
353 if (rgb.length !== width * height * 3) return
354 result = await $.ui.blit({
355 requestId: PANE, key: 'video', columns: box.cols, rows: box.rows,
356 cells: rgbToBlocks(rgb, width, height, box.cols, box.rows),
357 })
358 }
359 if (!result.deny) r.denies = 0
360 else if (r.mode === 'pixels' && ++r.denies >= DENY_LIMIT) {
361 // This terminal shows no images: blocks now, and start in blocks next time too.
362 await update($, override, () => 'auto')
363 await switchMode($, r, 'blocks', 'Blocks: this terminal can\'t show images (v switches view)')
364 }
365 } catch (err) {
366 $.ui.log(`youtube: frame draw failed: ${String(err)}`, { to: 'debug' })
367 } finally {
368 r.busy = false
369 }
370}
371
372// Switching view only changes how the same frames are drawn: nothing restarts.
373async function switchMode($: Engine, r: Run, m: PlayerMode, why?: string) {
374 if (run?.id !== r.id) return
375 r.mode = m
376 r.denies = 0
377 r.lastMtime = 0
378 await update($, mode, () => m)
379 if (why) await update($, status, () => why)
380}
381
382async function cycleMode($: Engine) {
383 const r = run
384 if (!r || !envCache) return
385 const next = nextOverride(await read($, override))
386 await update($, override, () => next)
387 await switchMode($, r, pickMode(envCache, next), `view: ${next}`)
388}
389
390async function stopPlayback($: Engine, message?: string) {
391 const r = run
392 run = undefined
393 shown = undefined
394 await update($, playing, () => '')
395 await update($, paused, () => false)
396 if (message) await update($, status, () => message)
397 if (!r) return
398 r.ticker?.cancel()
399 endLeg(r)
400 if (r.dir.includes('/yt-pane-')) void $.process.run(['rm', '-rf', r.dir]).catch(() => undefined)
401}
402
403// In-pane playback failed: stop, say why in the pane and the transcript, and leave mpv to the
404// person (the window button). Nothing opens on its own.
405async function failInPane($: Engine, r: Run, why: string) {
406 if (run?.id !== r.id) return
407 await stopPlayback($)
408 $.ui.log(`youtube: couldn't play "${r.video.title}" in the pane: ${why}`)
409 await update($, status, () => `Couldn't play here: ${why.slice(0, 160)} · [window] opens it in mpv`)
410}
411
412async function fallbackToMpv($: Engine, r: Run, why: string) {
413 if (run?.id !== r.id) return
414 await stopPlayback($)
415 await update($, status, () => `in-pane failed (${why.slice(0, 100)}); opening mpv`)
416 await playMpv($, r.video)
417}
418
419let isUpdating = false
420
421// "2026.08.19" (yt-dlp) and "2026.8.19" (Homebrew) are the same version.
422export function sameVersion(a: string, b: string): boolean {
423 const norm = (v: string) => v.trim().split('.').map(n => String(Number(n))).join('.')
424 return norm(a) === norm(b)
425}
426
427async function updateYtDlp($: Engine) {
428 if (isUpdating) return
429 isUpdating = true
430 try {
431 const version = async () => (await $.process.run(['yt-dlp', '--version'])).stdout.trim()
432 const before = await version()
433 const api = await $.process.run(['curl', '-fsS', 'https://formulae.brew.sh/api/formula/yt-dlp.json'])
434 const latest: string = JSON.parse(api.stdout).versions.stable
435 if (sameVersion(before, latest)) return
436 $.ui.toast(`Updating yt-dlp ${before} → ${latest}…`)
437 // Exit code is unreliable (brew can fail on an unrelated dependency); the version tells.
438 const { stderr } = await $.process.run(['brew', 'upgrade', 'yt-dlp'], { timeoutMs: 300_000 })
439 const after = await version()
440 $.ui.toast(after !== before ? `yt-dlp updated to ${after}`
441 : `yt-dlp update failed: ${stderr.trim().split('\n').pop()}`)
442 } catch (err) {
443 $.ui.log(`youtube: yt-dlp update check failed: ${String(err)}`, { to: 'debug' })
444 } finally {
445 isUpdating = false
446 }
447}
448
449export const register: Register = on => {
450 on('session.start', async ($, e, next) => {
451 await $.command.register({ name: 'youtube', description: 'Search YouTube and play a video' })
452 return next(e)
453 })
454
455 on('session.end', async ($, e, next) => {
456 await stopPlayback($).catch(() => undefined)
457 return next(e)
458 })
459
460 on('ui.close', { id: PANE }, async ($, e, next) => {
461 await stopPlayback($).catch(() => undefined)
462 return next(e)
463 })
464
465 on('command.run', { command: 'youtube' }, async ($, e) => {
466 await $.ui.open({ id: PANE, title: 'YouTube', focus: true })
467 void updateYtDlp($)
468 const id = videoIdFrom(e.args)
469 if (id) void playLink($, id)
470 else if (e.args.trim()) void search($, e.args)
471 return { text: 'YouTube pane opened.' }
472 })
473
474 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
475 const els = $.ui.resolve(e)
476 const { Box, Text, Button } = els
477 // The mobile app draws no Input yet, and only the terminal has Image and Raster.
478 const Input = 'Input' in els ? els.Input : null
479 const Image = 'Image' in els ? els.Image : null
480 const Raster = 'Raster' in els ? els.Raster : null
481 const canPlay = e.surface === 'terminal' && Image !== null && Raster !== null
482 const title = await read($, playing)
483
484 // After a hot reload the atom survives but the child does not: show the list.
485 if (title && run && canPlay) {
486 const m = await read($, mode)
487 const meta = run.meta
488 const room = cellBox(m, e.props.bodyColumns - FRAME_COLS, e.props.scroll.bodyRows - DETAIL_ROWS - FRAME_ROWS)
489 const box = fitBox(meta ? meta.width / meta.height : 16 / 9, room.cols, room.rows)
490 shown = { mode: m, ...box }
491 run.lastMtime = 0 // a redraw reset the picture: blit the current frame again
492 const Link = 'Link' in els ? els.Link : null
493 const facts = [
494 meta?.channel || run.video.channel,
495 meta?.views !== undefined ? `${compact(meta.views)} views` : '',
496 meta?.date ?? '',
497 meta?.duration || run.video.duration,
498 meta?.likes !== undefined ? `▲ ${compact(meta.likes)}` : '',
499 ].filter(Boolean)
500 const description = (meta?.description ?? '').trim().slice(0, MAX_DESCRIPTION)
501 const links = linksIn(description)
502 const width = Math.max(20, e.props.bodyColumns - 2)
503 // Hotkeys only while the search bar is empty, so typing "stop" never stops the video.
504 const keys = !(await read($, hasDraft))
505 const bar = await read($, submits)
506 const isPaused = await read($, paused)
507 const others = (await read($, results)).filter(v => v.id !== run!.video.id).slice(0, 8)
508 return (
509 <Box flexDirection="column">
510 <Box justifyContent="space-between">
511 <Text><Text color={C.accent} bold>▶ </Text><Text color={C.dim}>NOW PLAYING</Text></Text>
512 <Text color={C.faint}>{await read($, status)}</Text>
513 </Box>
514 <Box justifyContent="center"><Text color={C.accent} bold>YouTube Video Mod</Text></Box>
515 {Input && <Input key={`q-${bar}`} label="search " placeholder="search YouTube or paste a link" submitLabel="go"
516 onInput={(value: string) => void draftChanged($, value)}
517 onSubmit={(value: string) => void submitFromPlayer($, value)} />}
518 <Box borderStyle="round" borderColor={C.accent} alignSelf="center">
519 {m === 'pixels'
520 ? <Image key="video" source={BLACK_PIXEL} columns={box.cols} rows={box.rows} alt=" " />
521 : <Raster key="video" columns={box.cols} rows={box.rows} cells={blankCells(box.cols, box.rows)} />}
522 </Box>
523 <Text bold wrap="truncate-end">{title}</Text>
524 <Text color={C.dim} wrap="truncate-end">{facts.join(' · ')}</Text>
525 <Box gap={2}>
526 <Button key="back" plain label={`◀◀ ${SKIP_SECONDS}s`} {...(keys ? { hotkey: 'j' } : {})} onPress={() => void skip($, -SKIP_SECONDS)} />
527 <Button key="pause" plain label={isPaused ? 'play' : 'pause'} {...(keys ? { hotkey: 'k' } : {})} onPress={() => void togglePause($)} />
528 <Button key="forward" plain label={`${SKIP_SECONDS}s ▶▶`} {...(keys ? { hotkey: 'l' } : {})} onPress={() => void skip($, SKIP_SECONDS)} />
529 <Button key="stop" plain label="stop" {...(keys ? { hotkey: 's' } : {})} onPress={() => void stopPlayback($, 'Stopped.')} />
530 <Button key="window" plain label="window" {...(keys ? { hotkey: 'm' } : {})}
531 onPress={() => { const r = run; if (r) void fallbackToMpv($, r, 'window requested') }} />
532 <Button key="view" plain label="view" {...(keys ? { hotkey: 'v' } : {})} onPress={() => void cycleMode($)} />
533 <Text color={C.faint}>{keys ? 'tab to move · ↑↓ scroll' : 'keys off while typing'}</Text>
534 </Box>
535 {others.length > 0 && (
536 <Box flexDirection="column" marginTop={1}>
537 <Text color={C.dim} bold>RESULTS</Text>
538 {others.map((v, i) => (
539 <Box key={`next-${v.id}`} gap={1}>
540 <Box width={3} flexShrink={0}><Text color={C.faint}>{String(i + 1).padStart(2)}</Text></Box>
541 <Button key={`next-play-${v.id}`} plain label={v.title.length > width - 18 ? `${v.title.slice(0, width - 19)}…` : v.title}
542 onPress={() => void startPlayback($, v)} />
543 <Text color={C.dim}>{v.duration}</Text>
544 </Box>
545 ))}
546 </Box>
547 )}
548 {description && (
549 <Box flexDirection="column" borderStyle="round" borderColor={C.faint} paddingX={1} marginTop={1} width={width}>
550 <Text color={C.dim} bold>DESCRIPTION</Text>
551 <Text color={C.text}>{description}</Text>
552 </Box>
553 )}
554 {links.length > 0 && (
555 <Box flexDirection="column" marginTop={1}>
556 <Text color={C.dim} bold>LINKS</Text>
557 {links.map((url, i) => (
558 <Box key={`link-${i}`}>
559 <Text color={C.accent}>↗ </Text>
560 {Link ? <Link href={url} label={url} /> : <Text color={C.link}>{url}</Text>}
561 </Box>
562 ))}
563 </Box>
564 )}
565 </Box>
566 )
567 }
568
569 const list = await read($, results)
570 const cols = e.viewport?.columns ?? 80
571 const room = Math.max(1, (e.viewport?.rows ?? 24) - 5)
572 const titleW = Math.max(16, cols - (canPlay ? 34 : 24))
573 const pick = (v: Video) => void (canPlay ? startPlayback($, v) : playMpv($, v))
574
575 return (
576 <Box flexDirection="column">
577 <Box justifyContent="space-between">
578 <Text><Text color={C.accent} bold>▶ YouTube</Text></Text>
579 <Text color={C.faint}>{canPlay ? 'plays here · [window] opens mpv' : 'plays in the mpv window'}</Text>
580 </Box>
581 {Input && <Input key="q" label="search " placeholder="lofi beats, rust tutorial, or paste a link" submitLabel="search"
582 autoFocus onSubmit={(value: string) => void submitQuery($, value)} />}
583 <Text color={C.dim}>{await read($, status)}</Text>
584 {list.slice(0, room).map((v, i) => (
585 <Box key={`row-${v.id}`} gap={1}>
586 <Box width={3} flexShrink={0}><Text color={C.faint}>{String(i + 1).padStart(2)}</Text></Box>
587 <Box width={titleW} flexShrink={0}>
588 <Button key={`play-${v.id}`} plain label={v.title.length > titleW ? `${v.title.slice(0, titleW - 1)}…` : v.title}
589 onPress={() => pick(v)} />
590 </Box>
591 <Box width={8} flexShrink={0}><Text color={C.dim}>{v.duration.padStart(7)}</Text></Box>
592 <Text color={C.faint} wrap="truncate-end">{v.channel}</Text>
593 {canPlay && <Button key={`win-${v.id}`} plain label="[window]" onPress={() => void playMpv($, v)} />}
594 </Box>
595 ))}
596 </Box>
597 )
598 })
599}
600hooks/player.ts 281 lines1// Pure player logic: no engine calls, so it is testable on its own.
2// Approach credit: refact0r/claude-surf (MIT), see ../NOTICE.md.
3
4// The plugin runtime has these (ES2026 base64); older lib typings do not declare them.
5declare global {
6 interface Uint8Array { toBase64(): string }
7 interface Uint8ArrayConstructor { fromBase64(text: string): Uint8Array }
8}
9
10export type PlayerMode = 'pixels' | 'blocks'
11export type Override = PlayerMode | 'auto'
12export type FrameSize = { width: number; height: number }
13export type TermEnv = { termProgram?: string; term?: string; kittyWindow?: string }
14
15const PIXEL_TERM_PROGRAMS = ['ghostty', 'wezterm']
16const PIXEL_TERMS = ['xterm-kitty', 'xterm-ghostty']
17const MAX_PIXEL_W = 960
18const MAX_PIXEL_H = 4096
19const MAX_BLOCK_COLS = 120
20const MAX_BLOCK_ROWS = 40
21const MAX_PIXEL_CELLS = 255
22export const CHROME_ROWS = 3
23
24// Guess from env: image-capable terminals get pixels, everything else (and any
25// multiplexer, which swallows image escapes) gets quadrant-block cells.
26export function pickMode(env: TermEnv, override: Override = 'auto'): PlayerMode {
27 if (override !== 'auto') return override
28 const term = (env.term ?? '').toLowerCase()
29 const program = (env.termProgram ?? '').toLowerCase()
30 if (program === 'tmux' || term.startsWith('tmux') || term.startsWith('screen')) return 'blocks'
31 if (PIXEL_TERM_PROGRAMS.includes(program) || PIXEL_TERMS.includes(term) || env.kittyWindow) return 'pixels'
32 return 'blocks'
33}
34
35export function nextOverride(now: Override): Override {
36 return now === 'auto' ? 'pixels' : now === 'pixels' ? 'blocks' : 'auto'
37}
38
39// Cells the video box takes, from the pane body's size.
40export function cellBox(mode: PlayerMode, bodyColumns: number, bodyRows: number): { cols: number; rows: number } {
41 const rows = Math.max(2, Math.floor(bodyRows) - CHROME_ROWS)
42 const cols = Math.max(2, Math.floor(bodyColumns))
43 return mode === 'pixels'
44 ? { cols: Math.min(cols, MAX_PIXEL_CELLS), rows: Math.min(rows, MAX_PIXEL_CELLS) }
45 : { cols: Math.min(cols, MAX_BLOCK_COLS), rows: Math.min(rows, MAX_BLOCK_ROWS) }
46}
47
48const even = (n: number) => Math.max(2, Math.floor(n / 2) * 2)
49
50// ---- the pipeline: yt-dlp fetches (googlevideo refuses links ffmpeg opens itself), ffmpeg
51// decodes once at a fixed size, ffplay plays the sound. Named pipes join them.
52
53const FORMAT = 'bv*[height<=480]+ba/b[height<=480]/bv*+ba/b'
54export const FPS = 15
55
56// Online, once: save yt-dlp's details file (`${base}.info.json`) for the steps below.
57export function lookupArgv(pageUrl: string, base: string): string[] {
58 return ['yt-dlp', '--no-playlist', '--no-warnings', '--skip-download', '--write-info-json', '-o', base, pageUrl]
59}
60
61// Offline, from that file: the two format ids, then one JSON line of details.
62export function detailsArgv(infoPath: string): string[] {
63 return ['yt-dlp', '--no-warnings', '--load-info-json', infoPath, '-f', FORMAT,
64 '--print', '%(requested_formats.0.format_id,format_id)s',
65 '--print', '%(requested_formats.1.format_id,format_id)s',
66 '--print', '%(.{width,height,channel,view_count,like_count,upload_date,duration,duration_string,description})j']
67}
68
69export type Formats = { video: string; audio: string; muxed: boolean }
70
71// The first two non-JSON lines are the video and audio format ids ("NA" when one format has both).
72export function parseFormats(stdout: string): Formats | undefined {
73 const [video, audio] = stdout.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('{'))
74 if (!video || video === 'NA') return undefined
75 const muxed = !audio || audio === 'NA' || audio === video
76 return { video, audio: muxed ? video : audio, muxed }
77}
78
79// yt-dlp's own downloader into a named pipe. `exec` makes the shell become yt-dlp, so killing the
80// spawned process kills the download, with nothing left behind.
81export function downloadArgv(infoPath: string, formatId: string, pipe: string): string[] {
82 return ['/bin/sh', '-c', 'exec yt-dlp -q --no-warnings --no-part --load-info-json "$0" -f "$1" -o - > "$2"',
83 infoPath, formatId, pipe]
84}
85
86// One decode size per video, in its own shape: about 270 px tall, at most 480 wide.
87export function decodeSize(aspect: number): FrameSize {
88 const a = aspect > 0 && Number.isFinite(aspect) ? aspect : 16 / 9
89 const width = Math.min(480, even(270 * a))
90 return { width, height: even(width / a) }
91}
92
93// ffmpeg paces both inputs in real time (-re): frames go to one overwritten raw rgb24 file,
94// sound goes as raw PCM into the pipe ffplay reads. One process, one clock.
95// startAt > 0 starts there: ffmpeg reads and drops what comes before at full speed, unpaced.
96export function decoderArgv(videoPipe: string, audioPipe: string | undefined, size: FrameSize, framePath: string, pcmPipe: string, startAt = 0): string[] {
97 const ss = startAt > 0 ? ['-ss', startAt.toFixed(1)] : []
98 return ['ffmpeg', '-v', 'error', '-nostdin',
99 ...ss, '-re', '-i', videoPipe, ...(audioPipe ? [...ss, '-re', '-i', audioPipe] : []),
100 '-map', '0:v:0', '-vf', `fps=${FPS},scale=${size.width}:${size.height}:flags=area`,
101 '-pix_fmt', 'rgb24', '-c:v', 'rawvideo', '-f', 'image2', '-update', '1', '-atomic_writing', '1', framePath,
102 '-map', audioPipe ? '1:a:0' : '0:a:0', '-ar', '48000', '-ac', '2', '-f', 's16le', '-y', pcmPipe]
103}
104
105// ffplay plays the PCM with as little buffering as it allows; it ends when ffmpeg closes the pipe.
106// (AudioToolbox straight from ffmpeg started 10-15 s late; ffplay starts at once.)
107export function soundArgv(pcmPipe: string): string[] {
108 return ['ffplay', '-nodisp', '-autoexit', '-nostats', '-loglevel', 'error',
109 '-fflags', 'nobuffer', '-flags', 'low_delay', '-probesize', '32', '-analyzeduration', '0',
110 '-f', 's16le', '-ar', '48000', '-ch_layout', 'stereo', pcmPipe]
111}
112
113export type Meta = {
114 width: number; height: number; channel: string; views?: number; likes?: number
115 date: string; duration: string; description: string
116 /** Length in seconds; undefined for live streams. */
117 seconds?: number
118}
119
120// The JSON line yt-dlp prints after the stream URLs. Missing or broken → undefined.
121export function parseMeta(stdout: string): Meta | undefined {
122 const line = stdout.split('\n').map(l => l.trim()).filter(l => l.startsWith('{') && !l.includes('"User-Agent"')).pop()
123 if (!line) return undefined
124 try {
125 const j = JSON.parse(line) as Record<string, unknown>
126 const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
127 const str = (v: unknown) => (typeof v === 'string' ? v : '')
128 const d = str(j.upload_date)
129 return {
130 width: num(j.width) ?? 16, height: num(j.height) ?? 9, channel: str(j.channel),
131 views: num(j.view_count), likes: num(j.like_count),
132 date: /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}` : '',
133 duration: str(j.duration_string), description: str(j.description), seconds: num(j.duration),
134 }
135 } catch {
136 return undefined
137 }
138}
139
140// Cells a video of this shape fills inside the space given, with no bars: a cell is about
141// twice as tall as wide (8x16 px), so the box's real shape is (cols*8):(rows*16).
142// ponytail: assumes an 8x16 cell; a terminal with a different cell shape stretches slightly.
143export function fitBox(aspect: number, cols: number, rows: number): { cols: number; rows: number } {
144 const a = aspect > 0 && Number.isFinite(aspect) ? aspect : 16 / 9
145 const byWidth = { cols, rows: Math.round((cols * 8) / a / 16) }
146 const box = byWidth.rows <= rows ? byWidth : { cols: Math.round((rows * 16 * a) / 8), rows }
147 return { cols: Math.max(2, box.cols), rows: Math.max(1, box.rows) }
148}
149
150// Every distinct http(s) link in a description, in order, trailing punctuation trimmed.
151export function linksIn(text: string, max = 20): string[] {
152 const found = (text.match(/https?:\/\/[^\s<>"')\]]+/g) ?? []).map(u => u.replace(/[.,;:!?]+$/, ''))
153 return [...new Set(found)].slice(0, max)
154}
155
156// Where a skip of `delta` seconds lands: never before the start, and short of the end
157// (a seek past the end would just finish the video).
158export function seekTarget(at: number, delta: number, seconds?: number): number {
159 const end = seconds !== undefined ? Math.max(0, seconds - 2) : Infinity
160 return Math.max(0, Math.min(at + delta, end))
161}
162
163// 75 → "1:15", 3725 → "1:02:05"
164export function clock(at: number): string {
165 const t = Math.max(0, Math.floor(at))
166 const [h, m, s] = [Math.floor(t / 3600), Math.floor(t / 60) % 60, t % 60]
167 const two = (n: number) => String(n).padStart(2, '0')
168 return h ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`
169}
170
171// 1234 → "1.2K", 3400000 → "3.4M"
172export function compact(n: number): string {
173 for (const [div, unit] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']] as const) {
174 if (n >= div) return `${(n / div).toFixed(n >= div * 10 ? 0 : 1).replace(/\.0$/, '')}${unit}`
175 }
176 return String(n)
177}
178
179// Quadrant blocks: each cell shows 2x2 pixels in two colors. Index = which of the four
180// pixels take the foreground (bit 1 top-left, 2 top-right, 4 bottom-left, 8 bottom-right).
181const QUADRANTS = [
182 0x0020, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b,
183 0x2597, 0x259a, 0x2590, 0x259c, 0x2584, 0x2599, 0x259f, 0x2588,
184]
185
186// rgb is (cols*2) x (rows*2) pixels, 3 bytes each. For every cell, try each way of splitting its
187// four pixels into two groups, color each group by its mean, and keep the split with the least error.
188// ponytail: 8 splits x 4 pixels per cell; at 120x40 cells and 15 fps that is ~2.3M small steps a second.
189const SPLITS = [15, 8, 9, 10, 11, 12, 13, 14]
190
191export function quadrantWords(rgb: Uint8Array, cols: number, rows: number): Uint32Array {
192 const words = new Uint32Array(cols * rows * 3)
193 const w = cols * 2
194 const px = new Int32Array(12)
195 for (let y = 0; y < rows; y++) {
196 for (let x = 0; x < cols; x++) {
197 const tl = ((y * 2) * w + x * 2) * 3
198 const bl = tl + w * 3
199 for (const [k, at] of [[0, tl], [3, tl + 3], [6, bl], [9, bl + 3]] as const) {
200 px[k] = rgb[at] ?? 0; px[k + 1] = rgb[at + 1] ?? 0; px[k + 2] = rgb[at + 2] ?? 0
201 }
202 let best = 15, bestErr = Infinity, fg = 0, bg = 0
203 // Masks 8..15 cover every split once (a split and its complement look the same);
204 // 15 (one color) goes first so a flat cell stays a plain full block on ties.
205 for (const mask of SPLITS) {
206 const f = [0, 0, 0], b = [0, 0, 0]
207 let nf = 0, nb = 0
208 for (let i = 0; i < 4; i++) {
209 const into = mask & (1 << i) ? f : b
210 into[0] += px[i * 3]!; into[1] += px[i * 3 + 1]!; into[2] += px[i * 3 + 2]!
211 if (mask & (1 << i)) nf++; else nb++
212 }
213 const fm = f.map(c => c / nf)
214 const bm = nb ? b.map(c => c / nb) : fm
215 let err = 0
216 for (let i = 0; i < 4; i++) {
217 const m = mask & (1 << i) ? fm : bm
218 for (let c = 0; c < 3; c++) { const d = px[i * 3 + c]! - m[c]!; err += d * d }
219 }
220 if (err < bestErr) {
221 bestErr = err; best = mask
222 fg = (Math.round(fm[0]!) << 16) | (Math.round(fm[1]!) << 8) | Math.round(fm[2]!)
223 bg = (Math.round(bm[0]!) << 16) | (Math.round(bm[1]!) << 8) | Math.round(bm[2]!)
224 }
225 }
226 const o = (y * cols + x) * 3
227 words[o] = QUADRANTS[best]!
228 words[o + 1] = fg
229 words[o + 2] = bg
230 }
231 }
232 return words
233}
234
235// Averages a w x h rgb frame down (or up) to outW x outH: each output pixel is the mean of the
236// source pixels under it, so small text and edges keep what detail the cells can hold.
237export function resample(rgb: Uint8Array, w: number, h: number, outW: number, outH: number): Uint8Array {
238 if (w === outW && h === outH) return rgb
239 const out = new Uint8Array(outW * outH * 3)
240 for (let y = 0; y < outH; y++) {
241 const y0 = Math.floor((y * h) / outH), y1 = Math.max(y0 + 1, Math.floor(((y + 1) * h) / outH))
242 for (let x = 0; x < outW; x++) {
243 const x0 = Math.floor((x * w) / outW), x1 = Math.max(x0 + 1, Math.floor(((x + 1) * w) / outW))
244 let r = 0, g = 0, b = 0, n = 0
245 for (let sy = y0; sy < y1; sy++) {
246 for (let sx = x0; sx < x1; sx++) {
247 const i = (sy * w + sx) * 3
248 r += rgb[i] ?? 0; g += rgb[i + 1] ?? 0; b += rgb[i + 2] ?? 0; n++
249 }
250 }
251 const o = (y * outW + x) * 3
252 out[o] = r / n; out[o + 1] = g / n; out[o + 2] = b / n
253 }
254 }
255 return out
256}
257
258// A w x h frame drawn into cols x rows quadrant cells.
259export function rgbToBlocks(rgb: Uint8Array, w: number, h: number, cols: number, rows: number): string {
260 return new Uint8Array(quadrantWords(resample(rgb, w, h, cols * 2, rows * 2), cols, rows).buffer).toBase64()
261}
262
263// A black frame for a Raster before the first blit.
264export function blankCells(cols: number, rows: number): string {
265 return rgbToBlocks(new Uint8Array(cols * rows * 12), cols * 2, rows * 2, cols, rows)
266}
267
268// The video id in a YouTube link: youtu.be/ID, watch?v=ID, /shorts/ID, /embed/ID, /live/ID.
269// Plain text (a search) gives undefined; a bare 11-character word is a search, not an id.
270export function videoIdFrom(text: string): string | undefined {
271 let url: URL
272 try { url = new URL(text.trim()) } catch { return undefined }
273 const host = url.hostname.replace(/^(www|m|music)\./, '')
274 const id = host === 'youtu.be'
275 ? url.pathname.split('/')[1]
276 : host === 'youtube.com' || host === 'youtube-nocookie.com'
277 ? url.searchParams.get('v') ?? url.pathname.match(/^\/(?:shorts|embed|live|v)\/([^/?#]+)/)?.[1]
278 : undefined
279 return id && /^[\w-]{11}$/.test(id) ? id : undefined
280}
281types/index.d.ts 23 lines1export type Video = { id: string; title: string; channel: string; duration: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 youtube: {
6 results: Video[]
7 status: string
8 /** Title of the video playing in the pane, '' when the list shows. */
9 playing: string
10 /** The mode the player draws in. */
11 mode: 'pixels' | 'blocks'
12 /** User choice for the mode: auto picks from the terminal. */
13 override: 'auto' | 'pixels' | 'blocks'
14 /** True while playback is paused. */
15 paused: boolean
16 /** True while the player's search bar holds text: the j/k/l/s/m/v hotkeys are off then. */
17 hasDraft: boolean
18 /** Bumped on each player search submit, so the bar redraws empty. */
19 submits: number
20 }
21 }
22}
23