Module: MP4::Metadata::Memoize::Stbl::Samples

Defined in:
lib/mp4/metadata/memoize/stbl/samples.rb

Class Method Summary collapse

Class Method Details

.call(track_id, cache, stsc, stco, stss, stts, ctts, stsz) ⇒ Object



7
8
9
10
11
12
13
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
# File 'lib/mp4/metadata/memoize/stbl/samples.rb', line 7

def call(track_id, cache, stsc, stco, stss, stts, ctts, stsz)
  sample_sizes = expand_stsz(stsz)
  track_timescale = cache.track(track_id).fetch('timescale').to_i
  stsc_calculator = SampleToChunkCalculator.new(stsc.table, stco.offsets.size)
  ctts_calculator = CompositionOffsetCalculator.new(ctts&.entries_list)
  delta_calculator = DeltaCalculator.new(stts.time_to_sample)

  delta_sum_counter = 0
  sample_offset_counter = 0
  prev_sample_size = 0
  prev_chunk_index = 0

  cache.transaction do
    stsz.sample_count.times do |index|
      sample_index = index.next
      sample_delta = delta_calculator.find_delta(sample_index)

      chunk_index = stsc_calculator.find_chunk_number(sample_index)

      chunk_offset = stco.offsets.fetch(chunk_index - 1)
      is_keyframe = stss&.sync_sample&.include?(sample_index) ? 'TRUE' : 'FALSE'

      if prev_chunk_index.zero? || prev_chunk_index != chunk_index
        sample_offset_counter = chunk_offset
      else
        sample_offset_counter += prev_sample_size
      end

      prev_sample_size = sample_sizes[index].to_i

      cache.add_sample(
        track_id: track_id.to_i,
        chunk_index: chunk_index.to_i,
        sample_index: sample_index.to_i,
        sample_size: sample_sizes[index].to_i,
        sample_offset: sample_offset_counter,
        chunk_offset: chunk_offset,
        original_chunk_offset: chunk_offset,
        sample_delta: sample_delta.to_i,
        delta_sum: delta_sum_counter,
        absolute_delta_sum: (delta_sum_counter.to_f / track_timescale * 1000.0).ceil,
        composition_offset: ctts_calculator.find_composition_offset(sample_index),
        is_keyframe: is_keyframe,
      )

      delta_sum_counter += sample_delta
      prev_chunk_index = chunk_index
    end
  end
end

.expand_stsz(stsz) ⇒ Object



58
59
60
61
62
# File 'lib/mp4/metadata/memoize/stbl/samples.rb', line 58

def expand_stsz(stsz)
  return Hash.new(stsz.sample_size) if stsz.sample_size.to_i.nonzero?

  stsz.sample_sizes
end

.fetch_composition_offset_by_sample_index(ctts, sample_number) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/mp4/metadata/memoize/stbl/samples.rb', line 64

def fetch_composition_offset_by_sample_index(ctts, sample_number)
  return nil if ctts.nil?

  total_samples = 0

  ctts.entries_list.each do |entry|
    total_samples += entry.sample_count

    return entry.fetch(:composition_offset) if total_samples >= sample_number
  end

  raise "Sample Composition offset not found for sample index: #{sample_index}"
end