1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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(binary = <<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70, _::bits>>) 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. Why stream useless bytes when you can do without?
64 case List.keytake(index, "free", 0) do
65 {{_, _, _, size, _}, index} -> {size, index}
69 {{_moov, _, _, moov_size, moov}, index} = List.keytake(index, "moov", 0)
70 offset = -free_size + moov_size
71 rest = for {_, _, _, _, data} <- index, do: data, into: []
72 <<moov_head::bits-size(64), moov_data::bits>> = moov
73 [ftyp, moov_head, fix_moov(moov_data, offset, []), rest]
77 <<size::integer-big-size(32), fourcc::bits-size(32), rest::bits>>,
81 full_size = (size - 8) * 8
82 <<data::bits-size(full_size), rest::bits>> = rest
86 fourcc in ["trak", "mdia", "minf", "stbl"] ->
87 # Theses contains sto or co64 part
88 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, fix_moov(data, offset, [])]
90 fourcc in ["stco", "co64"] ->
92 <<version::integer-big-size(32), count::integer-big-size(32), rest::bits>> = data
101 <<size::integer-big-size(32), fourcc::bits-size(32), version::integer-big-size(32),
102 count::integer-big-size(32)>>,
103 rewrite_entries(entry_size, offset, rest, [])
107 [<<size::integer-big-size(32), fourcc::bits-size(32)>>, data]
111 fix_moov(rest, offset, acc)
114 defp fix_moov(<<>>, _, acc), do: acc
116 for size <- [32, 64] do
117 defp rewrite_entries(
120 <<pos::integer-big-size(unquote(size)), rest::bits>>,
123 rewrite_entries(unquote(size), offset, rest, [
124 acc | <<pos + offset::integer-big-size(unquote(size))>>
129 defp rewrite_entries(_, _, <<>>, acc), do: acc