1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Helpers.QtFastStart do
7 (WIP) Converts a "slow start" (data before metadatas) mov/mp4 file to a "fast start" one (metadatas before data).
10 # TODO: Cleanup and optimizations
11 # Inspirations: https://www.ffmpeg.org/doxygen/3.4/qt-faststart_8c_source.html
12 # https://github.com/danielgtaylor/qtfaststart/blob/master/qtfaststart/processor.py
13 # ISO/IEC 14496-12:2015, ISO/IEC 15444-12:2015
16 def fix(<<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70, _::bits>> = binary) do
17 index = fix(binary, 0, nil, nil, [])
21 [{"ftyp", _, _, _, _}, {"mdat", _, _, _, _} | _] -> faststart(index)
22 [{"ftyp", _, _, _, _}, {"free", _, _, _, _}, {"mdat", _, _, _, _} | _] -> faststart(index)
31 # MOOV have been seen before MDAT- abort
32 defp fix(<<_::bits>>, _, true, false, _) do
37 <<size::integer-big-size(32), fourcc::bits-size(32), rest::bits>>,
43 full_size = (size - 8) * 8
44 <<data::bits-size(full_size), rest::bits>> = rest
47 {fourcc, pos, pos + size, size,
48 <<size::integer-big-size(32), fourcc::bits-size(32), data::bits>>}
52 fix(rest, pos + size, got_moov || fourcc == "moov", got_mdat || fourcc == "mdat", acc)
55 defp fix(<<>>, _pos, _, _, acc) do
59 defp faststart(index) do
60 {{_ftyp, _, _, _, ftyp}, index} = List.keytake(index, "ftyp", 0)
62 # Skip re-writing the free fourcc as it's kind of useless.
63 # Why stream useless bytes when you can do without?
65 case List.keytake(index, "free", 0) do
66 {{_, _, _, size, _}, index} -> {size, index}
70 {{_moov, _, _, moov_size, moov}, index} = List.keytake(index, "moov", 0)
71 offset = -free_size + moov_size
72 rest = for {_, _, _, _, data} <- index, do: data, into: []
73 <<moov_head::bits-size(64), moov_data::bits>> = moov
74 [ftyp, moov_head, fix_moov(moov_data, offset, []), rest]
78 <<size::integer-big-size(32), fourcc::bits-size(32), rest::bits>>,
82 full_size = (size - 8) * 8
83 <<data::bits-size(full_size), rest::bits>> = rest
87 fourcc in ["trak", "mdia", "minf", "stbl"] ->
88 # Theses contains sto or co64 part
89 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, fix_moov(data, offset, [])]
91 fourcc in ["stco", "co64"] ->
93 <<version::integer-big-size(32), count::integer-big-size(32), rest::bits>> = data
102 <<size::integer-big-size(32), fourcc::bits-size(32), version::integer-big-size(32),
103 count::integer-big-size(32)>>,
104 rewrite_entries(entry_size, offset, rest, [])
108 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, data]
112 fix_moov(rest, offset, acc)
115 defp fix_moov(<<>>, _, acc), do: acc
117 for size <- [32, 64] do
118 defp rewrite_entries(
121 <<pos::integer-big-size(unquote(size)), rest::bits>>,
124 rewrite_entries(unquote(size), offset, rest, [
125 acc | <<pos + offset::integer-big-size(unquote(size))>>
130 defp rewrite_entries(_, _, <<>>, acc), do: acc