~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0

Videos play Bluesky's HLS, and the blob proxy serves them as they arrive

Merged chadtmiller.com asked to merge into main from chadtmiller.com/hud:video/hls-and-streaming
crates/hud-core/src/ui/embed.rs+45−4
@@ -104,6 +104,14 @@ fn external(v: &Value, ctx: &Ctx) -> Option<Value> {
fn video(v: &Value, did: Option<&str>, uri: Option<&str>, ctx: &Ctx) -> Option<Value> {
let src = page_url(&v["url"]).or_else(|| page_url(&v["video"]["url"]));
// Bluesky's own HLS, adaptive and from its CDN, where its playlist is
// on Bluesky's video service: played before the stream from the server.
let hls = str_at(v, "playlist").filter(|p| {
url::Url::parse(p).is_ok_and(|u| {
u.origin().ascii_serialization() == crate::blobs::VIDEO_ORIGINS[0]
&& u.path().starts_with("/watch/")
})
});
let poster = url_of(&v["thumbnail"], ctx);
let ratio = ratio_of(&v["aspectRatio"]).unwrap_or(16.0 / 9.0);
let author = did.map(str::to_string).or_else(|| {
@@ -120,9 +128,10 @@ fn video(v: &Value, did: Option<&str>, uri: Option<&str>, ctx: &Ctx) -> Option<V
None => format!("https://bsky.app/profile/{a}"),
}
});
let playable = src.is_some() || hls.is_some();
Some(json!({
"kind": "video", "src": src, "poster": poster, "ratio": ratio,
"alt": str_at(v, "alt").unwrap_or("Video"), "watch": if src.is_none() { watch } else { None },
"kind": "video", "src": src, "hls": hls, "poster": poster, "ratio": ratio,
"alt": str_at(v, "alt").unwrap_or("Video"), "watch": if playable { None } else { watch },
}))
}
@@ -535,10 +544,12 @@ mod tests {
let root = json!({});
let c = ctx(&root, &[]);
let video = json!({ "$type": "app.bsky.embed.video#view",
"playlist": "https://video.bsky.app/watch/did%3Aplc%3Av/bafy/playlist.m3u8" });
// Its author from its playlist, with no post to link to.
"playlist": "http://video.bsky.app/watch/did%3Aplc%3Av/bafy/playlist.m3u8" });
// Its author from its playlist, with no post to link to; a playlist
// over http is never played.
let v = shown(video.clone(), json!({}), &c).unwrap();
assert_eq!(v["watch"], "https://bsky.app/profile/did%3Aplc%3Av");
assert_eq!(v["hls"], Value::Null);
assert_eq!(v["alt"], "Video");
assert_eq!(v["ratio"], 16.0 / 9.0);
// The post it is in, by its uri.
@@ -559,4 +570,34 @@ mod tests {
.unwrap();
assert_eq!(v["watch"], Value::Null);
}
#[test]
fn a_video_plays_bluesky_s_hls_and_needs_no_link_then() {
let root = json!({});
let c = ctx(&root, &[]);
let playlist = "https://video.bsky.app/watch/did%3Aplc%3Av/bafy/playlist.m3u8";
let v = shown(
json!({ "$type": "app.bsky.embed.video#view", "playlist": playlist }),
json!({}),
&c,
)
.unwrap();
assert_eq!(v["hls"], playlist);
assert_eq!(v["src"], Value::Null);
assert_eq!(v["watch"], Value::Null);
// Anywhere else, or not under /watch/: none.
for other in [
"https://video.example/watch/x/playlist.m3u8",
"https://video.bsky.app/other/playlist.m3u8",
"not a url",
] {
let v = shown(
json!({ "$type": "app.bsky.embed.video#view", "playlist": other }),
json!({}),
&c,
)
.unwrap();
assert_eq!(v["hls"], Value::Null, "{other}");
}
}
}
crates/hud-core/src/blobcache.rs+399−120
519 lines changed: not loaded until asked for.
crates/hud-core/src/blobs.rs+5−0
@@ -164,6 +164,11 @@ pub fn servable(o: &Map<String, Value>) -> Option<(&str, &str)> {
/// The image CDN where `HUD_IMAGE_CDN` names none: Bluesky's.
pub const IMAGE_CDN: &str = "https://cdn.bsky.app/img";
/// Bluesky's video service, whose playlists a public post's video names,
/// and the CDN its segments are served from: where the view plays a video's
/// HLS from.
pub const VIDEO_ORIGINS: [&str; 2] = ["https://video.bsky.app", "https://video.cdn.bsky.app"];
/// The image CDN's URL for a blob of `did`'s repository at one of its sizes
/// (`feed_fullsize`, `feed_thumbnail`, `avatar_thumbnail`), as a JPEG.
pub fn cdn_url(cdn: &str, preset: &str, did: &str, cid: &str) -> String {
crates/hud-server/src/blob.rs+180−57
@@ -10,12 +10,15 @@
//! and it has ten seconds to answer. A blob never changes, so it is cached
//! for good.
//!
//! Images stream straight through. Audio and video are kept on disk first
//! (hud-core's `blobcache`, which keeps only bytes that hash to the CID),
//! because a player seeks with `Range` and PDSes answer only whole blobs:
//! from the cache, a single range is answered `206`, an unsatisfiable one
//! `416`, and a plain request `200`. A blob already kept is served without
//! asking its PDS again: its bytes are what its CID names, whoever asks.
//! Audio and video are kept on disk (hud-core's `blobcache`, which keeps
//! only bytes that hash to the CID), because a player seeks with `Range`
//! and PDSes answer only whole blobs. Each is downloaded once however many
//! ask for it, and served as it arrives, so a player starts on its first
//! bytes: a single range is answered `206`, an unsatisfiable one `416`, and
//! a plain request `200`, against the length its PDS said (one that said
//! none is served once it is all here). A blob already kept is served
//! without asking its PDS again: its bytes are what its CID names, whoever
//! asks.
use axum::body::Body;
use axum::extract::{Path, State};
@@ -23,7 +26,7 @@ use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use futures::{StreamExt, TryStreamExt};
use hud_core::Hud;
use hud_core::blobcache::{Cached, PutError};
use hud_core::blobcache::{Cached, Filling, PutError, READ_CHUNK};
use hud_core::blobs::{IMAGE_MAX, SNIFF_LEN, is_kept, max_size, sniff};
use std::sync::Arc;
use std::time::Duration;
@@ -124,13 +127,17 @@ fn parse_range(value: &str, len: u64) -> Range {
}
}
/// A kept blob, as a request's `Range` asks for it.
async fn serve_cached(c: Cached, range: Option<&HeaderValue>) -> Response {
let Cached {
mut file,
len,
mime,
} = c;
/// A blob of `len` bytes, as a request's `Range` asks for it: `count` of
/// its bytes from `start`, as `read` gives them.
fn ranged<S>(
len: u64,
mime: &str,
range: Option<&HeaderValue>,
read: impl FnOnce(u64, u64) -> S,
) -> Response
where
S: futures::Stream<Item = std::io::Result<bytes::Bytes>> + Send + 'static,
{
let range = range
.and_then(|r| r.to_str().ok())
.map_or(Range::Whole, |r| parse_range(r, len));
@@ -145,17 +152,10 @@ async fn serve_cached(c: Cached, range: Option<&HeaderValue>) -> Response {
return r;
}
};
// Read from `start`: a kept blob is a file, so seeking it fails only as
// reading it would, which ends the body.
let body = futures::stream::once(async move {
file.seek(std::io::SeekFrom::Start(start)).await?;
Ok::<_, std::io::Error>(ReaderStream::new(file.take(count)))
})
.try_flatten();
let mut r = Response::new(Body::from_stream(body));
let mut r = Response::new(Body::from_stream(read(start, count)));
*r.status_mut() = status;
let h = r.headers_mut();
blob_headers(h, &mime);
blob_headers(h, mime);
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
h.insert(header::CONTENT_LENGTH, HeaderValue::from(count));
if status == StatusCode::PARTIAL_CONTENT
@@ -166,6 +166,53 @@ async fn serve_cached(c: Cached, range: Option<&HeaderValue>) -> Response {
r
}
/// A kept blob, as a request's `Range` asks for it.
fn serve_cached(c: Cached, range: Option<&HeaderValue>) -> Response {
let Cached {
mut file,
len,
mime,
} = c;
// Read from `start`: a kept blob is a file, so seeking it fails only as
// reading it would, which ends the body.
ranged(len, &mime, range, |start, count| {
futures::stream::once(async move {
file.seek(std::io::SeekFrom::Start(start)).await?;
Ok::<_, std::io::Error>(ReaderStream::with_capacity(file.take(count), READ_CHUNK))
})
.try_flatten()
})
}
/// A blob being downloaded, as a request's `Range` asks for it, each byte
/// as it arrives: against the length its PDS said, or where it said none,
/// once it is all here.
async fn serve_filling(f: Arc<Filling>, range: Option<&HeaderValue>) -> Response {
let len = match f.said {
Some(len) => len,
None => match f.kept().await {
Ok(len) => len,
Err(e) => return unkept(&e),
},
};
ranged(len, &f.mime, range, |start, count| f.read(start, count))
}
/// Why a blob was not kept, answered before any of it was sent.
fn unkept(e: &PutError) -> Response {
match e {
PutError::TooLarge => refuse(StatusCode::PAYLOAD_TOO_LARGE, "The blob is too large"),
PutError::Disk(e) => {
tracing::warn!(error = %e, "could not keep a blob");
refuse(
StatusCode::INTERNAL_SERVER_ERROR,
"The blob could not be kept",
)
}
e => refuse(StatusCode::BAD_GATEWAY, &e.to_string()),
}
}
pub async fn blob(
State(hud): State<Arc<Hud>>,
Path((did, cid_text)): Path<(String, String)>,
@@ -179,7 +226,10 @@ pub async fn blob(
};
let range = headers.get(header::RANGE);
if let Some(kept) = hud.blob_cache.get(&cid).await {
return serve_cached(kept, range).await;
return serve_cached(kept, range);
}
if let Some(filling) = hud.blob_cache.filling(&did, &cid) {
return serve_filling(filling, range).await;
}
let pds = match hud.pds(&did).await {
Ok(pds) => pds,
@@ -252,19 +302,13 @@ pub async fn blob(
return refuse(StatusCode::PAYLOAD_TOO_LARGE, "The blob is too large");
}
if is_kept(&content_type) {
return match hud.blob_cache.put(&cid, &content_type, stream, max).await {
Ok(kept) => serve_cached(kept, range).await,
Err(PutError::TooLarge) => {
refuse(StatusCode::PAYLOAD_TOO_LARGE, "The blob is too large")
}
Err(PutError::Disk(e)) => {
tracing::warn!(error = %e, "could not keep a blob");
refuse(
StatusCode::INTERNAL_SERVER_ERROR,
"The blob could not be kept",
)
}
Err(e) => refuse(StatusCode::BAD_GATEWAY, &format!("{pds}: {e}")),
return match hud
.blob_cache
.fill(&did, &cid, &content_type, length, stream, max)
.await
{
Ok(filling) => serve_filling(filling, range).await,
Err(e) => unkept(&PutError::Disk(e)),
};
}
// An image streams on, cut off past the cap whatever the PDS said its
@@ -305,14 +349,19 @@ mod tests {
Status(u16),
/// No answer, ever.
Never,
/// Its type and its bytes, its length said: the first half sent at
/// once, the rest once the gate opens.
Gated(&'static str, bytes::Bytes, Arc<tokio::sync::Notify>),
}
/// What the fake PDSes hold, by CID: `held` at did:plc:alice's; at
/// did:plc:short's, each blob's type and the bytes it sends of it, a
/// thousand fewer than it says, before it hangs up.
/// What the fake PDSes hold, by CID: `held` at did:plc:alice's, and how
/// often it was asked for a blob; at did:plc:short's, each blob's type
/// and the bytes it sends of it, a thousand fewer than it says, before
/// it hangs up.
#[derive(Default)]
struct Shelves {
held: HashMap<String, Held>,
asked: usize,
short: HashMap<String, (&'static str, bytes::Bytes)>,
}
@@ -341,7 +390,11 @@ mod tests {
}
};
let get_blob = move |Query(q): Query<HashMap<String, String>>| {
let found = fake.lock().unwrap().held.get(&q["cid"]).cloned();
let found = {
let mut shelves = fake.lock().unwrap();
shelves.asked += 1;
shelves.held.get(&q["cid"]).cloned()
};
async move {
let typed = |t: &'static str| {
let mut h = HeaderMap::new();
@@ -358,6 +411,18 @@ mod tests {
}
Some(Held::Status(s)) => StatusCode::from_u16(s).unwrap().into_response(),
Some(Held::Never) => std::future::pending::<Response>().await,
Some(Held::Gated(t, b, gate)) => {
let mut h = typed(t);
h.insert(header::CONTENT_LENGTH, HeaderValue::from(b.len()));
let (first, rest) = (b.slice(..b.len() / 2), b.slice(b.len() / 2..));
let body = futures::stream::iter([Ok::<_, String>(first)]).chain(
futures::stream::once(async move {
gate.notified().await;
Ok(rest)
}),
);
(h, Body::from_stream(body)).into_response()
}
None => StatusCode::NOT_FOUND.into_response(),
}
}
@@ -619,17 +684,21 @@ mod tests {
async fn audio_kept_then_served_from_the_cache() {
let (hud, held) = proxy().await;
let wav = [b"RIFF\x10\0\0\0WAVEfmt ".as_slice(), &[3; 200]].concat();
let (song, wrong, long) = (cid(&wav), cid(b"wrong"), cid(b"long"));
let (song, wrong, unsaid, long) = (cid(&wav), cid(b"wrong"), cid(b"unsaid"), cid(b"long"));
let mib = bytes::Bytes::from(vec![0u8; 1 << 20]);
let mibs = usize::try_from(AUDIO_MAX >> 20).unwrap() + 1;
held.lock().unwrap().held.extend([
(song.clone(), Held::Whole("", wav.clone().into())),
// Bytes that are not what the CID names.
(song.clone(), Held::Chunks("", vec![wav.clone().into()])),
// Bytes that are not what the CID names, their length said and unsaid.
(wrong.clone(), Held::Whole("audio/wav", wav.clone().into())),
(
unsaid.clone(),
Held::Chunks("audio/wav", vec![wav.clone().into()]),
),
(long.clone(), Held::Chunks("audio/mpeg", vec![mib; mibs])),
]);
let at = |c: &str| format!("/blob/did:plc:alice/{c}");
// Kept, then the range asked of it.
// Its length unsaid: kept whole, then the range asked of it.
let (status, h, body) = fetch(&hud, &at(&song), Some("bytes=4-11")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(h[header::CONTENT_TYPE], "audio/wav");
@@ -644,13 +713,21 @@ mod tests {
assert_eq!(status, StatusCode::OK);
assert_eq!(h[header::ACCEPT_RANGES], "bytes");
assert_eq!(body.unwrap(), wav);
// Never kept: bytes not its CID's, and more than an audio blob's cap.
let (status, why) = refused(&hud, &at(&wrong)).await;
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert!(
why.ends_with("the blob's bytes do not match its CID\n"),
"{why}"
// Never kept: bytes not its CID's. Their length said, they are
// sent as they come, and the body ends in an error short of the
// last; unsaid, nothing is sent.
let (status, _, body) = fetch(&hud, &at(&wrong), None).await;
assert_eq!(status, StatusCode::OK);
assert!(body.is_err());
let (status, why) = refused(&hud, &at(&unsaid)).await;
assert_eq!(
(status, why.as_str()),
(
StatusCode::BAD_GATEWAY,
"the blob's bytes do not match its CID\n"
)
);
// More than an audio blob's cap.
assert_eq!(
refused(&hud, &at(&long)).await,
(
@@ -660,6 +737,33 @@ mod tests {
);
}
#[tokio::test]
async fn video_served_as_it_arrives_and_downloaded_once() {
let (hud, held) = proxy().await;
let mp4: Vec<u8> = (0..=255u8).cycle().take(400).collect();
let gate = Arc::new(tokio::sync::Notify::new());
let movie = cid(&mp4);
held.lock().unwrap().held.insert(
movie.clone(),
Held::Gated("video/mp4", mp4.clone().into(), gate.clone()),
);
let at = format!("/blob/did:plc:alice/{movie}");
// Its first bytes, and more of them asked again, before the rest has come.
let (status, h, body) = fetch(&hud, &at, Some("bytes=0-1")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(h[header::CONTENT_RANGE], "bytes 0-1/400");
assert_eq!(body.unwrap(), mp4[..2]);
let (status, _, body) = fetch(&hud, &at, Some("bytes=100-149")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(body.unwrap(), mp4[100..150]);
// The rest come: all of it, from the one download.
gate.notify_one();
let (status, _, body) = fetch(&hud, &at, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body.unwrap(), mp4);
assert_eq!(held.lock().unwrap().asked, 1);
}
#[tokio::test]
async fn audio_the_disk_cannot_keep() {
let (hud, held) = proxy().await;
@@ -671,12 +775,26 @@ mod tests {
// Where its blobs would go, a file.
std::fs::create_dir_all(&hud.config.cache_dir).unwrap();
std::fs::write(hud.config.cache_dir.join("blobs"), "").unwrap();
let could_not = (
StatusCode::INTERNAL_SERVER_ERROR,
"The blob could not be kept\n".to_string(),
);
assert_eq!(
refused(&hud, &format!("/blob/did:plc:alice/{}", cid(&wav))).await,
(
StatusCode::INTERNAL_SERVER_ERROR,
"The blob could not be kept\n".into()
)
could_not
);
// Downloaded, its length unsaid, but its type cannot be kept.
let (hud, held) = proxy().await;
held.lock().unwrap().held.insert(
cid(&wav),
Held::Chunks("audio/wav", vec![wav.clone().into()]),
);
let blobs = hud.config.cache_dir.join("blobs");
std::fs::create_dir_all(blobs.join(format!("{}.type", cid(&wav))).join("in-the-way"))
.unwrap();
assert_eq!(
refused(&hud, &format!("/blob/did:plc:alice/{}", cid(&wav))).await,
could_not
);
}
@@ -750,9 +868,14 @@ mod tests {
let bytes: Vec<u8> = (0..=255u8).collect();
let cid = atproto::Cid::of_raw(&bytes);
let body = futures::stream::iter([Ok::<_, String>(bytes)]);
let kept = cache.put(&cid, "audio/wav", body, 1 << 20).await.unwrap();
let filling = cache
.fill("did:plc:alice", &cid, "audio/wav", None, body, 1 << 20)
.await
.unwrap();
filling.kept().await.unwrap();
let kept = cache.get(&cid).await.unwrap();
let header = range.map(|r| HeaderValue::from_str(r).unwrap());
let r = serve_cached(kept, header.as_ref()).await;
let r = serve_cached(kept, header.as_ref());
let (status, headers) = (r.status(), r.headers().clone());
let body = axum::body::to_bytes(r.into_body(), usize::MAX)
.await
crates/hud-server/src/mcp.rs+10−2
@@ -645,8 +645,9 @@ fn server_meta() -> Json {
/// The view's UI metadata: it calls only the server's own origin, and loads
/// media from there (the blob proxy), from the origins the bundled views
/// trust, and from the image CDN public records' images come from: for
/// every view, a model's too, as it serves nothing but images.
/// trust (Bluesky's video service and CDN among them, for posts' videos'
/// HLS), and from the image CDN public records' images come from: for
/// every view, a model's too, as they serve nothing but media.
fn view_meta(hud: &Hud) -> Json {
let origin = &hud.config.public_origin;
let mut resources = hud_core::view::csp_origins(origin);
@@ -1099,10 +1100,17 @@ mod tests {
bundled.push("https://images.example".into());
assert_eq!(csp["resourceDomains"], json!(bundled));
assert!(domains.contains(&json!("https://hud.example")));
for v in hud_core::blobs::VIDEO_ORIGINS {
assert!(domains.contains(&json!(v)), "{v}");
}
assert!(domains.contains(&json!("https://audio.plyr.fm")));
// The image CDN (HUD_IMAGE_CDN's origin), once.
let cdn = json!("https://images.example");
assert_eq!(domains.iter().filter(|d| **d == cdn).count(), 1);
// Bluesky's video service and CDN, once each.
for v in hud_core::blobs::VIDEO_ORIGINS {
assert_eq!(domains.iter().filter(|d| **d == v).count(), 1, "{v}");
}
let (_, body) = modern_call("resources/list", None, json!({})).await;
assert_eq!(body["result"]["resources"][0]["uri"], VIEW_URI);
}
crates/hud-server/src/workspace.rs+8−3
@@ -63,9 +63,10 @@ pub fn routes() -> Router<Arc<Hud>> {
}
/// The page's Content-Security-Policy: its own inline script and styles;
/// the server alone to talk to; images and audio from the server and the
/// origins the bundled views trust, and images from Bluesky's CDN, for the
/// AppView's avatars, and the image CDN (`image_cdn`, an origin), for
/// the server alone to talk to; images, audio and video from the server and
/// the origins the bundled views trust (Bluesky's video service and CDN
/// among them, for posts' videos' HLS), and images from Bluesky's CDN, for
/// the AppView's avatars, and the image CDN (`image_cdn`, an origin), for
/// public records' images.
fn csp(public_origin: &str, image_cdn: Option<&str>) -> String {
let trusted: Vec<String> = hud_core::view::csp_origins(public_origin)
@@ -688,6 +689,10 @@ mod tests {
.find(|d| d.starts_with("media-src"))
.unwrap();
assert!(!media.contains("images.example"), "{policy}");
// Bluesky's video service and CDN, for video, once each.
for v in hud_core::blobs::VIDEO_ORIGINS {
assert_eq!(media.matches(v).count(), 1, "{policy}");
}
assert!(!csp(ORIGIN, None).contains("images.example"));
let bluesky = csp(ORIGIN, Some("https://cdn.bsky.app"));
assert_eq!(
docs/internals.md+4−2
@@ -29,7 +29,9 @@ Every image, audio and video blob in a record gets a sibling `url`, `<public ori
When a PDS sends a blob untyped (`application/octet-stream`), the proxy knows it by its first bytes. It never serves a blob as HTML or SVG. Browsers cache it forever, since a CID never changes.
Images stream straight through. The proxy keeps audio and video on disk first (`<HUD_CACHE_DIR>/blobs/<cid>`), and only if their bytes hash to their CID. That lets a player seek, because PDSes answer whole blobs only and the proxy answers `Range` from the cache.
Images stream straight through. The proxy keeps audio and video on disk (`<HUD_CACHE_DIR>/blobs/<cid>`), and only if their bytes hash to their CID. That lets a player seek, because PDSes answer whole blobs only and the proxy answers `Range` from the cache.
The proxy downloads each audio or video blob once, however many requests ask for it while it comes. It answers each request as the bytes arrive, against the length the PDS said, so a player starts on the first bytes, not the last. It sends a blob's last byte only once the whole hashes to its CID. A blob whose PDS gave no length is answered once all of it is here.
Like every other outbound request, the proxy's requests refuse plain `http` and private, loopback and link-local addresses. A DID document can name any host.
@@ -65,7 +67,7 @@ The service's DID document gives the endpoint of the service that its fragment n
Blob refs in an answer get URLs where HUD knows the repository holding them. That's the case for a record beside the `uri` naming it. Images go through the image CDN when HUD asks as no one or asks the AppView. Otherwise they go through the proxy alone.
Every video the answer shows (`app.bsky.embed.video#view`) gets a `url` of its blob from the proxy, in the repository of the post around it. The video's own playlist is HLS, which browsers other than Safari don't play. With the blob URL, the view plays it natively.
Every video the answer shows (`app.bsky.embed.video#view`) gets a `url` of its blob from the proxy, in the repository of the post around it. Its own playlist, HLS on Bluesky's video service (`video.bsky.app`, its segments on `video.cdn.bsky.app`), is adaptive and served from a CDN, so the resolved tree gives it too (`hls`). Where the platform plays HLS natively (iOS, Safari, Chrome), the video plays from there. Elsewhere (Firefox) it plays the blob from the proxy, and the view never loads hls.js.
HUD makes calls as no one. When signed in, it makes them through the account's PDS, which proxies them to the service (`atproto-proxy`), for the services its sign-in asks to call ([sign-in](sign-in.md#what-hud-asks-for)).
docs/views.md+3−2
@@ -51,7 +51,7 @@ handles these:
- images or a gallery
- a link card
- a video (played from the blob proxy)
- a video (played as Bluesky's HLS, or from the blob proxy)
- a quoted post with its own embed one level down (in a record's form, fetched from the AppView)
- a feed, list, starter pack or labeler card
- media with a quote
@@ -239,7 +239,8 @@ named along with where it is, so the model can fix it.
Only bundled views are trusted. Only they may name `origins`, the https origins whose media URLs
their bindings may load (plyr.fm keeps some audio and art off the PDS, and the AppView keeps its
images on `cdn.bsky.app`). The UI resource's CSP allows exactly those, beside the server's own
origin and the image CDN's (`HUD_IMAGE_CDN`). A view given inline may load media only through blob
origin, the image CDN's (`HUD_IMAGE_CDN`), and Bluesky's video service and CDN, for posts' videos.
A view given inline may load media only through blob
refs. No code names Bluesky, Grain, plyr.fm, standard.site or knotless.
A result says whether its view is trusted (`_meta.ui.trusted`). A trusted view's actions run on one
docs/workspace-api.md+1−1
@@ -92,4 +92,4 @@ The server sends a `ping` every 25 s. The stream ends when the server stops, and
## Page CSP
The page's CSP lets it reach only the server. It loads images and audio from the server and from the origins the bundled views trust, and images from the image CDN.
The page's CSP lets it reach only the server. It loads images and audio from the server and from the origins the bundled views trust, and images from the image CDN. It plays video from Bluesky's video service and CDN too.
ios/HUDKit/Sources/HUDKit/Embed/EmbedVideo.swift+8−6
@@ -2,16 +2,18 @@ import AVKit
import SwiftUI
// A post's video, as a resolved tree's Embed gives it, shaped by its aspect
// ratio before it loads: the system's player over the server's blob proxy
// (`src`), loading nothing until it is played, its poster drawn first.
// Without a `src` (a server that cannot reach it), the poster and a link to
// watch it on Bluesky.
// ratio before it loads: the system's player, loading nothing until it is
// played, its poster drawn first, over Bluesky's HLS (`hls`), adaptive and
// from its CDN, else the server's blob proxy (`src`). With neither (a
// server that cannot reach it), the poster and a link to watch it on
// Bluesky.
struct EmbedVideo: View {
/// What a video shows: where it plays from, its poster, shape and alt
/// text, and where Bluesky shows it, for one with nowhere to play.
struct Shown {
let src: URL?
let hls: URL?
let poster: Source?
let ratio: Double
let alt: String
@@ -33,14 +35,14 @@ struct EmbedVideo: View {
EmbedFrame(ratio: shown.ratio, maxHeight: 448) {
ZStack {
Color.black
if let src = shown.src {
if let stream = shown.hls ?? shown.src {
if let player {
VideoPlayer(player: player)
.accessibilityLabel(alt)
} else {
Picture(source: poster, alt: alt, fit: .fit, placeholder: "Video")
Button {
let made = AVPlayer(url: src)
let made = AVPlayer(url: stream)
player = made
made.play()
} label: {
ios/HUDKit/Sources/HUDKit/Tree/ResolvedEmbed.swift+1−0
@@ -42,6 +42,7 @@ struct ResolvedEmbed: View {
EmbedVideo(
shown: EmbedVideo.Shown(
src: Resolved.url(embed["src"]),
hls: Resolved.url(embed["hls"]),
poster: embed["poster"]?.string.map { Source(src: $0, fallback: nil) },
ratio: embed["ratio"]?.number ?? 16 / 9,
alt: embed["alt"]?.string ?? "Video",
schemas/place.hud.ui.json+3−2
web/renderer/src/embed/VideoView.svelte+14−7
web/renderer/src/tree/Embed.svelte+1−1
web/renderer/src/tree/types.ts+1−1
AGENTS.md+2−1