8.0 KiB · text History 44bc4f7
defmodule CartosnapApp.Photos.Images do
  @moduledoc """
  What we work out from an image file: its EXIF block (and from that, when
  it was taken and where), a blurhash placeholder, and the resized variants.

  Resizing shells out to ImageMagick through Mogrify, so `magick` must be on
  the PATH (the release image installs it).
  """

  import Mogrify

  alias CartosnapApp.Photos.Photo

  # A blurhash is computed from a tiny copy: the hash only keeps a few
  # cosine components, so more pixels cost time and add nothing.
  @hash_size 32
  @hash_components {4, 3}

  @variants [
    full: [quality: 82],
    prev: [limit: "640x640", quality: 80],
    thumb: [fill: "240x180", quality: 78]
  ]

  @content_types %{
    "jpg" => "image/jpeg",
    "jpeg" => "image/jpeg",
    "png" => "image/png",
    "gif" => "image/gif"
  }

  def content_type(ext), do: Map.get(@content_types, ext, "application/octet-stream")

  @doc """
  The attributes we can read from the file at `path`: `:exif`, `:date`,
  `:geo_point` (when it has GPS), `:blurhash`, and the camera details
  from `shooting/1`.
  """
  def describe(path) do
    exif = read_exif(path)
    json = jsonable(exif)

    json
    |> shooting()
    |> Map.merge(%{
      exif: json,
      date: taken_at(exif) || DateTime.utc_now(:second),
      geo_point: geo_point(exif),
      blurhash: blurhash(path)
    })
  end

  @doc """
  The camera details from EXIF as stored (string keys, as in the `exif`
  column): `:camera`, `:lens`, `:f_number`, `:focal_length`, `:iso` and
  `:exposure` (in seconds). Each is nil when the file doesn't say.

  The camera is the maker's first word and the model ("Apple iPhone 15",
  "Canon EOS R6"), without the maker twice when the model already starts
  with it ("NIKON CORPORATION" + "NIKON D750" is "NIKON D750").
  """
  def shooting(exif) when is_map(exif) do
    block = if is_map(exif["exif"]), do: exif["exif"], else: %{}

    %{
      camera: camera(text(exif["make"]), text(exif["model"])),
      lens: text(block["lens_model"]),
      f_number: positive_float(block["f_number"]),
      focal_length: positive_float(block["focal_length"]),
      iso: iso(block["iso_speed_ratings"]),
      exposure: exposure(block["exposure_time"])
    }
  end

  def shooting(_), do: shooting(%{})

  defp camera(nil, model), do: model
  defp camera(make, nil), do: make

  defp camera(make, model) do
    [brand | _] = String.split(make)

    if String.starts_with?(String.downcase(model), String.downcase(brand)),
      do: model,
      else: "#{brand} #{model}"
  end

  # EXIF strings come padded with spaces or NULs.
  defp text(value) when is_binary(value) do
    case value |> String.replace("\0", "") |> String.trim() do
      "" -> nil
      text -> String.slice(text, 0, 120)
    end
  end

  defp text(_), do: nil

  defp positive_float(value) when is_number(value) and value > 0,
    do: Float.round(value / 1, 3)

  defp positive_float(_), do: nil

  defp iso([value | _]), do: iso(value)
  defp iso(value) when is_integer(value) and value > 0, do: value
  defp iso(_), do: nil

  defp exposure("1/" <> denominator) do
    case Integer.parse(denominator) do
      {d, ""} when d > 0 -> Float.round(1 / d, 6)
      _ -> nil
    end
  end

  defp exposure(value), do: positive_float(value)

  @doc """
  Writes the resized variants of `path` to temporary files and returns
  `[{variant, temp_path}]`. The caller removes the files.
  """
  def variants(path) do
    base = path |> open() |> auto_orient()

    for {variant, opts} <- @variants do
      image =
        Enum.reduce(opts, base, fn
          {:limit, size}, img -> resize_to_limit(img, size)
          {:fill, size}, img -> resize_to_fill(img, size)
          {:quality, q}, img -> quality(img, to_string(q))
        end)
        |> save()

      {variant, image.path}
    end
  end

  @doc """
  The image's shape: `:width` and `:height` as displayed (EXIF rotation
  applied), and whether it's a photo sphere or panorama (`:kind`,
  `:pano`; see `CartosnapApp.Photos.Panorama`).
  """
  def shape(path) do
    {width, height} = dimensions(path) || {nil, nil}

    path
    |> CartosnapApp.Photos.Panorama.describe(width, height)
    |> Map.merge(%{width: width, height: height})
  end

  @doc "`{width, height}` as displayed, or nil when it can't be read."
  def dimensions(path) do
    # Tagged, because ImageMagick mixes its warnings in (Pixel photos'
    # XMP makes it complain about the XML, harmlessly).
    case System.cmd(
           "magick",
           [path <> "[0]", "-auto-orient", "-format", "size=%w,%h\n", "info:"],
           stderr_to_stdout: true
         ) do
      {out, 0} ->
        case Regex.run(~r/size=(\d+),(\d+)/, out) do
          [_, w, h] -> {String.to_integer(w), String.to_integer(h)}
          nil -> nil
        end

      _ ->
        nil
    end
  rescue
    ErlangError -> nil
  end

  @doc "A blurhash for the image at `path`, or nil when it can't be read."
  def blurhash(path) do
    {x, y} = @hash_components
    size = "#{@hash_size}x#{@hash_size}!"

    case System.cmd(
           "magick",
           [path <> "[0]", "-auto-orient", "-resize", size, "-depth", "8", "rgb:-"],
           stderr_to_stdout: false
         ) do
      {pixels, 0} when byte_size(pixels) == @hash_size * @hash_size * 3 ->
        pixels |> :binary.bin_to_list() |> BlurHash.encode(@hash_size, @hash_size, x, y)

      _ ->
        nil
    end
  rescue
    ErlangError -> nil
  end

  defp read_exif(path) do
    case Exexif.exif_from_jpeg_file(path) do
      {:ok, info} -> info
      {:error, _} -> %{}
    end
  rescue
    # Exexif raises on malformed blocks rather than returning an error.
    _ -> %{}
  end

  @doc """
  When the photo was taken, from EXIF `DateTimeOriginal`. Cameras record
  local time with no zone, so this is that wall-clock time labelled UTC,
  as photos always have been.
  """
  def taken_at(exif) do
    with %{} = block <- Map.get(exif, :exif),
         value when is_binary(value) <- Map.get(block, :datetime_original),
         [_, y, mo, d, h, mi, s] <-
           Regex.run(~r/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/, value),
         {:ok, naive} <-
           NaiveDateTime.new(int(y), int(mo), int(d), int(h), int(mi), int(s)) do
      DateTime.from_naive!(naive, "Etc/UTC")
    else
      _ -> nil
    end
  end

  @doc "Where the photo was taken, from the EXIF GPS block, or nil."
  def geo_point(exif) do
    with %{} = gps <- Map.get(exif, :gps),
         lat when is_number(lat) <-
           degrees(gps_field(gps, :gps_latitude), gps_field(gps, :gps_latitude_ref)),
         lon when is_number(lon) <-
           degrees(gps_field(gps, :gps_longitude), gps_field(gps, :gps_longitude_ref)),
         true <- lat >= -90 and lat <= 90 and lon >= -180 and lon <= 180,
         false <- lat == 0 and lon == 0 do
      Photo.point(lat, lon)
    else
      _ -> nil
    end
  end

  defp gps_field(gps, key), do: Map.get(gps, key)

  defp degrees([d, m, s], ref) when is_number(d) and is_number(m) and is_number(s) do
    value = d + m / 60.0 + s / 3600.0
    if is_binary(ref) and String.upcase(ref) in ["S", "W"], do: -value, else: value
  end

  defp degrees(_, _), do: nil

  defp int(string), do: String.to_integer(string)

  @doc """
  EXIF as something the `exif` jsonb column can hold: structs become maps,
  tuples lists, and binary blobs (maker notes, thumbnails) are dropped.
  """
  def jsonable(%_{} = struct), do: struct |> Map.from_struct() |> jsonable()

  def jsonable(map) when is_map(map) do
    Enum.reduce(map, %{}, fn {k, v}, acc ->
      case jsonable(v) do
        :drop -> acc
        value -> Map.put(acc, to_string(k), value)
      end
    end)
  end

  def jsonable(list) when is_list(list),
    do: list |> Enum.map(&jsonable/1) |> Enum.reject(&(&1 == :drop))

  def jsonable(tuple) when is_tuple(tuple), do: tuple |> Tuple.to_list() |> jsonable()

  def jsonable(binary) when is_binary(binary) do
    if String.printable?(binary), do: binary, else: :drop
  end

  def jsonable(value) when is_number(value) or is_boolean(value) or is_nil(value), do: value
  def jsonable(atom) when is_atom(atom), do: Atom.to_string(atom)
  def jsonable(_), do: :drop
end