Free peer-to-peer assisted live streaming

So it’s just like Napster?

The peer-to-peer realm… It goes so far off the ‘classic’ client-server paradigm it’s just a world in itself. If you’re not familiar with the topic, you will in turn have heard of Bitcoin, Tor, Skype, BitTorrent, DC++ or Napster. What do you know, they all rely on… 

P2P

Computers, smartphones and IoT devices can connect to each other and exchange data. The closer they are to one another, the faster and more efficient they can communicate. Ha, that’s actually not true 🙂 Open internet connectivity, routing and network peering is optimized for end-user devices to efficiently reach service providers’ servers. As for connecting to each other, it’s a hit and miss. Particularly due to extensive NATting and sometimes deliberate ISP blocks, but also other reasons, 2 random internet connected devices may or may not be able to communicate to each other directly.

Swarming

That’s ok. Except for special circumstances, an IP connected device can still connect to a bunch of quasi-random like-minded fellow devices to share data in a partly-predictable fashion. If you lived the age of torrent downloads, you probably do have a certain understanding of how individual clients team up and help each other towards a common goal by sharing pieces of that same individual content. Results will vary; peers in close vicinity to each other (network-wise, not necessarily geographic) do share faster while others have to wait, sometimes more than they would if downloading from an actual server. Regardless, pressure and traffic on the seed(s) is heavily reduced as compared to the scenario where all clients would have to download directly. 

The video streaming context

The amounts of data trafficked by video streaming are enormous. Meaning that somewhere there’s an enormous traffic bill. Forget the giants as they can strike nice deals with the CDNs, the average players will end up paying lots for broadcasting their venue outside of the ad-driven free services like YT and FB. 

So what if we could put some of that p2p magic to good use…?

Peer-assisted video streaming is not a new idea. Sure, unlike a torrent download you can’t afford your viewers to buffer a lot or play at low quality just because of inadequate peer availability. Instead, rely on your friendly CDN to quickly grab the first part of the video and, in parallel, start downloading latter pieces from peers as soon as you have secured a comfortable buffer to ensure smooth playback for a while; fall back to CDN if peering capabilities degrade.

The live video streaming context

Particular to live streaming, all viewers will be consuming the same pieces of content at the same time. This is of furthest importance and makes for a particularly interesting use case, as the sharing is way more straightforward. Think there’s just 5-10 pieces of video being circulated in the ‘swarm’ at any given time, as opposed to hundreds in an hour long VOD.

If not clear by now, peer-to-peer traffic is free. From the standpoint of the provider that is. Any slice of video downloaded from a peer rather than from a server is a penny saved. And the overall potential savings are huge! Think large communities of ‘neighbors’, like in a campus or compound, downloading that content just once or twice and sharing it among each other in a fast and fairly efficient network. 

And it gets more spectacular as the viewer count increases. For events with enormous audiences like the World Cup or the Superbowl, the sheer number of devices watching will lead to high incidence of high-speed peering and massive savings, all at a scale that might get a traditional client-proxy-server network to just crumble. 

Convinced yet? There’s more! It’s not just sheer savings on the content provider’s end. There’s also faster starts, reduced buffering, and superior quality on many of the viewers. For some it’s just as if they were connected to a faster network, with all the benefits of that. 

The readily available technology: HTML5 and WebRTC

WebRTC is finally part of almost any modern browser. And surprisingly unknown to many, it incorporates advanced peering capabilities. Details aside, a piece of JS code can drive swarming between browsers and get them to speed up, cut costs and improve the quality of video playback in a manner that’s transparent to the viewer. And it’s happening. For quite a while already WebTorrent has been around, ventures have tried to capitalize on the tech by selling it as a service, and ready-to-use open solutions eventually surfaced.

The Nugget 

Here it is, your very own p2p-enabled streaming platform, ready to deploy and start broadcasting in minutes. It’s based on this free and open initiative; though built and promoted by a private company there are no strings attached afaik. 

Does it scale?

Beautifully! As mentioned, this could actually sustain numbers that would overwhelm even the mightiest CDN, and that’s no overstatement. Minor note though, the proof of concept makes use of public trackers and if you need to stream to more than a couple thousand you’ll have to deploy your own. Scalability of that will be your bottleneck so take good care of it. 

How much can I save?

Hard to say. Some will advertise figures of ‘up to’ 90% or more, but your mileage will vary. The more watching the better, and the more concentrated into metropolitan areas or individual networks your viewers are, the more and faster they will peer. 

What’s the catch?

There isn’t one, everybody wins. Except… 🙂

  1. Extra traffic usage (think double) on most of the viewers due to the fact that they have to upload video pieces to others; not a problem for unlimited wifi but possibly problematic for those on a metered connection
  2. Extra overhead on each of the clients in terms of CPU and memory consumption; that’s needed to initiate and maintain tracker and peer connections and also manage and relay the extensive amount of data

Is the free solution inferior to commercial alternatives?

May very well be. As is the case with other tech, it’s easier and faster to build a proprietary system, and monetizing it may fuel further innovation. P2P is still a matter that spurs academic research, trade secrets and patents. At the core of any solution there’s a tracker and some replication algorithms that can vary immensely in key areas like central coordination, congestion avoidance, mesh optimization etc. Long story short it once again depends, and your use case is possibly very different from others’.

Dirt cheap live transcoding for ABR

Neet to pitch this at the lowest possible cost

Couldn’t stress it enough, except for a few borderline cases Adaptive Bitrate is simply a must have. Your viewers need to start fast and be able to watch the game on poor or fluctuating networks. 

Revisiting the topic as there are ever so many angles to approach it. For this one, (unsurprisingly) cost was the primordial factor and had to pull all the tricks to get it that cheap. 

In no particular order, and not necessarily to be used all together (actually some are incompatible), following are tactics to reduce the cost of an ABR setup:

Reduce the number of ABR renditions

The main point of ABR is to allow bandwidth-challenged viewers to play your content smoothly, may that be at a lower quality. The more renditions employed, the closer you will be able to match one’s capabilities (it’s at times not just bandwidth but also decoding horsepower and video canvas resolution) and offer them the best possible viewing experience.

On the other hand, having fewer renditions may lock some users into a less than ideal quality setting, yet still fluid, of reasonable visual quality, and with good audio. Especially if your content or programming does not mandate top quality (i.e. news), this may save a lot on transcoding in the long run. 

Add to that, much of the public has grown to instinctively realize a better network will lead to better quality and will make voluntary efforts to better their connection if they want a better video.  

Recycle the original encode 

This won’t work for all scenarios but…

Particularly when source feed is encoded by known studio equipment (unlike user contributed which tends to be less predictable) you can transmux the original video and make it the highest quality variant in the ABR set. Depending on the profile, this may save up to half the overall processing power needed for transcode.

Recycle the original audio

Simple, just mandate a middle ground audio bitrate/quality at the source and use it for all renditions. Not always ideal for audiophiles but good enough for us humans. 

Use lesser complex transcoding

Encoding is a fine trade-off between quality, bitrate (which translates in bandwidth required for transport) and processing needs. In the special case of live streaming, the transcoding device has to offer enough power to process the content in real time. Choosing a less complex transcoding profile, while requiring less computing resources, will lead to video that has a higher bitrate for the same quality, or lower quality for the same bitrate. Sure thing, traffic costs too, and it may be unwise to save pennies on one transcode and pay for the extra traffic multiplied by the number of viewers. Yet every case is different and numbers may be in favor of this approach at times. 

Use the GPU

Modern GPUs have had built-in dedicated video encoders for quite a while now and they can be put to good use in many scenarios. Just off the top of my head, you’d be able to transcode 2-4 times as cheap, real number depends on a huge amount of factors, most notably the cost of actually buying or renting the respective GPUs

Use the cloud

That’s a no brainer nowadays, I guess. Even if you have some idle dedicated servers lying around, it would be hard to set up a scalable solution around them. Between SaaS cloud transcoding and running custom software on cloud virtual servers, the latter is cheaper by far though it comes with extra headaches. 

Use free software

Duh, doesn’t get any cheaper than that. You don’t get to call support when something goes wrong, but hey, maybe your team is too good to ever need that. Encoders in ffmpeg and gstreamer (i.e. x264) are hardly inferior to their commercial counterparts and also mature and stable, so no real worries there, most software transcoders are built on top of them anyway.

Use a separate virtual server for every stream

That’s not necessarily a winner for every scenario. In fact it’s always more economical to be doing multiple transcodes on a more powerful machine. But that’s only if you can use that to full capacity, otherwise you’re as efficient as flying a large plane half empty.

Take advantage of the Launch Credits

This one is very close to a hack. Only particular to AWS, the older virtual server types (since the days they billed by the hour) will let you burst some cheap CPU credits and throw the instance away when depleted. There’s a limit to how much you can abuse the ‘feature’ but good enough to get you started at a real bargain.

Putting it all together (actually just some) …

…the solution is here for grabs. Deploys in a few clicks and sets you up with a rather generous ABR profile for as little as 2-5¢ (!!!) per hour of live streaming or well within the free tier if you still have that. 

Does it scale?

Not in all directions. Long story short, you can stay on the cheap end of the spectrum if you transcode up to a couple hundred hours of content per day, after that the perks start to run out.

Is it worth it?

Oh yess! If only I could pocket the savings it’s brought…

Is it stable/reliable?

Should be. For a while I monitored it in production and noticed no issues. See for yourself.

Is this blog sponsored by AWS?

No. And by no other company for that matter. I just happen to have been exposed to amazon’s much more than to others’, but (except perhaps for very specific use cases) do not believe it’s any better than other cloud platforms. Will gladly take on the challenge to deploy solutions in any environment or to objectively choose one that best suits particular needs.

The Free HTML5 Video Players – HLS and DASH

What player should I use?

This one is just about the completely free and open players. Not including the commercial products that offer a free starter alternative, free players that are tied to a commercial platform, not even the free ones that encompass proprietary technology.

Even so there’s a lot of them. Instead of a boring exhaustive comparative analysis, I’ll try to just list all the relevant ones along with as many key features and information, in a setup that’s compact and easy to digest. Also as part of the effort, took the time to put together a one-page HLS URL tester that lets you check out your own stream against any of the players. The DASH tester is coming soon. 

Basic info and capabilities

Player License Sponsor HLS Dash Library API Plugins
Video.js Apache 2.0 Brightcove x yes
Clappr BSD 3-Clause Globo via plugin x yes
Hls.js Apache 2.0 Netlify x x
Dash.js BSD 3-Clause DashIF x x
Shaka Apache 2.0 Google yes
Media Element MIT n/a via hls.js via dash.js x yes
Fluid Player MIT Exads via hls.js via dash.js x x
DPlayer MIT various via hls.js via dash.js or shaka x x
Plyr MIT n/a via hls.js via dash.js or shaka x x
OpenPlayerJS MIT n/a via hls.js via dash.js x ?

In this context, “library” means that some of the respective player’s features library can be easily used into some other player or context. For instance, dash.js and hls.js are used as protocol clients for many other players. 

Popular features

Player Skinning CC Support Thumbnails on seekbar Level Selector Chromecast & AirPlay 360/VR
Video.js advanced
Clappr ? x
Hls.js x ? x x
Dash.js x x x
Shaka basic x x
Media Element css x x
Fluid Player x x
DPlayer css x x
Plyr css x
OpenPlayerJS css x x x

Note that a “?” means unknown or undocumented. In case it’s not obvious, many of the “✓” are hyperlinks pointing to some page/article best describing the topic. 

Commercial features

Player Ads DRM Analytics
Video.js plugin availableplugin available plugin available plugins available
Clappr wip x plugins available
Hls.js x x
Dash.js x ?
Shaka not yet plugin available
Media Element supported via plugins via dash.js plugin available
Fluid Player via dash.js ?
DPlayer x via dash.js or shaka ?
Plyr plugin available via dash.js or shaka ?
OpenPlayerJS via dash.js ?

So what’s the best of them?

For your project, I don’t know… It will be your job to match the features to your needs, further look into the details and test to be sure it’s the right choice. 

I can tell you there’s a lot of criteria one may choose a player for, and interestingly, the strongest is personal preference. Fair enough, as having prior exposure to a product may greatly speed up deployment time; just be sure you’re not missing out on what the others have to offer. 

Second most important is the looks, and that’s kind of natural. Let me once again mention the tester, that’ll give you a quick glimpse of them all; remember most can be skinned tho, albeit some easier, fancier and/or more efficiently than others.

For what it’s worth, Video.js is the widest used by far, and the listing order roughly matches their popularity. Do however take the time to make a more educated choice if you need comercial features, a couple of those down the line have some interesting key strengths.

 Am I good with just a free player?

For the most part, you are. I’d say there’s no feature at least one of the players above does not offer, and long gone are the days when these were thought of as less stable or in any way substandard. Still, you will be missing proper support, documentation of some may be lacking/confusing, and incorporating some functionality may give you extra headaches. Furthermore, commercial player products do focus more on commercial features (i.e monetization, DRM, ad inserts, advanced statistics) and if you need these you may find that the extra bucks are totally worth it, especially if you’re actually selling the respective content.

Free DRM grade content protection for live streaming

We don’t fully understand copy protection. It’s mostly expensive, never flawless, and there’s even scam/conspiracy rumors around it.

Copy protection is a complex topic. At times misunderstood, misused or abused, despite standardization efforts there’s still confusion regarding schemes, providers, what browser supports what etc. 

May you start worrying about your content being compromised, liberally copied, or just inadvertently seen by unauthorized viewers, looking into a solution will probably soon send you into the arms of a DRM provider. Not that there’s anything wrong with it, but DRM is still pricey and not turnkey, so it may have your team put up with a steep learning curve.

Somewhat overlooked, the simpler flavours of content encryption (i.e. MPEG-CENC and HLS AES) still do a good job. Cryptography is just as strong, you can employ key rotation, and it costs nothing at all. You will however need to manage the keys yourself, inclusive of securing access to them. And also, unlike a real DRM, you won’t be able to allow your users to watch content offline, but that’s not really an issue for live video. 

In case you wonder, no protection is bulletproof. Provided enough determination and funds/skill, any scheme is ultimately vulnerable. Rather than trying to be perfect, safeguarding efforts are aimed at one or more of the following:

  • Prevent eavesdropping of content while it travels from source to destination via the open internet
  • Prevent clandestine viewing
  • Prevent content sharing by users properly authorized to see it
  • Make it harder or unfeasible to reverse engineer the encryption and obtain a digital copy of the original video by authorized viewers
  • Accomplish as much of the above, while maintaining as much of the user base as possible (some technologies may not be compatible with end-user devices etc)
  • Stay within budget and remain competitive

The cheap and easy solution I put together to be used out of the box makes use of HLS AES. It builds on the simple live streaming platform, adding encryption and key management. Rather than employing a dedicated key server, it just uses the application’s own environment to handle the keys; this greatly simplifies the workflow as the requests for a key will carry the session data (i.e. cookie) and that lets you instantly identify “who” is asking for the content. 

At a glance, the architecture/flow looks like this

The proof of concept merely ensures that only players accessing the video via your website/platform are able to consume the content. Any attempt to ‘hotlink’ to the .m3u8 URL dug up in the page source will fail to play, due to access to the decryption key being denied to any but the legit viewers. 

This is already a huge gain, as it will effectively block your content from being leached not just through browsers and apps, but also via VLC and stalker links, potentially saving you a lot on the traffic bill. But there’s more, the same session check mechanism can be employed to securely filter access to individual pieces of content to authorized viewers only, i.e. for a live pay-per-view platform.

Is it fast?

As compared to its non-encrypted counterpart, there is extra effort to encrypt/decrypt the content and distribute/retrieve the keys. 

Yet being that the encryption is symmetric, and the key size is fairly short (128 bit), this is less computationally intense than HTTPS, which is a breeze to virtually all modern servers and devices. 

The need for the player to download a key may delay the video start time by a roundtrip, but I’ve seen many downloading both the key and the payload (which is larger therefore slower) in parallel so no delay in the big picture.

Overall, I’d say there’s some added latency but that’s negligible, if done right, for all but a few corner case implements.

Does it scale?

Kind of 🙂

HLS manifest and payload (.ts) are identical for all viewers and can therefore be cached and distributed via CDNs, no issues here.

Keys, on the other hand, get rotated and also serving one to any user involves checking their credentials. That is potentially your bottleneck under high loads and special care may be needed to handle it. A normal CMS, however, will be dealing with the same credential check over and over doing any sort of other queries, so it’s unlikely that the added key check would make a significant impact on the bigger picture. 

So all in all, your platform would be just as scalable as it was before adding copy protection to it.

Is it stable/reliable?

A few variations of the solution are running in production, oldest for more than 2 years. While I’ve seen no issues with the architecture in itself, there have been some quirky implements that required extensive troubleshooting. As putting this together is a multidisciplinary effort, and the setup is somewhat atypical, there is room for misunderstandings. If handled improperly, authorized viewers may be wrongfully denied access or, on the flip side, content may be viewed illicitly by unauthorized viewers or even hotlinked to, and able to be publicly viewed via other sites or apps. Do understand that the main point of copy protection is to deny access to all but desired views and thoroughly test all use cases. Also, as there’s no way to send a message to the player about the reason of being denied access, do not rely on the key serving mechanism for anything other than preventing deliberately illicit access to the content. 

Is it effective?

For what it’s worth, there’s no viable way to safeguard against screen recording. Call that the “analog hole” although it has meanwhile turned digital, if there is will to obtain an illegal copy of something, then there is a way, may that mean that it will have a lower quality than the original. 

That said, the solution admirably manages to:

  • Make your content impossible to be viewed from another site or app
  • Make your content impossible to be viewed via shared .m3u8 links
  • Make your content impossible to be viewed on your site/app unless authorized
  • Cost nothing
  • Be compatible with all modern browsers and platforms

Can I use it to stream studio content or mainstream sports?

Probably not. The licensor of these may require you to use full-blown DRM. And for good reason, as they can’t trust a custom implement, and don’t have the means to audit it. Instead they will prefer to rely on tried and true schemes and providers. Each have their own requirements so be sure to ask. 

You will still be able to use it for most non-mainstream content though, like indie films/music, college sports, and lots of other stuff.

Dirt cheap live streaming platform

All in all, there are quite a few solutions out there, but none cheap and straightforward at the same time

Ok, as compared to the previous this is rather basic. There’s no recording, no adaptive bitrate, reduced scalability, no content protection, and it may require some maintenance. But it does the job. You will be able to run a handful of concurrent streams and there’s no limit to how many can watch. 

At the core of the solution there’s a tiny Nginx-RTMP server that takes care of ingesting RTMP streams and transmuxing these as HLS. Runs in the cloud of course, can be sized to meet demand, and it’s as cheap as it gets. 

Not much more to say, solution’s been around for years, and still waiting for more implementers to put it to good use. Had the chance to use it over and over in various scenarios, finally took the time to dust the simplest one up and make it available to deploy in a few clicks. Here it is.

How cheap can it get and why is it not free?

Yea, I know. Streaming to YT and FB is free, but they run ads on top of your content. With this, you can have it ad-free or run your own.

The virtual server pricing starts around 0.5¢/h. If running your live events sporadically you can turn that on and off as needed to save costs. And you want to broadcast 24/7 you can have it even cheaper by purchasing a reservation

Next up, you will be paying for traffic at regular CDN rates. The more people are watching, and for longer they watch, the more traffic they will spend against your account. 

Also important, the higher your audio+video bitrate, the higher your bandwidth consumption and your bill. Since this has no ABR, I’d recommend you keep your video resolution at or below 720p and combined a/v bitrate below 2Mbit. That equates to under a Gigabyte of traffic used up for every viewer watching for an hour, or proportional. 

Is it stable?

Very, just don’t throw too much at it. With just half a Gigabyte of RAM, the tiny server gracefully runs a dozen streams. If you need more (at the same time) just make it bigger. 

Other than that, OS upgrades I think may come in handy for the sake of security. Or just trash it and make it new every once in a while.

Does it scale?

Viewer wise, yes it does, as it runs on the CDN.

Broadcaster count wise, you’ll have to scale it manually. That is, adjust your server’s instance type based on demand. Bottlenecks are memory and networking, and secondarily CPU. The most one single server can take is probably around 1k, beyond that you will want to consider a multiple origin or SaaS solution. 

Is it worth it?

It’s sure worth trying it out if you’re just starting. Should take less than 30min to set it up, even if you don’t know much about the field. 

Moving on, you can rather easily make it grow, both in terms of capacity and capabilities. The underlying software is powerful, versatile, and packed with features. And if the AWS is not your flavor, solution can easily be ported to another cloud, or a colocated physical or virtual machine. It’ll even run on a Raspberry Pi, just be sure it has enough bandwidth to stream up and down.

Synchronized live streaming for HLS and DASH

That’s a race against the clock, so everybody should have the same clock.

It’s no secret, traditional OTT live feeds are not just delayed, but the delay is arbitrary and each screen will be slightly out of sync with any other. It’s not even a surprise if you understand the inner workings of internet streaming. Basically, the client will download chunks of content in a sequence and start playing that as soon as it’s lengthy enough to be considered safe to further play without interruption. No more waiting as that would worsen the user experience. Yet for others, the download time won’t be the same, so they’d start playback somewhat earlier or later. 

However, there’s times when you really need your viewers to see the same thing at the same time, otherwise it may offer some an unfair advantage, if seeing something even narrowly ahead of others. Think gambling or sports betting, auctions or trivia shows.

There are so many approaches to synchronizing your users’ video feed that I’ll have to dare categorize them; that is for fear of having to go into detail. As they all need an immutable reference to synchronize to, that may be the best criteria:

  1. Sync to NTP or equivalent
    You can’t assume your users’ devices’ clock is accurate. In fact, it’s often not. So one solution will be to get a sample of the “good” time via a reliable clock sync protocol like NTP; of course, you won’t “fix” the user’s clock but rather use it internally for video synchronization; for this to work, video has to carry similar wall-clock information with timestamps obtained from the same NTP source
  2. Sync to video/media server
    Socket-based video transmissions like RTMP or SLDP can benefit from the intimate connection with the server to swiftly get a reasonably accurate time sample directly from it; in the end, it’s not important what wall-clock you sync to, just that incoming and outgoing video can use the same absolute time reference 
  3. Sync implicitly for low/ultra-low latency and near-realtime streaming
    While for some sub-second delivery mechanisms the delay is so small that its fluctuation is inherently within certain acceptable margins for many applications, several providers will build fixed-delay capabilities right into the protocol and even advertise frame-accurate sync. Won’t further elaborate on the topic for now but some of it has been addressed here.

Interesting to note, the sync isn’t always perfect. That’s because, unlike broadcast television that uses dedicated data channels, OTT makes large use of the public internet and unpredictable private networks. Rather, the solutions will aim to bring the gap under a threshold that serves the purpose. 100 or 200 ms will be acceptable for gambling etc., while a 25-50ms will be fine even for displaying 2 TVs side by side in the same room.

Also important, the larger the tolerable live delay, the better you’ll be able to sync. Having a playback buffer helps deal with bandwidth fluctuations, but in the case of synchronized play this buffer will need to have the same length for all. 

And just so you know, being in sync just won’t work for every one of your viewers. Even with ABR, simply offering a playable stream at all is challenging enough for some device/bandwidth combinations; not having the luxury to pause and buffer (because it would go out of sync) will be too much for a few, and a drop-out strategy will need set in place (i.e. notify the user they can’t support playback). You’ll actually have to trade off between how many can watch and how strict of a sync you are imposing. You’d need to employ certain analytics to know for sure, but expect to cover at least 95% in areas with good high speed coverage like Europe and North America for a 200ms tolerance. 

In light of the above, customer needed a proof-of-concept sync strategy to deploy on top of their HLS and DASH setup. What’s been delivered is pretty basic but also quite flexible. It allows adjusting the live delay (i.e. 10 seconds) and the sync tolerance (i.e. 100ms) to experimentally adjust to the optimal setup for a given use case. They may have further built upon or never have used it (can’t tell) but agreed to share the initial deliverable. It is here for anyone to use or hack with. 

Does it scale?

Yeah. The sync is handled in the client browser so there’s nothing burdening the delivery. Any scaling scheme you’d deploy for HLS or DASH would still be compatible. For what it’s worth, the NTP server needs to keep up with all the requests but that should be trivial. 

Is it stable?

Not to perfection. I’ve seen it glitching numerous times (it’s a POC mind you), especially when bringing the numbers down to a certain limit. Ideally, you’d know your audience and (at least) emulate their worst network capabilities to roughly tune your initial product. Going further, consider gathering QoS statistics and further improve upon it. 

Is it worth it?

No idea 🙂 As with most open source solutions, you will eventually run into issues you can’t blame anyone for. If you have a skilled dev/qa team, manipulating this should be a breeze. Otherwise you may want to opt for an enterprise solution, there’s at least a handful out there.

Is it expensive?

Figure it out yourself 🙂 There’s no added data or infrastructure costs, just the work of altering, tuning and maintaining the “synchronizing” player.

Affordable live transcoding at scale

…better to be quicker to market and optimize later

We’ve examined the topic before, just that this time it’s not about Wowza. There are many ways to approach live transcoding and each best fits a particular context. 

For this one we’re once again in the nasty case of mostly short-lived broadcasts and ever-fluctuating, unpredictable broadcaster count.

Between cloud transcoding and doing it yourself, I will advise anyone starting up to boldly go with the former, smoothly set their streaming venture in motion, and perhaps consider investing in a custom monster transcoder later. There’s a lot to learn from running at scale, so you may not get it right from the start anyway.

Even the cloud solution is not trivial, it requires manual (read programmatic) starting and stopping of transcoding threads, and finding a smart way to balance cost vs availability. As there’s a cost for keeping a transcoder up, even if idle/unused, and it can take a minute or 2 to start one, the way to go about instantly processing new feeds will be to maintain a pool of idle, “on standby” workers. Logic of how many at a certain time can be improved over time, we’ll start with letting that be a fixed number (i.e. 1 or 2 or 5, easily adjustable manually).

AWS MediaLive was chosen for this architecture, and cost has been the decisive factor. Unlike other providers they charge per input/output and differentiate HD from SD in pricing each. Final price tag ended up being some $1.2/hour for on demand transcoding, and down to under $0.4 by using reservations.

Here’s the open-sourced solution, courtesy of yet another anonymous benevolent client. Some details have been altered to protect their interests.

Does it scale?

Like a charm. AWS transparently allocates transcoding resources for as much as you’d need. Note that there’s a default limit of 5 MediaLive channels and 5 inputs, which is mostly in place to prevent you (i.e. your test scripts) from creating too many by mistake and max out your bill. You can easily raise the limit via AWS Support. 

Is it fast?

It depends. And I’m talking about how fast after requesting a transcoder thread you’d get it to actually output transcoded content. And that’s 2-3 seconds if you have one in standby or 1-2 minutes if you don’t. Deciding how many to keep in standby to trade speed vs cost is the key issue here, and while you’ll be good with a fixed amount for starters, the algorithm can be later improved with “rush hour” variations or even smartly adjusted based on stats or machine learning. The coding of that is deliberately decoupled so that it can be easily improved upon. 

Is it worth it?

It has been for this project. Rather uncommonly, it only needed live transcoding to 3 SD resolutions from a HD source. May it have to also need HD outputs in the future, that will raise the MediaLive cost to $2.5-3 per hour, so still competitive as compared to Wowza Cloud at $3.5-6 or Azure Media Services at $2.5-3.5 

Note that setting up a home-grown solution can bring the price down to $.2 for CPU transcoding and $.1 for GPU. This does however require extra software, skill, maintenance and infrastructure.

Turnkey Live Streaming Platform

No External Services should be used.

A fairly simple spec:

  • allow a producer to live stream via RTMP to somewhere
  • let your subscribers see the live feed
  • record individual transmissions, and make these available as VOD
  • let your subscribers browse and watch the respective recordings

Moreover, the whole architecture was to be built on top of AWS and Elemental. No Wowza, Nimble, Nginx, virtual servers, just pure SaaS at work.

AWS Elemental streaming suite has been around for quite a while already, and for quite a while under wraps before going public. Yet there’s little word of non-enterprise solutions being deployed on top of it, little to no developer feedback, and no tips&tricks anywhere. Just the dull documentation. And even that’s lacking to the point where you need to improvise, reach out for expensive support, or run trial and errors to get it right.

Also, the client did not reveal what this is to be used for, so it had to plug into anything. And it came out like this

Fitting it with an API was the logical choice. Any integration will be puppeteering a streaming black box, no specific knowledge required.

As with other solutions, I’m thanking the anonymous client for agreeing to share this. It is here to use or build upon.

Does it scale?

Yes, viewer-wise. Unless maybe you’re broadcasting at the same time as the World Cup Final, the CDN can take millions. There’s no weak link in the chain but if you find one I’ll be glad to take AWS on it for you.

Broadcaster-wise, it’s designed for one live stream alone. You can clone the setup to make that into a handful, but if you need a dynamic number of inputs there’s a bit of extra work involved.

Is it expensive?

Mmm, kinda… Yet it might even out when you factor in the zero development/consultant cost, quick turnaround (have you deployed it already?) and zero maintenance needs.

You’ll be paying the following:

  • some $2 for each hour of live content you’re broadcasting, that covers ingesting your content, transcoding, optimization and packaging for both live and VOD delivery
  • CDN traffic at regular rates
  • S3 storage at regular rates, both the raw (archive) and processed video are kept
  • Pennies for other services

Is it stable?

Yes! It’s all a chain of services and if assembled right it’s as solid as AWS and Elemental themselves.


Is it worth it?

What do you know, it depends 🙂

If you can find your way around a virtual or dedicated server and either Wowza or Nginx-RTMP/ffmpeg then you might want to use (and maintain) that for the purpose, combined with a CDN if the case.

Still, do consider this one for short-lived implements (like one-off or yearly broadcasts) and situations where you need to guarantee for the stability of your setup.

HLS Live streaming with CDN and multiple origins

…obviously streaming and storage costs affect the budget greatly

It has been easy for a while, just pointing the CDN against your single HLS muxer (Wowza, Nimble, Flussonic, Ant, Nginx etc). More often than not it works, and it stretches to serve as many viewers any marketing can bring. But not as many broadcasters.
You know it’s a matter of time before capacity or failover needs will force you to come up with a multiple origin setup. And none of the top vendors offer a straightforward solution for it. No surprise, they’d rather lure you into using their cloud 🙂

Answering “what stream is where” is just a hash table away, yet in a global and scalable context resolving it extremely fast, over and over, is far from trivial.
Most solutions I’ve seen either use specialized edges (like this) or employ distinct CDN branches (i.e. distributions) for every origin. While the former is either expensive or comes with extra development (read extra bugs), latter is unfeasible or impossible for a fluctuating number of origins, like if you’d want to autoscale these.

The proposed solution makes use of [email protected] on top of CloudFront. The origins are customized to simply leave a note of every stream that is being broadcast to it into a database (i.e. DynamoDB), while a Lambda function at the edge level retrieves that value and, based on the result, routes HLS calls to the proper edge.

It has been deployed on a platform that hosts an ever-fluctuating number of broadcasters, with dynamics so arbitrary they’re just impossible to predict. This required an autoscale setup for the origin count, and we also wanted to separate the origin-edge logic from the main application. Architecture looks like this:

While client chose to remain unnamed, they consented to publishing the solution. Here goes.

Is it fast?

Blazing! It is substantially accelerated by CDN caching (calls to the same objects will be routed to the same origin without further resolution), explicit caching built into the Lambda function, and (possibly) DynamoDB internal caching (observe subsequent requests for the same value are faster, even from different locations).
While some HLS calls will be inherently delayed (mostly the first few), edge resolution hardly slows it down at all in the big picture.

Is it expensive?

I’ll say no but I can’t give you the figures. As Lambda acts at the ‘origin-request’ level, only a fraction of the requests will invoke it. And the explicit caching (see lambda code) makes it so only a few of the invokes actually request data from the database. All in all, expect to be paying pocket change for Lambda and DynamoDB for any audience, literally.

Is it worth it compared to other solutions?

Once again, depends on what you’re after. This particular project started off with its own set of confines, AWS/CloudFront and Wowza included.
If you’re using something other than Wowza, setting up a compatible notifier will be pretty easy.
For a CDN other than CloudFront, I don’t know if something similar to [email protected] does exist, or if there’s a way to make it equally quick.
Any (fast) database setup would work in place of the DynamoDB, however think that it needs to be globally available for the array of edges to access, so a non-SQL, AWS-hosted database will make most sense in the AWS network. An in-memory store (Redis) has been considered, but it came with just superficial increases in speed yet substantial extra cost and maintenance requirements.

Royalty-Free Low-Latency Streaming

2 second delay is fine…

We’ve witnessed HLS and MPEG-DASH streaming solutions taking over RTMP in just a few years, yet these are inherently delayed from real time due to their segmented nature. And we are talking default end-to-end lags of over 30 seconds. While for some live streaming setups a sub-minute long delay is harmless, others are compelled to reduce the latency to the very minimum. Think live auctions, gambling, or trading platforms.

To be clear, HTTP streaming and its big delays are no mistake. It leverages the ubiquity of HTTP, gives your player time to adapt to network fluctuations, doesn’t rush the muxer to output slices or the edges to cache them. It’s friendly to ABR. And it’s hugely beneficial to the CDN industry 🙂

While there are no protocol limitations when delivering to mobile apps, and you can easily stream over RTMP or RTSP, the browser is very restrictive and not at all straightforward to live stream to or from.

For quite a while, online platform implementers held on to RTMP, but as support for it eventually went away, the community had to adapt. Many of us tried pushing the HLS and DASH to its limits (shorter segments and shorter playlists), but that soon proved to be far from ideal, as playback smoothness would suffer on all but the best connections.

You’ll run into more and more companies and individuals willing and able to put together a custom low-latency solution nowadays. Moreover, the rise of HQ Trivia seems to have stimulated many to bring their approach to the the masses and offer plug-and-play solutions. You may hear stories of ground-breaking technology but really, they all fall into into one of the 3 categories:

  1. WebRTC basedWebRTC is not particularly new to the game, yet it’s still not ubiquitous, and it may still be a while before it is; providers like Twilio or Red5Pro offer easy to integrate SaaS or hosted solutions on top of it and CDNs like LimeLight are building it into their networks. If done right, you can expect sub-second latencies out of WebRTC, even across long distances and poor network connections
  2. WebSocket based – every modern browser supports WebSockets; while not trivial, a high-level protocol can be implemented on top of it and successfully stream video from server to client; at least in theory, capabilities similar to RTMP can be achieved. As WebSockets run over TCP (in turn WebRTC can use UDP) and the added protocols introduce overheads, expect a latency of 2-3 seconds out of any approach; providers like Wowza, Nanocosmos and Nimble offer solutions based on it, while CDNs like CloudFront and CloudFlare lately support WebSockets
  3. Chunked-transfer basedchunked-transfer is built into HTTP 1.1, and makes it possible for “chunks” of data to be written to, and read from, the network before the whole data is available. Provided compatible encoder, infrastructure, and decoder, this can be taken advantage of to output and playback “not-yet-complete” video segments, and significantly reduce the latency of segment-based protocols. The technique is being employed with promising results for HLS, DASH, and newly CMAF. Companies like Periscope or TheoPlayer offer proprietary solutions based on it, and a few open approaches can be found online. Chunked-transfer is supported by some CDNs. Expect a latency of under 5 seconds, it will greatly vary with the specifics of the implement.

So what’s the best of them?

There isn’t one… Client has been presented the above knowledge and options, among others. Long story short, a solution based on Nimble was chosen. They agreed to make it public but asked to remain anonymous. And here it is for you to deploy in just a few clicks.

Does it scale?

Yes, viewer-wise. It has held up to hundreds of thousands and I see no reason it can’t do more. In case of sudden spikes though, the Auto Scaling group is set to only fire up a new edge every 5 minutes so you’d want to manually intervene if you expect a riot.

Broadcaster-wise, no. As per the specs, it would only need to stream a handful of streams. Sure, there are ways to turn this into a bunch or a million.

Is it stable?

Very. It works like a charm and it’s production sound out of the box. Don’t take my word for it, try it out.

Is it worth it?

Depends on what you’re after. At the time (summer-fall 2018) Nimble’s has been the preferred option; cost, reliability, and capability to deploy on own infrastructure taken into account. Worthy competitors were Nano, Wowza and Red5Pro.

Where’s the diagram?

Here it is, sorry…