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.MediaHelper do
7 Handles common media-related operations.
10 @tmp_base "/tmp/pleroma-media_preview-pipe"
12 def image_resize(url, options) do
13 with executable when is_binary(executable) <- System.find_executable("convert"),
14 {:ok, args} <- prepare_image_resize_args(options),
15 url = Pleroma.Web.MediaProxy.url(url),
16 {:ok, env} <- Pleroma.HTTP.get(url),
17 {:ok, fifo_path} <- mkfifo()
19 run_fifo(fifo_path, env, executable, args)
21 nil -> {:error, {:convert, :command_not_found}}
22 {:error, _} = error -> error
26 defp prepare_image_resize_args(%{max_width: max_width, max_height: max_height} = options) do
27 quality = options[:quality] || 85
28 resize = Enum.join([max_width, "x", max_height, ">"])
30 "-interlace", "Plane",
32 "-quality", to_string(quality),
38 defp prepare_image_resize_args(_), do: {:error, :missing_options}
40 def video_framegrab(url) do
41 with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
49 url = Pleroma.Web.MediaProxy.url(url),
50 {:ok, env} <- Pleroma.HTTP.get(url),
51 {:ok, fifo_path} <- mkfifo() do
52 run_fifo(fifo_path, env, executable, args)
54 nil -> {:error, {:ffmpeg, :command_not_found}}
55 {:error, _} = error -> error
59 defp run_fifo(fifo_path, env, executable, args) do
60 args = List.flatten([fifo_path, args])
61 pid = Port.open({:spawn_executable, executable}, [:use_stdio, :stream, :exit_status, :binary, args: args])
62 fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
63 true = Port.command(fifo, env.body)
64 :erlang.port_close(fifo)
71 path = "#{@tmp_base}#{to_charlist(:erlang.phash2(self()))}"
72 case System.cmd("mkfifo", [path]) do
74 spawn(fifo_guard(path))
77 {:error, {:fifo_failed, err}}
81 defp fifo_guard(path) do
84 ref = Process.monitor(pid)
86 {:DOWN, ^ref, :process, ^pid, _} ->
92 defp loop_recv(pid) do
96 defp loop_recv(pid, acc) do
98 {^pid, {:data, data}} ->
99 loop_recv(pid, acc <> data)
100 {^pid, {:exit_status, 0}} ->
102 {^pid, {:exit_status, status}} ->
106 :erlang.port_close(pid)