We replaced H.264 streaming with JPEG screenshots (and it worked better)

blog.helix.ml

265 points by quesobob 5 hours ago


mikepavone - 3 hours ago

> When the network is bad, you get... fewer JPEGs. That’s it. The ones that arrive are perfect.

This would make sense... if they were using UDP, but they are using TCP. All the JPEGs they send will get there eventually (unless the connection drops). JPEG does not fix your buffering and congestion control problems. What presumably happened here is the way they implemented their JPEG screenshots, they have some mechanism that minimizes the number of frames that are in-flight. This is not some inherent property of JPEG though.

> And the size! A 70% quality JPEG of a 1080p desktop is like 100-150KB. A single H.264 keyframe is 200-500KB. We’re sending LESS data per frame AND getting better reliability.

h.264 has better coding efficiency than JPEG. For a given target size, you should be able to get better quality from an h.264 IDR frame than a JPEG. There is no fixed size to an IDR frame.

Ultimately, the problem here is a lack of bandwidth estimation (apart from the sort of binary "good network"/"cafe mode" thing they ultimately implemented). To be fair, this is difficult to do and being stuck with TCP makes it a bit more difficult. Still, you can do an initial bandwidth probe and then look for increasing transmission latency as a sign that the network is congested. Back off your bitrate (and if needed reduce frame rate to maintain sufficient quality) until transmission latency starts to decrease again.

WebRTC will do this for you if you can use it, which actually suggests a different solution to this problem: use websockets for dumb corporate network firewall rules and just use WebRTC everything else

qbow883 - 2 hours ago

Setting aside the various formatting problems and the LLM writing style, this just seems all kinds of wrong throughout.

> “Just lower the bitrate,” you say. Great idea. Now it’s 10Mbps of blocky garbage that’s still 30 seconds behind.

10Mbps should be way more than enough for a mostly static image with some scrolling text. (And 40Mbps are ridiculous.) This is very likely to be caused by bad encoding settings and/or a bad encoder.

> “What if we only send keyframes?” The post goes on to explain how this does not work because some other component needs to see P-frames. If that is the case, just configure your encoder to have very short keyframe intervals.

> And the size! A 70% quality JPEG of a 1080p desktop is like 100-150KB. A single H.264 keyframe is 200-500KB.

A single H.264 keyframe can be whatever size you want, *depending on how you configure your encoder*, which was apparently never seriously attempted. Why are we badly reinventing MJPEG instead of configuring the tools we already have? Lower the bitrate and keyint, use a better encoder for higher quality, lower the frame rate if you need to. (If 10 fps JPEGs are acceptable, surely you should try 10 fps H.264 too?)

But all in all the main problem seems to be squeezing an entire video stream through a single TCP connection. There are plenty of existing solutions for this. For example, this article never mentions DASH, which is made for these exact purposes.

nemothekid - 36 minutes ago

I'm very familiar with the stack and the pain of trying to livestream video to a browser. If JPEG screenshots work for your clients, then I would just stick with that.

The problem with wolf, gstreamer, moonlight, $third party, is you need to be familiar with how the underlying stack handles backpressure and error propagation, or else things will just "not work" and you will have no idea why. I've worked on 3 projects in the last 3 years where I started with gstreamer, got up and running - and while things worked in the happy path, the unhappy path was incredibly brittle and painful to debug. All 3 times I opted to just use the lower level libraries myself.

Given all of OPs requirements, I think something like NVIDIA Video Codec SDK to a websocket to MediaSource Extensions.

However, given that even this post seems to be LLM generated, I don't think the author would care to learn about the actual internals. I don't think this is a solution that could be vibe coded.

adamjs - 4 hours ago

They might want to check out what VNC has been doing since 1998– keep the client-pull model, break the framebuffer up into tiles and, when client requests an update, perform a diff against last frame sent, composite the updated tiles client-side. (This is what VNC falls back to when it doesn’t have damage-tracking from the OS compositor)

This would really cut down on the bandwidth of static coding terminals where 90% of screen is just cursor flashing or small bits of text moving.

If they really wanted to be ambitious they could also detect scrolling and do an optimization client-side where it translates some of the existing areas (look up CopyRect command in VNC).

somehnguy - 32 minutes ago

40mbps for video of an LLM typing text didn't immediately fire off alarm bells in anyone's head that their approach was horribly wrong? That's an insane amount of bandwidth for what they're trying to do.

Dylan16807 - 5 hours ago

> When the network is bad, you get... fewer JPEGs. That’s it. The ones that arrive are perfect.

You can have still have weird broken stallouts though.

I dunno, this article has some good problem solving but the biggest and mostly untouched issue is that they set the minimum h.264 bandwidth too high. H.264 can do a lot better than JPEG with a lot less bandwidth. But if you lock it at 40Mbps of course it's flaky. Try 1Mbps and iterate from there.

And going keyframe-only is the opposite of how you optimize video bandwidth.

kccqzy - 4 hours ago

There are so many things that I would have done differently.

> We added a keyframes_only flag. We modified the video decoder to check FrameType::Idr. We set GOP to 60 (one keyframe per second at 60fps). We tested.

Why muck around with P-frames and keyframes? Just make your video 1fps.

> Now it’s 10Mbps of blocky garbage that’s still 30 seconds behind.

10 Mbps is way too much. I occasionally watch YouTube videos where someone writes code. I set my quality to 1080p to be comparable with the article and YouTube serves me the video at way less than 1Mbps. I did a quick napkin math for a random coding video and it was 0.6Mbps. It’s not blocky garbage at all.

andai - 3 hours ago

Many moons ago I was using this software which would screenshot every five seconds and give you a little time lapse and the end of the day. So you could see how you were spending your computer time.

My hard disk ended up filling up with tens of gigabytes of screenshots.

I lowered the quality. I lowered the resolution, but this only delayed the inevitable.

One day I was looking through the folder and I noticed well almost all the image data on almost all of these screenshots is identical.

What if I created some sort of algorithm which would allow me to preserve only the changes?

I spent embarrassingly long thinking about this before realizing that I had begun to reinvent video compression!

So I just wrote a ffmpeg one-liner and got like 98% disk usage reduction :)

nrhrjrjrjtntbt - 6 minutes ago

Thats fun. I take it JPEG (what settings lolz!) is compressing harder than a keyframe.

But you are waching code. Why not send the code? Plus any css/html used to render it pretty. Or in other words why not a vscode tunnel?

Tarean - 4 hours ago

Having pair programmed over some truly awful and locked down connections before, dropped frames are infinitely better than blurred frames which make text unreadable whenever the mouse is moved. But 40mbps seems an awful lot for 1080p 60fps.

Temporal SVC (reduce framerate if bandwidth constrained) is pretty widely supported by now, right? Though maybe not for H.264, so it probably would have scaled nicely but only on Webrtc?

dotancohen - 4 hours ago

They're just streaming a video feed of an LLC running in a terminal? Why not stream the actual text? Or fetch it piecemeal over AJAX requests? They complain that corporate networks support only HTTPS and nothing else? Do they not understand what the first T stands for?

laurencerowe - 4 hours ago

If you are ok with a second or so of latency then MPEG-DASH (standardized version of HTTP Live Streaming) is likely the best bet. You simply serve the video chunks over HTTP so it should be just as compatible as the JPEG solution used here but provide 60fps video rather than crappy jpegs.

The standard supports adaptive bit rate playback so you can provide both low quality and high quality videos and players can switch depending on bandwidth available.

robrain - 5 hours ago

"Think “screen share, but the thing being shared is a robot writing code.”"

Thinks: why not send text instead of graphics, then? I'm sure it's more complicated than that...

keerthiko - 3 hours ago

> The fix was embarrassingly simple: once you fall back to screenshots, stay there until the user explicitly clicks to retry.

There is another recovery option:

- increase the JPEG framerate every couple seconds until the bandwidth consumption approaches the H264 stream bandwidth estimate

- keep track latency changes. If the client reports a stable latency range, and it is acceptable (<1s latency, <200ms variance?) and bandwidth use has reached 95% of H264 estimate, re-activate the stream

Given that text/code is what is being viewed, lower res and adaptive streaming (HLS) are not really viable solutions since they become unreadable at lower res.

If remote screen sharing is a core feature of the service, I think this is a reasonable next step for the product.

That said, IMO at a higher level if you know what you're streaming is human-readable text, it's better to send application data pipes to the stream rather than encoding screenspace videos. That does however require building bespoke decoders and client viewing if real time collaboration network clients don't already exist for the tools (but SSH and RTC code editors exist)

karhuton - 4 hours ago

I made this because I got tired of screensharing issues in corporate environments: https://bluescreen.live (code via github).

Screenshot once per second. Works everywhere.

I’m still waiting for mobile screenshare api support, so I could quickly use it to show stuff from my phone to other phones with the QR link.

andai - 3 hours ago

I recognize this voice :) This is Claude.

MBCook - 4 hours ago

So it’s video of an AI typing text?

Why not just send text? Why do you need video at all?

throwaway173738 - an hour ago

This article reminds me so much of so many hardware providers I deal with at work who want to put equipment on-site and then spend the next year not understanding that our customers manage their own firewall. No, you can’t just add a new protocol or completely change where your stuff is deployed because then our support team has to contact hundreds of customers about thousands of sites.

rcarmo - 5 hours ago

This was the most entertaining thing I read all day. Kudos.

I've had similar experiences in the past when trying to do remote desktop streaming for digital signage (which is not particularly demanding in bandwidth terms). Multicast streaming video was the most efficent, but annoying to decode when you dropped data. I now wonder how far I could have gone with JPEGs...

Jakob - 4 hours ago

Yes, this is unfortunately still the way and was very common back when iOS Safari did not allow embedded video.

For a fast start of the video, reverse the implementation: instead of downgrading from Websockets to polling when connection fails, you should upgrade from polling to Websockets when the network allows.

Socket.io was one of the first libraries that did that switching and had it wrong first, too. Learned the enterprise network behaviour and they switched the implementation.

benterix - 3 hours ago

> And the size! A 70% quality JPEG of a 1080p desktop is like 100-150KB. A single H.264 keyframe is 200-500KB.

I believe the latter can be adjusted in codec settings.

jayd16 - 4 hours ago

So they replaced a TCP connection with no congestion control with a sycnronous poll of an endpoint which is inherently congestion controlled.

I wonder if they just tried restarting the stream at a lower bitrate once it got too delayed.

The talk about how the images looks more crisp at a lower FPS is just tuning that I guess they didn't bother with.

egorfine - 5 hours ago

> The constraint that ruined everything: It has to work on enterprise networks.

> You know what enterprise networks love? HTTP. HTTPS. Port 443. That’s it. That’s the list.

That's not enough.

Corporate networks also love to MITM their own workstations and reinterpret http traffic. So, no WebSockets and no Server-Side Events either, because their corporate firewall is a piece of software no one in the world wants and everyone in the world hates, including its own developers. Thus it only supports a subset of HTTP/1.1 and sometimes it likes to change the content while keeping Content-Length intact.

And you have to work around that, because IT dept of the corporation will never lift restrictions.

I wish I was kidding.

algesten - 4 hours ago

WebSockets over TCP is probably always going to cause problems for streaming media.

WebRTC over UDP is one choice for lossy situations. Media over Quic might be another (is the future here?), and it might be more enterprise firewall friendly since HTTP3 is over Quic.

any1 - 3 hours ago

I have some experience with pushing video frames over TCP.

It appears that the writer has jumped to conclusions at every turn and it's usually the wrong one.

The reason that the simple "poll for jpeg" method works is that polling is actually a very crude congestion control mechanism. The sender only sends the next frame when the receiver has received the last frame and asks for more. The downside of this is that network latency affects the frame rate.

The frame rate issue with the polling method can be solved by sending multiple frame requests at a time, but only as many as will fit within one RTT, so the client needs to know the minimum RTT and the sender's maximum frame rate.

The RFB (VNC) protocol does this, by the way. Well, the thing about rtt_min and frame rate isn't in the spec though.

Now, I will not go though every wrong assumption, but as for this nonsense about P-frames and I-frames: With TCP, you only need one I-frame. The rest can be all P-frames. I don't understand how they came to the conclusion that sending only I-frames over TCP might help with their latency problem. Just turn off B-frames and you should be OK.

The actual problem with the latency was that they had frames piling up in buffers between the sender and the receiver. If you're pushing video frames over TCP, you need feedback. The server needs to know how fast it can send. Otherwise, you get pile-up and a bunch of latency. That's all there is to it.

The simplest, absolutely foolproof way to do this is to use TCP's own congestion control. Spin up a thread that does two things: encodes video frames and sends them out on the socket using a blocking send/write call. Set SO_SNDBUF on that socket to a value that's proportional to your maximum latency tolerance and the rough size of your video frames.

One final bit of advice: use ffmpeg (libavcodec, libavformat, etc). It's much simpler to actually understand what you're doing with that than some convoluted gstreamer pipeline.

dimatura - 2 hours ago

About eight years ago I was trying to stream several videos of a drone over the internet for remote product demos. Since we were talking to customers while the demo happened, the latency needed to be less than a few seconds. I couldn't get that latency with the more standard streaming video options I tried, and at the time setting up something based on WebRTC seemed pretty daunting. I ended up doing something pretty much like JPEGs as well, via the jsmpeg library [1]. Worked great.

[1] https://jsmpeg.com/ (tagline: "decode like it's 1999")

petcat - 5 hours ago

so did they reinvent mjpeg

nico - 3 hours ago

Super interesting. Some time ago I wrote some code that breaks down a jpeg image into smaller frames of itself, then creates an h.264 video with the frames, outputting a smaller file than the original image

You can then extract the frames from the video and reconstruct the original jpeg

Additionally, instead of converting to video, you can use the smaller images of the original, to progressively load the bigger image, ie. when you get the first frame, you have a lower quality version of the whole image, then as you get more frames, the code progressively adds detail with the extra pixels contained in each frame

It was a fun project, but the extra compression doesn’t work for all images, and I also discovered how amazing jpeg is - you can get amazing compression just by changing the quality/size ratio parameter when creating a file

poly2it - 3 hours ago

Why is video streaming so difficult? We've been doing it for decades, why is there seemingly no FOSS library which let's me encode an arbitrary dynamic frame rate image stream in Rust and get HD data with delta encoding in a browser receiver? This is insanity.

epx - 5 hours ago

Would HLS be an option? I publish my home security cameras via WebRTC, but I keep HLS as a escape for hotel/cafe WiFi situations (MediaMTX makes it easy to offer both).

binocarlos - 5 hours ago

> I mashed F5 like a degenerate.

I love the style of this blog-post, you can really tell that Luke has been deep down in the rabbit hole, encountered the Balrog and lived to tell the tale.

avsn - 4 hours ago

We did something similar in one of the places I've worked at. We sent xy coordinates and pointer events from our frontend app to our backend/3d renderer and received JPEG frames back. All of that wrapped in protobuf messages and sent via WS connection. Surpassingly it kinda worked, not "60fps worked" though obviously.

bandamo - 27 minutes ago

would like to see what alternatives were looked at. RDP with a html client (guacamole) seams like a good match

K0nserv - 2 hours ago

You can do TURN using TLS/TCP over port 443. This can fool some firewalls, but will still fail for instances when an intercepting HTTP proxy is used.

The neat thing about ICE is that you get automatic fallbacks and best path selection. So best case IPv6 UDP, worst case TCP/TLS

One of the nice things about HTTP3 and QUIC will be that UDP port 443 will be more likely to be open in the future.

wewewedxfgdf - 4 hours ago

webp is smaller than jpeg

https://developers.google.com/speed/webp/docs/webp_study

ALSO - the blog author could simplify - you don't need any code at all at the web browser.

The <img> tag automatically does motion jpeg streaming.

Eduard - 2 hours ago

> A JPEG screenshot is self-contained. It either arrives complete, or it doesn’t. There’s no “partial decode.”

What about Progressive JPEG?

STELLANOVA - 3 hours ago

We did something similar +12 years ago with `streaming` AWS running app inside the browser. Basically you can run 3d studio max on chromebook. App is actually running on AWS instance and it just sending jpegs to browser to `stream` it. We did a lot of QoS logic and other stuff but it was actually working pretty nice. Adobe used it for some time to allow user to run Photoshop in the browser. Good old days..

julik - 2 hours ago

Having built an image sequence player using JPEGs back in the day - I can attest that it slappps.

breve - 3 hours ago

WebP is well supported in browsers these days. Use WebP for the screenshots instead of JPEG and it will reduce the file size:

https://developers.google.com/speed/webp/gallery1

https://caniuse.com/webp

wood_spirit - 5 hours ago

A long time ago I was trying to get video multiplexing to work over mobile over 3G. We struggled with H264 which had broad enough hardware support but almost no tooling and software support on the phones we were targeting. Even with engineers from the phone manufacturer as liaison we struggled to get access to any kind or SDK etc. We ended up doing JPEG streaming instead, much like the article said. And it worked great but we discovered we were getting a fraction of the framerate reported in Flash players - the call to refresh the screen was async and the act of receiving and deciding the next frame staved the redraw so the phone spent more time receiving lots of frames but not showing them. Super annoying and I don’t think the project survived long enough for us to find a fix.

praveen9920 - 4 hours ago

This reminds me of the time we built a big angular3 codebase for a content platform. When we had to launch, the search engines were expecting content to be part of page html while we are calling APIs to fetch the content ( angular3 didn’t have server side rendering at that point)

So only plausible thing to do was pre-build html pages for content pages and let load angular’s JS take its time to load ( for ux functionality). It looked like page flickered when JS loads for the first time but we solved the search engine problem.

visiondude - 2 hours ago

I very confused, couldn’t they have achieved much better outcome with existing hls tech with adaptive bitrate playlists? Seems they both created the problem and found a suboptimal solution.

bob1029 - 5 hours ago

> Why JPEGs Actually Slap

JPEG is extremely efficient to [de/en]code on modern CPUs. You can get close to 1080p60 per core if you use a library that leverages SIMD.

I sometimes struggle with the pursuit of perfect codec efficiency when our networks have become this fast. You can employ half-assed compression and still not max out a 1gbps pipe. From Netflix & Google's perspective it totally makes sense, but unless you are building a streaming video platform with billions of customers I don't see the point.

sevensor - 4 hours ago

No mention of PNGs? I don’t usually go to jpegs first for screenshots of text. Did png have worse compression? Burn more cpu? I’m sure there are good reasons, but it seems like they’ve glossed over the obvious choice here.

edit: Thanks for the answers! The consensus is that PNG en/de -coding is too expensive compared to jpeg.

tylertyler - an hour ago

I've found that WebM works much better because of the structure of the data in the container. I've also gone down similar routes using outdated tech and even inventing my own encoder and decoders trying to smooth things out but what I've currently found is the best current approach is using WebM because it is easier to lean on hardware encoder and decoders including across browsers with the new WebCodecs APIs. What I've been working on is a little different than what is in this post but but I'm pretty sure this logic still stands.

Sean-Der - 4 hours ago

Doesn’t matter now, but what led you to TURN?

You can run all WebRTC traffic over a single port. It’s a shame you spent so much time/were frustrated by ICE errors

That’s great you got something better and with less complexity! I do think people push ‘you need UDP and BWE’ a little too zealously. If you have a homogeneous set of clients stuff like RTMP/Websockets seems to serve people well

- 4 hours ago
[deleted]
elzbardico - 2 hours ago

There's no real reason other than bad configuration/coding for a H.264 1080p 30fps screen share stream to sustainably use 40mbps. You can watch an action move at the same frame rate but with 4k resolution while using less than half this bandwidth.

The real solution is using WebRTC, like every single other fucking company that have to stream video is doing. Yes, enterprise consumers require additional configuration. Yes, sometimes you need to provide a "network requirements" sheet to your customer so they can open a ticket with their IT to configure an exception.

Second problem, usually enterprise networks are not as bad as internet cafe networks, but then, internet café networks usually are not locked down, so, you should always try first the best case scenario with webrtc and turn servers on 3478. That will also be the best option for really bad networks, but usually those networks are not enterprise networks.

Please configure your encoder, 40mbps bit rate for what you're doing is way way too much.

Test if TURN is not acessible. try it first with UDP (the best option and will also work with internet cafe), if not try over tcp on port 443, not working? try over tls on port 443.

- 4 hours ago
[deleted]
gametheory87 - 4 hours ago

It’s always TCP_NODELAY seems relevant here: https://news.ycombinator.com/item?id=40310896

escapecharacter - 4 hours ago

I guess this is great as long as you don't worry about audio sync?

colechristensen - 35 minutes ago

H.264 can be used to encode a single frame as an effective image with better compression than JPEG.

keepamovin - 4 hours ago

This is similar to what BrowserBox does for the same reasons outlined. Glad to see the control afforded by "ye olde ways" is recognized and widely appreciated.

ddtaylor - 4 hours ago

A very stupid hack that can work to "fix" this could be to buffer the h264 stream at the data center using a proxy before sending it to the real client, etc.

mgaunard - 2 hours ago

RTP is specifically designed for real-time video.

mring33621 - 3 hours ago

This is such a great post. I love the "The Oscillation Problem"!

tverbeure - 4 hours ago

I’m surprised that H264 I-frame only compresses less than JPG.

Maybe because the basic frequency transform is 4x4 vs 8x8 for JPG?

ddtaylor - 5 hours ago

> I mashed F5 like a degenerate

Bargaining.

the8472 - 4 hours ago

> looks at TCP congestion control literature

> closes tab

Eh, there are a few easy things one can try. Make sure to use a non-ancient kernel on the sender side (to get the necessary features), then enable BBR and NOTSENT_LOWAT (https://blog.cloudflare.com/http-2-prioritization-with-nginx...) to avoid buffering more than what's in-flight and then start dropping websocket frames when the socket says it's full.

Also, with tighter integration with the h264 encoder loop one could tell it which frames weren't sent and account for that in pframe generation. But I guess that wasn't available with that stack.

mschuster91 - 2 hours ago

> We are professionals. We implement proper video codecs. We don’t spam HTTP requests for individual frames like it’s 2009.

I distinctly 'member doing CGI stuff with HTTP multipart responses... although I bet that with the exception of Apache, server (and especially: reverse proxy) side support for that has gone down the drain.

moralestapia - 3 hours ago

>A single H.264 keyframe is 200-500KB.

Hmm they must be doing something wrong, they're not usually that heavy.

willseth - 4 hours ago

“We didn’t have the expertise to build the thing we were building, got in way over our heads, and built a basic POC using legacy technology, which is fine.”

mannyv - 4 hours ago

Awesome!

Good engineering: when you're not too proud to do the obvious, but sort of cheesy-sounding solution.

refulgentis - 4 hours ago

The LinkedIn slop tone, random bolding, miscopied Markdown tables makes me invoke: "please read the copy you worked on with AI"

smaller thing: many, many, moons ago, I did a lot of work with H.264. "A single H.264 keyframe is 200-500KB." is fantastical.

Can't prove it wrong because it will be correct given arbitrary dimensions and encoding settings, but, it's pretty hard to end up with.

Just pulled a couple 1080p's off YouTube, biggest I-frame is 150KB, median is 58KB (`ffprobe $FILE -show_frames -of compact -show_entries frame=pict_type,pkt_size | grep -i "|pict_type=I"`)

andrewstuart - 2 hours ago

I wrote a motion jpeg server for precisely this use case.

https://github.com/crowdwave/maryjane

The secret to great user experience is you return the current video frame at time of request.

dengolius - 3 hours ago

what about av1?

lostmsu - 5 hours ago

If you have latency detection already why not pause H.264 frames, then when ack comes just force a key frame and resume (perhaps with adjusted target bitrate)?

ErroneousBosh - 4 hours ago

So, they've invented MJPEG?

Or is it intra-only H.264?

I mean, none of this is especially new. It's an interesting trick though!

HocusLocus - 5 hours ago

This is a beautiful cope. Every time technology rolls out something that works great 90% of the time for 90% of the people, those 10%s pile up big time in support and lost productivity. You need functional systems that fall back gracefully to 1994 if necessary.

I started the first ISP in my area. We had two T1s to Miami. When HD audio and the rudiments of video started to increase in popularity, I'd always tell our modem customers, "A few minutes of video is a lifetime of email. Remember how exciting email was?"

j45 - 4 hours ago

One thing this article does point to indirectly is sometimes, simple scales, and complex fails.

worksonmine - 3 hours ago

I'm confused, do people actually watch their agents code like it was a screen share? Why does the AI even mess with that, just send a diff over text? Is it getting a keyboard next?

This is the definition of over-engineering. I don't usually criticize ideas but this is so stupid my head hurts.

hmontazeri - 4 hours ago

Another case of we’re going backwards. The boring stuff is what works every time…