A Teleprompter in a Telegram Mini App: Canvas Video Recording, Chunked FastAPI Uploads, and Three iPhone and WebView TrapsArticle · digest for December 1
First-person shot: a developer's hands hold a smartphone vertically with a teleprompter and 9:16 recording frame above a desk with a laptop.
Article5 sections≈ 10 min

A Teleprompter in a Telegram Mini App: Canvas Video Recording, Chunked FastAPI Uploads, and Three iPhone and WebView Traps

When you build browser video recording on a laptop, everything feels easy. The camera gives a clean frame, MediaRecorder captures the stream, the file uploads to the server, and your prototype works in one evening. Then you open the same app inside Telegram on an iPhone: first the video gets squished, then the front camera zooms 3x into your face, and after you deploy a fix, the WebView keeps running the old script.

That's exactly what happened to developer Emil Mukhametzyanov when he built a web teleprompter for vertical clips in early November. Text scrolls under the lens, speed adjusts on the fly, a tap pauses scrolling, and the finished .mp4 lands in your bot chat. The first commit went in late on November 2, and the next two weeks went into mobile bugs that are completely invisible on a Mac.

Why Record Through Canvas and Fit Under 50 MB

The teleprompter shares one codebase for the regular website and the Telegram Mini App. On the server, a single FastAPI process serves static files, runs the API, and polls the bot. On the website, the video stays on the device and downloads locally from a Blob; in Telegram, it uploads straight to the server.

Reels require a strict 1080×1920 format, while cameras output whatever aspect ratio they please. So each <video> frame is redrawn onto a <canvas> with a centered 9:16 cover crop, captured via canvas.captureStream() (turning the canvas into a standard MediaStream), paired with the audio track, and passed to MediaRecorder.

function makeRecordStream() {
  const video = $('preview');
  const canvas = document.createElement('canvas');
  canvas.width = 1080;
  canvas.height = 1920;
  const ctx = canvas.getContext('2d');
  let frame;
  const paint = () => {
    const { videoWidth: w, videoHeight: h } = video;
    if (w && h) {
      const s = Math.max(canvas.width / w, canvas.height / h);
      const cw = canvas.width / s, ch = canvas.height / s;
      ctx.drawImage(
        video, (w - cw) / 2, (h - ch) / 2, cw, ch,
        0, 0, canvas.width, canvas.height
      );
    }
    frame = requestAnimationFrame(paint);
  };
  paint();
  // Capture the canvas stream at 30 fps and attach the audio track
  const res = canvas.captureStream(30);
  for (const t of stream.getAudioTracks()) res.addTrack(t);
  return { stream: res, stop: () => cancelAnimationFrame(frame) };
}

const type = [
  'video/mp4;codecs=avc1,mp4a', 'video/mp4',
  'video/webm;codecs=vp9,opus', 'video/webm',
].find((v) => MediaRecorder.isTypeSupported(v));

// 4 Mbps to fit the 50 MB limit; 1000 ms timeslice emits a chunk every second
recorder = new MediaRecorder(recording.stream, {
  mimeType: type, videoBitsPerSecond: 4_000_000,
});
recorder.ondataavailable = ({ data }) => {
  if (!data.size) return;
  chunks.push(data);
  sending?.add(data);
};
recorder.start(1000);

The bitrate started at 6 Mbps, then dropped to 4 Mbps on November 4. The cloud Telegram Bot API (sendVideo) rejects files over 50 MB (larger uploads require your own Local Bot API Server). At 4 Mbps, about 90 seconds fit under the cap; if a clip runs longer, the app returns a temporary one-hour download link.

Trap One: Why iPhone Squished the Portrait Frame

The first makeRecordStream() from November 2 relied on track.getSettings(). If height was greater than or equal to width, it passed the stream through; if width was larger, it cropped the center to 9:16.

Everything worked cleanly on a Mac, while early iPhone tests came back squished. In portrait mode, iPhone feeds a vertical picture into <video>, yet track.getSettings() reports the sensor's landscape dimensions (width > height). The code thought the frame was wide, calculated a left offset from a nonexistent width, and grabbed a slice past the edge — which Safari stretched. On November 3, the track.getSettings() check was removed in favor of the actual videoWidth and videoHeight on <video>.

Chunked Upload During Recording, os.truncate, and FFmpeg Audio

When the app uploaded the whole video after clicking Stop via XHR (fetch has no upload progress), mobile connections left users staring at percentage bars. On November 10, recording switched to recorder.start(1000): every second, the browser emits a Blob chunk of one continuous container. A 12-second clip became ready roughly 3 seconds after stopping.

Pen sketch of the chunked video upload flow on FastAPI: stream fragments from the phone, truncating broken tails with os.truncate, and remuxing audio to AAC via FFmpeg.

The FastAPI protocol uses four endpoints: POST /api/upload opens a session, PUT /api/upload/{id}/{index} appends a chunk, POST /api/upload/{id}/done triggers assembly, and DELETE /api/upload/{id} cancels a duplicate. The main hazard on mobile networks is a drop mid-chunk, leaving a corrupted tail in the file.

@app.put("/api/upload/{upload_id}/{index}")
async def upload_chunk(
    upload_id: str, index: int, request: Request,
    x_auth: str | None = Header(None),
) -> dict:
    upload = own_upload(upload_id, await current_user(x_auth))
    # Retry of an already received chunk: return OK without duplicating
    if index < upload["next"]:
        return {"ok": True}
    if index > upload["next"]:
        raise HTTPException(409, "Skipped chunk")
    try:
        upload["size"] = await append_body(
            request, upload["raw"], upload["size"]
        )
    except BaseException:
        # Dropped mid-chunk: truncate the partial tail back to last clean size
        if upload["raw"].exists():
            os.truncate(upload["raw"], upload["size"])
        raise
    upload["next"] += 1
    upload["touched"] = time.time()
    return {"ok": True}

If a client misses the response due to lag and resends index < next, the server returns 200 OK without duplicating bytes. If a write drops mid-stream, os.truncate rolls the file back to the last complete size. This path even has a pytest test: a real FFmpeg mp4 is split into three parts, and the middle chunk is sent twice.

On the phone, chunks upload sequentially with 3 attempts each (only on 5xx and network errors, waiting 1000 * (attempt + 1) ms). If a chunk fails, the uploader sets broken = true, and after Stop the app falls back to sending the full Blob saved in chunks to /api/video. ETA estimates use a moving average of chunks over 50 KB, while a background task sweeps abandoned uploads and finished videos older than an hour every 5 minutes.

After /done, the bot posts '⏳ Building video' and the server runs the file through FFmpeg in the background:

async def remux(src: Path, dst: Path, webm: bool) -> None:
    # Copy video from mp4; re-encode webm completely
    video = (
        ["-c:v", "libx264", "-preset", "veryfast", "-crf", "21"]
        if webm else ["-c:v", "copy"]
    )
    # Always convert audio to AAC: Chrome puts Opus inside mp4
    codec = [*video, "-c:a", "aac", "-b:a", "160k"]

Chrome often packs Opus audio inside mp4, which many platforms reject, so audio always converts to AAC at 160 kbps. Meanwhile, mp4 video simply remuxes (-c:v copy): estimated assembly time is 0.05 s/MB versus 1.2 s/MB for webm — 24x faster.

Trap Two: Why the Front Camera Zoomed 3x Into Faces

November 12 brought a new surprise: the iPhone frame was no longer squished, but the front camera zoomed roughly 3x into the speaker's face. Once again, the culprit was the landscape sensor — this time inside getUserMedia(). iPhone interpreted a 1080×1920 request in sensor coordinates, cropped a narrow strip, and then the <canvas> cover crop cut the frame a second time.

// Request iPhone's landscape sensor size instead of 1080x1920:
// the camera delivers a wide angle and rotates the image to portrait
const stream = await navigator.mediaDevices.getUserMedia({
  audio: true,
  video: {
    facingMode: 'user',
    width: { ideal: 1920 },
    height: { ideal: 1080 },
    frameRate: { ideal: 30 },
  },
});

That single edit restored the normal field of view. On a Mac, both versions look identical because webcams adapt ideal to their wide modes — without a real iPhone, you'd never catch this bug.

Trap Three: Why Telegram WebView Kept Serving Old app.js

The camera fix shipped on November 12 at 12:55, yet opening the Mini App still showed a huge face. Six minutes later, a version query string was added to the script tag in index.html (first the commit hash c918bbd, later safari-link-1):

<!-- Version in the URL forces Telegram WebView to fetch the fresh module -->
<script type="module" src="app.js?v=safari-link-1"></script>

Static files are served by StaticFiles in FastAPI via Starlette's FileResponse: it sets ETag and Last-Modified, but omits Cache-Control. Without it, Telegram's WebView heuristically treats app.js as fresh and skips the network. index.html, however, revalidates, sees the new URL, and fetches the updated script.

iPhone & WebView IssueCauseFix
Squished portrait frametrack.getSettings() returns landscape sensor dimensions; crop went past the edgeRead video.videoWidth / video.videoHeight for a unified 9:16 cover crop
3x face zoom on front cameraRequesting 1080×1920 in getUserMedia() made the sensor crop a narrow stripRequest landscape 1920×1080 in sensor coordinates
Stale app.js after deployFastAPI StaticFiles omits Cache-Control; WebView skips revalidationVersion the URL (app.js?v=...) in index.html
Where Weak Spots Remain in This Setup

A manual ?v= is easy to forget on deploy, and ./match.js and style.css have no version query at all: in production, it's safer to inject content hashes at build time or subclass StaticFiles with an explicit Cache-Control. Keeping all chunks in memory as a fallback works for 1–2 minute clips, but longer recordings will eat mobile WebView RAM. Finally, voice-synced scrolling via the Web Speech API has only been tested in Chrome on Mac, not inside Telegram on iPhone.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 9