4.4 KiB · text History e569b6d
defmodule CartosnapApp.Photos.Panorama do
  @moduledoc """
  Telling panoramas and photo spheres from ordinary photos.

    * A **photo sphere** is an equirectangular image: longitude across,
      latitude down. Phones mark them with Google's photo sphere XMP
      (`GPano:ProjectionType="equirectangular"`), which also says how much
      of the full sphere the image covers. A wide Google Camera panorama is
      one too, covering a band of the sphere rather than all of it, and is
      best seen the same way. Shown in a viewer you look around in
      (`assets/js/photo_sphere.js`).
    * A **panorama** without that metadata is just a very wide picture (at
      least #{2.5}:1, past a 21:9 phone photo): shown full height, panned
      across.

  The GPano XMP spec: https://developers.google.com/streetview/spherical-metadata
  """

  @xmp_header "http://ns.adobe.com/xap/1.0/\0"
  @wide 2.5

  @doc """
  What kind of photo the image at `path` (`width` × `height` as displayed)
  is: `%{kind: "sphere", pano: %{...}}`, `%{kind: "panorama", pano: nil}`,
  or `%{kind: nil, pano: nil}` for an ordinary one.
  """
  def describe(path, width, height) do
    gpano = path |> read_xmp() |> gpano()

    cond do
      sphere?(gpano) -> %{kind: "sphere", pano: projection(gpano, width, height)}
      wide?(width, height) -> %{kind: "panorama", pano: nil}
      true -> %{kind: nil, pano: nil}
    end
  end

  @doc "The standard XMP packet in a JPEG's APP1 segments, or nil."
  def read_xmp(path) do
    case File.open(path, [:read, :binary], &scan(IO.binread(&1, 2), &1)) do
      {:ok, xmp} -> xmp
      _ -> nil
    end
  end

  # JPEG: SOI, then segments <<0xFF, marker, length::16, data>> until the
  # image data (SOS). XMP is in the head, so the scan reads only that far.
  defp scan(<<0xFF, 0xD8>>, io), do: next_segment(io)
  defp scan(_, _io), do: nil

  defp next_segment(io) do
    with <<0xFF, marker, length::16>> when marker not in [0xDA, 0xD9] <- IO.binread(io, 4),
         data when is_binary(data) <- IO.binread(io, length - 2) do
      case {marker, data} do
        {0xE1, @xmp_header <> xmp} -> xmp
        _ -> next_segment(io)
      end
    else
      _ -> nil
    end
  end

  @doc """
  The GPano properties in an XMP packet, as `%{"ProjectionType" =>
  "equirectangular", ...}`, written either as attributes or as elements.
  """
  def gpano(nil), do: %{}

  def gpano(xmp) when is_binary(xmp) do
    attributes = Regex.scan(~r/GPano:(\w+)="([^"]*)"/, xmp, capture: :all_but_first)
    elements = Regex.scan(~r/<GPano:(\w+)>([^<]*)<\/GPano:\1>/, xmp, capture: :all_but_first)
    Map.new(attributes ++ elements, fn [key, value] -> {key, String.trim(value)} end)
  end

  defp sphere?(gpano), do: String.downcase(gpano["ProjectionType"] || "") == "equirectangular"

  defp wide?(width, height) when is_integer(width) and is_integer(height) and height > 0,
    do: width / height >= @wide

  defp wide?(_width, _height), do: false

  @doc """
  A sphere's projection, from its GPano properties: where the image sits
  in the full sphere (`full_width` × `full_height`, the image's area from
  `left`, `top`, `width` × `height`), plus the compass heading of its
  centre and the view to open on, when given. Missing sizes default to the
  image itself covering the whole sphere.
  """
  def projection(gpano, width, height) do
    cropped_width = int(gpano["CroppedAreaImageWidthPixels"]) || width
    cropped_height = int(gpano["CroppedAreaImageHeightPixels"]) || height
    full_width = int(gpano["FullPanoWidthPixels"]) || cropped_width
    full_height = int(gpano["FullPanoHeightPixels"]) || div(full_width || 0, 2)

    %{
      "full_width" => full_width,
      "full_height" => full_height,
      "left" => int(gpano["CroppedAreaLeftPixels"]) || 0,
      "top" => int(gpano["CroppedAreaTopPixels"]) || 0,
      "width" => cropped_width,
      "height" => cropped_height,
      "heading" => float(gpano["PoseHeadingDegrees"]),
      "initial_heading" => float(gpano["InitialViewHeadingDegrees"]),
      "initial_pitch" => float(gpano["InitialViewPitchDegrees"]),
      "initial_fov" => float(gpano["InitialHorizontalFOVDegrees"])
    }
  end

  defp int(nil), do: nil

  defp int(value) do
    case Integer.parse(value) do
      {n, _} when n >= 0 -> n
      _ -> nil
    end
  end

  defp float(nil), do: nil

  defp float(value) do
    case Float.parse(value) do
      {f, _} -> f
      :error -> nil
    end
  end
end