1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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>>,
44 full_size = (size - 8) * 8
45 <<data::bits-size(full_size), rest::bits>> = rest
48 {fourcc, pos, pos + size, size,
49 <<size::integer-big-size(32), fourcc::bits-size(32), data::bits>>}
53 fix(rest, pos + size, got_moov || fourcc == "moov", got_mdat || fourcc == "mdat", acc)
60 defp fix(<<>>, _pos, _, _, acc) do
64 defp faststart(index) do
65 {{_ftyp, _, _, _, ftyp}, index} = List.keytake(index, "ftyp", 0)
67 # Skip re-writing the free fourcc as it's kind of useless.
68 # Why stream useless bytes when you can do without?
70 case List.keytake(index, "free", 0) do
71 {{_, _, _, size, _}, index} -> {size, index}
75 {{_moov, _, _, moov_size, moov}, index} = List.keytake(index, "moov", 0)
76 offset = -free_size + moov_size
77 rest = for {_, _, _, _, data} <- index, do: data, into: []
78 <<moov_head::bits-size(64), moov_data::bits>> = moov
79 [ftyp, moov_head, fix_moov(moov_data, offset, []), rest]
83 <<size::integer-big-size(32), fourcc::bits-size(32), rest::bits>>,
87 full_size = (size - 8) * 8
88 <<data::bits-size(full_size), rest::bits>> = rest
92 fourcc in ["trak", "mdia", "minf", "stbl"] ->
93 # Theses contains sto or co64 part
94 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, fix_moov(data, offset, [])]
96 fourcc in ["stco", "co64"] ->
98 <<version::integer-big-size(32), count::integer-big-size(32), rest::bits>> = data
107 <<size::integer-big-size(32), fourcc::bits-size(32), version::integer-big-size(32),
108 count::integer-big-size(32)>>,
109 rewrite_entries(entry_size, offset, rest, [])
113 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, data]
117 fix_moov(rest, offset, acc)
120 defp fix_moov(<<>>, _, acc), do: acc
122 for size <- [32, 64] do
123 defp rewrite_entries(
126 <<pos::integer-big-size(unquote(size)), rest::bits>>,
135 <<pos + offset::integer-big-size(unquote(size))>>
141 defp rewrite_entries(_, _, <<>>, acc), do: acc