Rtransat

Rtransat

How to read id3v2 tags from mp3 files?

Hi, I’m new with Elixir and for learning I try to read id3v2 tags from mp3 files. The stdlib for working with binary seems awesome with pattern matching.
I have question about how to parse some data (title, artist, etc)
By following the spec it seems to have a flag with encodage information but I don’t know how to read it. I think I have utf16 for the title (TIT2) because I have some bytes to 0.

My current code:

file = File.stream!("./lib/file.mp3", [:read, :binary], 128)
id3tag_bytes = file |> Enum.take(1) |> hd

<<header::binary-size(10), rest::binary>> = id3tag_bytes

<<"ID3", major::binary-size(1), revision::binary-size(1), flags::binary-size(1),
  size::binary-size(4)>> =
  header

case flags do
  <<0>> -> IO.puts("No extended header")
  _ -> IO.puts("Extended header")
end

<<frame_overview::binary-size(10), frame::binary>> = rest

<<frame_id::binary-size(4), frame_size::binary-size(4), frame_flags::binary-size(2)>> =
  frame_overview

<<frame_size_int::size(4)-unit(8)>> = frame_size
IO.inspect(frame_size_int, label: "Frame Size")
<<title::binary-size(frame_size_int - 10), _rest::binary>> = frame

# id3 = <<header::binary-size(3), _v::binary-size(1), _flags::binary-size(1), _size::binary-size(4)>>

IO.inspect(header, label: "Header")
IO.inspect(:binary.decode_unsigned(major), label: "Version")
IO.inspect(:binary.decode_unsigned(revision), label: "Revision")
IO.inspect(:binary.decode_unsigned(flags), label: "Flags")
IO.inspect(frame_id, label: "Frame ID")
IO.inspect(:binary.decode_unsigned(frame_size), label: "Frame Size")
IO.inspect(size, label: "Size")
IO.inspect(frame_overview, label: "Frame Overview")
IO.inspect(title, label: "Title")
IO.inspect(title |> :unicode.characters_to_binary(:utf16, :utf8), label: "Title")

You can find the first 100 bytes from the file: id3tag_bytes

<<73, 68, 51, 3, 0, 0, 0, 4, 109, 110, 84, 73, 84, 50, 0, 0, 0, 19, 0, 0, 1,
  255, 254, 76, 0, 97, 0, 32, 0, 81, 0, 117, 0, 234, 0, 116, 0, 101, 0, 84, 80,
  69, 49, 0, 0, 0, 17, 0, 0, 1, 255, 254, 79, 0, 114, 0, 101, 0, 108, 0, 115, 0,
  97, 0, 110, 0, 84, 65, 76, 66, 0, 0, 0, 57, 0, 0, 1, 255, 254, 67, 0, 105, 0,
  118, 0, 105, 0, 108, 0, 105, 0, 115, 0, 97, 0, 116, 0, 105, 0, 111>>

The title in TIT2 frame should be “La Quête” which can be found here: <<76, 0, 97, 0, 32, 0, 81, 0, 117, 0, 234, 0, 116, 0, 101>> but like I said previously there are some bytes to 0 so I guess it’s encoded in utf16 and the tag is readable without the bytes 0.
<<76, 97, 32, 81, 117, 234::utf8, 116, 101>>

The frame size is 19 in header but we need to remove the header size so 19 - 10 = 9 so I think I need to convert utf16 to uf8 before reading the title, otherwise the size of my title is not the same.

Currently, the last IO.inspect print {:incomplete, "ǿ﹌a ", <<0>>}

Thx :wink:

Marked As Solved

kip

kip

ex_cldr Core Team

Here’s my final experiment in case its useful to you:

defmodule MP3 do
  def extract_tags(<<>>) do
    []
  end

  def extract_tags(<<0, _rest::binary>>) do
    []
  end

  def extract_tags(<<"ID3", _major::binary-size(1), _revision::binary-size(1), _flags::binary-size(1), _size::integer-size(32), rest::binary>>) do
    extract_tags(rest)
  end
  
  def extract_tags(data) do
    <<frame_overview::binary-size(10), frame::binary>> = data
    <<frame_id::binary-size(4), frame_payload_size::unsigned-integer-32, _frame_flags::binary-size(2)>> = frame_overview
    <<frame_payload::binary-size(frame_payload_size), rest::binary>> = frame

    {text, encoding} =
      case frame_payload do
        <<1, 0xff, 0xfe, text::binary>> -> {text, {:utf16, :little}}
        <<1, 0xfe, 0xff, text::binary>> -> {text, {:utf16, :big}}
        <<0, text::binary>> -> {text, :iso8859}  
      end
    
    frame_text =
      case encoding do
        :iso8859 -> :iconv.convert("iso8859-1", "utf8", text)
        encoding -> :unicode.characters_to_binary(text, encoding, :utf8)
      end

    [{frame_id, frame_text} | extract_tags(rest)]
  end
end

Example

iex> id3tag_bytes = File.read!("../Hells Bells.mp3")
iex> MP3.extract_tags(id3tag_bytes)
[
  {"TPE1", "AC/DC"},
  {"TYER", "1980"},
  {"TALB", "Back In Black"},
  {"TRCK", "01"},
  {"TIT2", "Hells Bells"}
]

Also Liked

kip

kip

ex_cldr Core Team

The following script is proof-of-concept you might find useful:

<<header::binary-size(10), rest::binary>> = id3tag_bytes
<<"ID3", major::binary-size(1), revision::binary-size(1), flags::binary-size(1), size::integer-size(32)>> = header
<<frame_overview::binary-size(10), frame::binary>> = rest
<<frame_id::binary-size(4), frame_size::unsigned-integer-32, frame_flags::binary-size(2)>> = frame_overview

frame_payload_size = frame_size
frame_payload = <<frame::binary-size(frame_payload_size)>>

{title, encoding} =
  case frame_payload do
    <<1, 0xff, 0xfe, title::binary>> -> {title, {:utf16, :little}}
    <<1, 0xfe, 0xff, title::binary>> -> {title, {:utf16, :big}}
    <<0, title::binary>> -> {title, :iso8859}  
  end

case encoding do
  :iso8859 -> :iconv.convert("iso8859-1", "utf8", title)
  encoding -> :unicode.characters_to_binary(title, encoding, :utf8)
end
kip

kip

ex_cldr Core Team

Welcome to the Elixir community!

If we look at what the encoding of the expected title is we can see its probably UTF16-LE since its a true subset of the frame payload:

iex> :iconv.convert("utf8", "utf16le", title)
<<76, 0, 97, 0, 32, 0, 81, 0, 117, 0, 234, 0, 116, 0, 101, 0>>

So now we know what we are looking for, we can examine the actual frame content, which appears to be:

iex> <<header::binary-size(10), rest::binary>> = id3tag_bytes
iex> <<"ID3", major::binary-size(1), revision::binary-size(1), flags::binary-size(1), size::binary-size(4)>> = header
iex> <<frame_overview::binary-size(10), frame::binary>> = rest
iex> <<frame_id::binary-size(4), frame_payload_size::unsigned-integer-32, frame_flags::binary-size(2)>> = frame_overview
iex> frame_payload = <<frame::binary-size(frame_payload_size)>>
iex> <<encoding::unsigned-integer-8, payload::binary>> = frame_payload
  
iex> IO.inspect(frame_payload_size, label: "Frame Payload Size")
Frame Payload Size: 19
iex> IO.inspect encoding, label: "Payload encoding (0 == ISO8859, 1 == UTF16)"
Payload encoding (0 == ISO8859, 1 == UTF16): 1
iex> IO.inspect payload, label: "Frame payload"
Frame payload: <<255, 254, 76, 0, 97, 0, 32, 0, 81, 0, 117, 0, 234, 0, 116, 0, 101, 0>>

Observations of the frame payload

  1. <<255, 254>> is the BOM indicating UTF16 little endian.
  2. The rest of the data is the actual string which we can decode with the following. Note that we don’t include the BOM, but we do use it to determine the endianness for conversion:
iex> title = <<76, 0, 97, 0, 32, 0, 81, 0, 117, 0, 234, 0, 116, 0, 101, 0>>
iex> :unicode.characters_to_binary(title, {:utf16, :little}, :utf8)
"La Quête"

Note that :unicode.characters_to_binary/3 does not detect endianness from a BOM, so the BOM needs to be excluded. :iconv.convert/3 has the same consideration.

Possible next steps

  1. For ISO-8859-1 conversion you may need to include :iconv as a dependency.
kip

kip

ex_cldr Core Team

IO.read and File.read return different types. chardata() is not the same as binary()

IO.read/2
@spec read(device(), :eof | :line | non_neg_integer()) :: chardata() | nodata()

File.read/1
@spec read(Path.t()) :: {:ok, binary()} | {:error, posix()}

In your case, I think I would just be doing:

case File.read(path) do
  {:ok, binary} -> extract_tags(binary)
  error -> error
end

Also note that I edited the case clause for :iso8859 to correctly binary pattern match.

cevado

cevado

doesn’t this solve it?

Where Next?

Popular in Questions Top

freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement