Daniel Dinca
Daniel Dinca

Reputation: 43

YouTube Video ID Algorithm

How can I create Videos IDs with javascript? I want to make a website that gives user random videos, but at the same time for me, I want to learn what is the YouTube Video ID algorithm

Upvotes: 1

Views: 1012

Answers (1)

bryc
bryc

Reputation: 15026

The process is straight forward when laid out this way:

  1. Generate random unsigned 64-bit ID number
  2. Check if ID already exists; if so, repeat (1)
  3. Generate Base64 string of ID, by splitting into 8-bit chunks
  4. Replace / with -. Replace + with _. Delete = if present

Keep in mind this method will almost always lead to a nonexistent YT video. There's just too many combinations, that YT will never run out. Here's a simple JS implementation:

function yt_rand_id() {
let chars2replace = {'/': '-', '+': '_', '=': ''};
let random_bytes = new Uint8Array(8).map(() => Math.floor(Math.random() * 256))
let base64_hash = btoa(String.fromCharCode.apply(0, random_bytes));
base64_hash = base64_hash.replace(/[/+=]/g, match => chars2replace[match]);
return base64_hash;
}

console.log(yt_rand_id(), yt_rand_id(), yt_rand_id(), yt_rand_id());

Hope this helped someone.

Upvotes: 2

Related Questions