Class: FormatParser::MOOVParser

Inherits:
Object
  • Object
show all
Includes:
IOUtils
Defined in:
lib/parsers/moov_parser.rb

Defined Under Namespace

Classes: Decoder

Constant Summary collapse

FTYP_MAP =

Maps values of the “ftyp” atom to something we can reasonably call “file type” (something usable as a filename extension)

{
  'qt  ' => :mov,
  'mp4 ' => :mp4,
  'm4a ' => :m4a,
}

Instance Method Summary collapse

Methods included from IOUtils

#safe_read, #safe_skip

Instance Method Details

#call(io) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/parsers/moov_parser.rb', line 14

def call(io)
  return unless matches_moov_definition?(io)

  # Now we know we are in a MOOV, so go back and parse out the atom structure.
  # Parsing out the atoms does not read their contents - at least it doesn't
  # for the atoms we consider opaque (one of which is the "mdat" atom which
  # will be the prevalent part of the file body). We do not parse these huge
  # atoms - we skip over them and note where they are located.
  io.seek(0)

  # We have to tell the parser how far we are willing to go within the stream.
  # Knowing that we will bail out early anyway we will permit a large read. The
  # branch parse calls will know the maximum size to read from the parent atom
  # size that gets parsed just before.
  max_read_offset = 0xFFFFFFFF
  decoder = Decoder.new
  atom_tree = decoder.extract_atom_stream(io, max_read_offset)

  ftyp_atom = decoder.find_first_atom_by_path(atom_tree, 'ftyp')
  file_type = ftyp_atom.field_value(:major_brand)

  width = nil
  height = nil

  # Try to find the width and height in the tkhd
  if tkhd = decoder.find_first_atom_by_path(atom_tree, 'moov', 'trak', 'tkhd')
    width = tkhd.field_value(:track_width).first
    height = tkhd.field_value(:track_height).first
  end

  # Try to find the "topmost" duration (respecting edits)
  if mdhd = decoder.find_first_atom_by_path(atom_tree, 'moov', 'mvhd')
    timescale = mdhd.field_value(:tscale)
    duration = mdhd.field_value(:duration)
    media_duration_s = duration / timescale.to_f
  end

  # M4A only contains audio, while MP4 and friends can contain video.
  if format_from_moov_type(file_type) == :m4a
    FormatParser::Audio.new(
      format: format_from_moov_type(file_type),
      media_duration_seconds: media_duration_s,
      intrinsics: atom_tree,
    )
  else
    FormatParser::Video.new(
      format: format_from_moov_type(file_type),
      width_px: width,
      height_px: height,
      media_duration_seconds: media_duration_s,
      intrinsics: atom_tree,
    )
  end
end