Streaming a teacher's screen to a classroom of phones
Pinchview is a side project I built for teaching. The teacher shares their screen, students open a link on their phones, pinch to zoom into the code, and the teacher gets an attendance report at the end. The interesting part is how little of it Django does, and how that small part still controls who can watch.
1Video never goes through Django
A Python process is the wrong place to push live video to a room of phones. The video goes through MediaMTX, a media server that takes the teacher's stream over WebRTC and serves it again as WebRTC and as HLS. nginx sits in front of everything. Django only answers small JSON requests:
teacher browser ── WebRTC ──▶ nginx ──▶ MediaMTX
student phone ◀── video ─── nginx ◀── MediaMTX
│
└── "may this phone watch?" ──▶ Django
The last line is nginx's auth_request. Before nginx passes a video request on, it makes a small request of its own to Django. A 2xx answer lets the video through; a 401 or 403 stops it:
location /hls/ {
auth_request /__media_auth;
proxy_pass http://127.0.0.1:8888/;
}
location = /__media_auth {
internal; # only nginx can call this
proxy_pass http://127.0.0.1:8031/api/media-auth/;
proxy_pass_request_body off;
proxy_set_header X-Original-URI $request_uri;
}
On the Django side the view reads the room from the original URL and checks the phone's cookie. It never touches the video, so it's fast, and it runs for every playlist and every segment request:
ROOM_IN_URI = re.compile(r"^/(?:webrtc|hls)/([^/?]+)/")
def media_auth(request):
match = ROOM_IN_URI.match(request.META.get("HTTP_X_ORIGINAL_URI", ""))
if not match:
return HttpResponse(status=403)
lesson = active_lesson(match.group(1))
allowed = seat_from_cookie(request, lesson)
return HttpResponse(status=204 if allowed else 403)
/api/media-auth/ returns 404. Only the internal location can reach it, so nobody can probe it from outside.2Checking in from the class list
Students don't have accounts. They open the link, pick their name from the class list, and that's it. The list is a plain JSON file, one list of names per group, so there's no sign-up and nothing new to maintain. A name that isn't on the list gets "Ask your teacher."
A successful check-in creates a Seat for this lesson with a random token, and puts the token in a cookie:
seat = Seat.objects.create(
lesson=lesson, name=canonical, token=secrets.token_urlsafe(24), ...
)
res.set_cookie(COOKIE, seat.token, max_age=12 * 3600,
httponly=True, samesite="Lax", secure=...)
The cookie is the whole permission. Video requests carry it automatically, so the auth_request check above just looks up the seat. A shared link alone shows nothing: someone outside the class gets a name picker they can't use.
3Attendance from heartbeats
Every 15 seconds the viewer page sends a heartbeat. It also reports how long the page was really on screen, using the visibilitychange event. A phone with the lesson open behind a game counts as "open", not "watching".
On the server, heartbeats become visits. If a phone goes quiet for more than 60 seconds, the student left; the next heartbeat starts a new visit:
def record_presence(seat, visible_secs):
now = timezone.now()
with transaction.atomic():
visit = seat.visits.order_by("-last_seen").first()
if not visit or (now - visit.last_seen).total_seconds() > GAP_SECS:
Visit.objects.create(seat=seat, started=now, last_seen=now)
return
elapsed = (now - visit.last_seen).total_seconds()
visit.visible_secs += max(0.0, min(visible_secs, elapsed + 5))
visit.last_seen = now
visit.save(update_fields=["visible_secs", "last_seen"])
Note the min(visible_secs, elapsed + 5). The phone reports its own on-screen time, and the server never trusts it for more than the time that really passed. A modified page can't claim an hour of watching in one heartbeat.
The report then gives each student minutes open, minutes on screen, how many times they rejoined, and how many devices they used. The teacher can download it as CSV.
4WebRTC first, HLS when it doesn't work
WebRTC gives under a second of delay, which feels live. But on some mobile networks it never connects. HLS works almost everywhere, through plain HTTP, but it's several seconds behind.
So the player tries WebRTC first. If no frame arrives within 6 seconds, it switches to HLS and stays there; students can tap "faster" to try WebRTC again. A 404 ("the teacher isn't sharing yet") doesn't count as a WebRTC failure, it only means wait and retry.
HLS has one more problem for screen sharing: after every stall the player falls further behind and never catches up on its own. If it's more than 8 seconds behind the live edge, the player jumps to 4 seconds behind. For a lesson, skipping ahead is right. Students should see the current screen, not the slide from a minute ago.
5Small things that mattered
- Teacher pages use nginx basic auth, not Django logins. One password, one place. The teacher API sits behind the same password.
- Basic auth needs CSRF protection too. The browser sends the saved password with any request, even one started by another website. Teacher endpoints accept only POST with a JSON body. A browser won't send that cross-site without asking the server first, so another page can't press "end lesson".
- nginx picks the first matching regex location. The rule that protects
teacher.htmlhas to stay above the general\.html$rule, or the page is public. There's a comment in the config saying so. - The whole Django app is one file. Settings, three models, views and URLs in a single
app.py, run by gunicorn. For a service this size, that's easier to read and deploy than a full project.
The takeaway
Let each piece do what it's good at. The media server moves video, nginx handles TLS, passwords and routing, and Django answers the questions that need data: who is in this class, may this phone watch, and how long were they really there.
More writing
I’m Aysulu, a backend developer (Python, Django) in Nukus, Uzbekistan, open to remote work. If your team deals with this kind of thing, I’d like to hear about it: aysulu.mambetnazarova@gmail.com. Or see my projects.