Video Streaming with Kotlin and Javalin

Introduction

Recently there was a need to have some videos in a centralized place so a few of my friends could stream them from the comfort of their own homes. It also avoids everyone having to download the file and figuring out the best way to share multi-GB files with everyone.

I have another post that talks about building a jukebox via Vert.x - this will be similar but for video files using Javalin.

Infrastructure

The app is an http server that can be deployed to any server. I chose to run it as a jar on a $6 DigitalOcean droplet and the performance was great even for multiple people watching concurrently.

The video files themselves were uploaded to /media/<file-name>.mp4

Code

The code is very simple - Javalin provides a great way to use seek-able streams combined with the fact that modern browsers can run videos natively means we can have the file play directly in the browser without needing to write any frontend code.

1
2
3
4
5
6
7
8
val app = Javalin.create { it.enableDevLogging() }

app.get("/episode/{epnum}") {
val file = File("/media/${it.pathParam("epnum")}.mp4")
it.seekableStream(file.inputStream(), "video/mp4")
}

app.start(7000)

Now if we navigate to http://localhost:7000/episode/1 it will play the file /media/1.mp4. If the file does not exist it returns a 500 internal server error.

Conclusion

It is elegance like this why I like Kotlin and Javalin so much. I can get work done instead of just always chasing the next error.