abhijeetbhagat

abhijeetbhagat

Best way to parse bytes from a file and turn them into struct fields

I started learning Elixir day before yesterday and have already started porting my MP4 parsing library written in Python to Elixir.
I am dealing with parsing a collection of bytes from the MP4 file and converting them into struct fields. For e.g. this is how i am parsing for one of the structs -

# Movie Header Box
defmodule Mvhd do
  defstruct(
    name: :mvhd,
    creation_time: 0,
    modification_time: 0,
    timescale: 0,
    duration: 0,
    next_track_id: 0
  )
end

defimpl Box, for: Mvhd do
  def parse(_, file, _) do
    <<version::integer-32>> = IO.binread(file, 4)

    mvhd = %Mvhd{}

    mvhd =
      if version == 0 do
        <<creation_time::integer-32>> = IO.binread(file, 4)
        <<modification_time::integer-32>> = IO.binread(file, 4)
        <<timescale::integer-32>> = IO.binread(file, 4)
        <<duration::integer-32>> = IO.binread(file, 4)

        mvhd
        |> Map.put(:creation_time, creation_time)
        |> Map.put(:modification_time, modification_time)
        |> Map.put(:timescale, timescale)
        |> Map.put(:duration, duration)
      else
        <<creation_time::integer-64>> = IO.binread(file, 8)
        <<modification_time::integer-64>> = IO.binread(file, 8)
        <<timescale::integer-32>> = IO.binread(file, 4)
        <<duration::integer-64>> = IO.binread(file, 8)

        mvhd
        |> Map.put(:creation_time, creation_time)
        |> Map.put(:modification_time, modification_time)
        |> Map.put(:timescale, timescale)
        |> Map.put(:duration, duration)
      end

    :file.position(file, {:cur, 76})
    <<next_track_id::integer-32>> = IO.binread(file, 4)
    mvhd |> Map.put(:next_track_id, next_track_id)
  end
end

This is based on whatever i’ve scavenged so far on the internet and it works.
I do not want to use any third party bytes-parsing/parser-combinator libraries for now.
But i do want experienced Elixir devs to suggest a better way (if any) to rewrite the above code.
Thank you!

Marked As Solved

kip

kip

ex_cldr Core Team

The following is a little more idiomatic Elixir using pattern matching to extract the head fields based upon the version. Its for ideas only. A couple of comments:

  1. I think mp4 is big-endian so I noted that in the pattern matches
  2. Using multiple function heads that pattern match on some binary data (like version) is quite a common approach
  3. Reading a single chunk of data reduces the number of IOs and allows pattern matching on the whole header which should be more efficient
  4. According to this reference the mvhd header box version is different to integer-32-big?

→ 1 byte version = 8-bit unsigned value
- if version is 1 then date and duration values are 8 bytes in length
→ 3 bytes flags = 24-bit hex flags (current = 0)

# Movie Header Box
defmodule Mvhd do
  defstruct(
    name: :mvhd,
    creation_time: 0,
    modification_time: 0,
    timescale: 0,
    duration: 0,
    next_track_id: 0
  )

  def parse(_, file, _) do
    {creation_time, modification_time, timescale, duration, next_track} =
      extract_meta(IO.binread(file, 112))

    %__MODULE__{
      creation_time: creation_time,
      modification_time: modification_time,
      timescale: timescale,
      duration: duration,
      next_track_id: next_track
    }
  end

  def extract_meta(<<0::integer-32-big, rest::binary>>) do
    <<
      creation_time::integer-32-big,
      modification_time::integer-32-big,
      timescale::integer-32-big,
      duration::integer-32-big,
      _skip::binary-size(76),
      next_track_id::integer-32-big
    >> = rest

    {creation_time, modification_time, timescale, duration, next_track_id}
  end

  def extract_meta(<<_version::integer-32-big, rest::binary >>) do
    <<
      creation_time::integer-64-big,
      modification_time::integer-64-big,
      timescale::integer-32-big,
      duration::integer-64-big,
      _skip::binary-size(76),
      next_track_id::integer-32-big
    >> = rest

    {creation_time, modification_time, timescale, duration, next_track_id}
  end
end

Also Liked

al2o3cr

al2o3cr

defimpl Box, for: Mvhd do
  def parse(_, file, _) do
    # NOTE: consider error handling. IO.binread can return either:
    #   * less bytes than you asked for (causing a MatchError)
    #   * :eof or {:error, reason}, also a MatchError
    <<version::integer-32>> = IO.binread(file, 4)

    mvhd = %Mvhd{}

    mvhd =
      # NOTE: consider breaking these out into helper functions
      #       that pattern-match on version
      if version == 0 do
        # NOTE: consider doing a single larger read and pattern-matching
        #       all the fields in one <<>> expression
        <<creation_time::integer-32>> = IO.binread(file, 4)
        <<modification_time::integer-32>> = IO.binread(file, 4)
        <<timescale::integer-32>> = IO.binread(file, 4)
        <<duration::integer-32>> = IO.binread(file, 4)

        # NOTE: consider either a struct literal or record update syntax here
        #       instead of Map.put
        mvhd
        |> Map.put(:creation_time, creation_time)
        |> Map.put(:modification_time, modification_time)
        |> Map.put(:timescale, timescale)
        |> Map.put(:duration, duration)
      else
        <<creation_time::integer-64>> = IO.binread(file, 8)
        <<modification_time::integer-64>> = IO.binread(file, 8)
        <<timescale::integer-32>> = IO.binread(file, 4)
        <<duration::integer-64>> = IO.binread(file, 8)

        mvhd
        |> Map.put(:creation_time, creation_time)
        |> Map.put(:modification_time, modification_time)
        |> Map.put(:timescale, timescale)
        |> Map.put(:duration, duration)
      end

    :file.position(file, {:cur, 76})
    <<next_track_id::integer-32>> = IO.binread(file, 4)
    mvhd |> Map.put(:next_track_id, next_track_id)
  end
end

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New

We're in Beta

About us Mission Statement