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.MediaHelper do
7 Handles common media-related operations.
14 def missing_dependencies do
15 Enum.reduce([imagemagick: "convert", ffmpeg: "ffmpeg"], [], fn {sym, executable}, acc ->
16 if Pleroma.Utils.command_available?(executable) do
24 def image_resize(url, options) do
25 with executable when is_binary(executable) <- System.find_executable("convert"),
26 {:ok, args} <- prepare_image_resize_args(options),
27 {:ok, env} <- HTTP.get(url, [], []),
28 {:ok, fifo_path} <- mkfifo() do
29 args = List.flatten([fifo_path, args])
30 run_fifo(fifo_path, env, executable, args)
32 nil -> {:error, {:convert, :command_not_found}}
33 {:error, _} = error -> error
37 defp prepare_image_resize_args(
38 %{max_width: max_width, max_height: max_height, format: "png"} = options
40 quality = options[:quality] || 85
41 resize = Enum.join([max_width, "x", max_height, ">"])
54 defp prepare_image_resize_args(%{max_width: max_width, max_height: max_height} = options) do
55 quality = options[:quality] || 85
56 resize = Enum.join([max_width, "x", max_height, ">"])
71 defp prepare_image_resize_args(_), do: {:error, :missing_options}
73 # Note: video thumbnail is intentionally not resized (always has original dimensions)
74 def video_framegrab(url) do
75 with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
76 {:ok, env} <- HTTP.get(url, [], []),
77 {:ok, fifo_path} <- mkfifo(),
90 run_fifo(fifo_path, env, executable, args)
92 nil -> {:error, {:ffmpeg, :command_not_found}}
93 {:error, _} = error -> error
97 defp run_fifo(fifo_path, env, executable, args) do
99 Port.open({:spawn_executable, executable}, [
107 fifo = File.open!(fifo_path, [:append, :binary])
108 fix = Pleroma.Helpers.QtFastStart.fix(env.body)
109 IO.binwrite(fifo, fix)
117 path = Path.join(System.tmp_dir!(), "pleroma-media-preview-pipe-#{Ecto.UUID.generate()}")
119 case System.cmd("mkfifo", [path]) do
121 spawn(fifo_guard(path))
125 {:error, {:fifo_failed, err}}
129 defp fifo_guard(path) do
133 ref = Process.monitor(pid)
136 {:DOWN, ^ref, :process, ^pid, _} ->
142 defp loop_recv(pid) do
146 defp loop_recv(pid, acc) do
148 {^pid, {:data, data}} ->
149 loop_recv(pid, acc <> data)
151 {^pid, {:exit_status, 0}} ->
154 {^pid, {:exit_status, status}} ->
158 :erlang.port_close(pid)