In part 1 I dove into Spotify Codes and explained the general technical concepts of how they work. If you haven’t read that post you should check it out. I shared it on reddit where it generated a lot of interesting discussion. Ludvig Strigeus, a key early developer at Spotify and the person who invented Spotify Codes, even stopped by and shared some more information on their creation and the rationale behind them!

At the end of part 1 I wrote that I wasn’t sure about some of the details, so I was not able to implement my own barcode to URI converter. Thanks to a little more digging and a lot of help from someone on Stack Overflow I can now do that conversion.

This article is going to be a little bit more technical than part 1 as I try to explain exactly how Spotify encodes their barcodes. I will include some more resources if you want to keep learning.

Encoding a URI into a Spotify Barcode

I find it easier to understand Spotify Barcodes by starting with the URI and working through the encoding process.

Media reference

A media reference is first generated by Spotify for a Spotify URI. The media reference is what gets encoded into the barcode and links the barcode to the URI. Spotify maintains a database of media reference to URI mappings. Media references let Spotify track which codes are scanned, enable them to theoretically re-map codes, and just look better when encoded. If Spotify encoded a whole URI, it would look something like this (and would be harder to scan):

Let’s start with the media reference 57639171874 which points to the following playlist: spotify:user:spotify:playlist:37i9dQZF1DWZq91oLsHZvy (Indie x Running).

The media reference can be expressed as a 37 bit binary number:

57639171874 -> 0100010011101111111100011101011010110

CRC Calculation

Next, cyclic redundancy check bits are calculated for the media reference. A CRC calculates check bits to verify the integrity of the data. (Tangent: another simple checksum algorithm we use every day to validate credit card numbers is the Luhn algorithm.)

Spotify uses CRC-8 with the following generator:

x^8 + x^2 + 1

Which gives us the following polynomial when fully written out:

1x^8 + 0x^7 + 0x^6 + 0x^5 + 0x^4 + 0x^3 + 1x^2 + 1
[1, 0, 0, 0, 0, 0, 1, 1, 1]

The CRC is calculated by following these steps:

  1. Pad with 3 bits on the right