2.9 KiB · text History e569b6d
defmodule CartosnapApp.Photos.PanoramaTest do
  use ExUnit.Case, async: true

  alias CartosnapApp.Photos.{Images, Panorama}

  @tag :tmp_dir
  test "a photo sphere is told by its GPano XMP, with where it sits in the sphere", %{
    tmp_dir: dir
  } do
    path =
      jpeg(dir, "sphere.jpg", "800x400", """
      <x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
        <rdf:Description xmlns:GPano="http://ns.google.com/photos/1.0/panorama/"
          GPano:UsePanoramaViewer="True"
          GPano:ProjectionType="equirectangular"
          GPano:FullPanoWidthPixels="1600"
          GPano:FullPanoHeightPixels="800"
          GPano:CroppedAreaLeftPixels="400"
          GPano:CroppedAreaTopPixels="200"
          GPano:CroppedAreaImageWidthPixels="800"
          GPano:CroppedAreaImageHeightPixels="400"
          GPano:PoseHeadingDegrees="307.0"/>
      </rdf:RDF></x:xmpmeta>
      """)

    assert %{kind: "sphere", width: 800, height: 400, pano: pano} = Images.shape(path)

    assert pano == %{
             "full_width" => 1600,
             "full_height" => 800,
             "left" => 400,
             "top" => 200,
             "width" => 800,
             "height" => 400,
             "heading" => 307.0,
             "initial_heading" => nil,
             "initial_pitch" => nil,
             "initial_fov" => nil
           }
  end

  test "reads GPano written as elements too, and fills in what's missing" do
    xmp = """
    <rdf:Description><GPano:ProjectionType>equirectangular</GPano:ProjectionType>
    <GPano:InitialViewHeadingDegrees>90</GPano:InitialViewHeadingDegrees></rdf:Description>
    """

    gpano = Panorama.gpano(xmp)
    assert gpano["ProjectionType"] == "equirectangular"

    assert %{"full_width" => 4000, "full_height" => 2000, "left" => 0, "initial_heading" => 90.0} =
             Panorama.projection(gpano, 4000, 2000)
  end

  @tag :tmp_dir
  test "a very wide photo without the XMP is a panorama; an ordinary one is neither", %{
    tmp_dir: dir
  } do
    assert %{kind: "panorama", pano: nil} = dir |> jpeg("wide.jpg", "900x300") |> Images.shape()

    assert %{kind: nil, width: 400, height: 300} =
             dir |> jpeg("plain.jpg", "400x300") |> Images.shape()

    # 21:9, as some phones shoot: wide, but a photo.
    assert %{kind: nil} = dir |> jpeg("phone.jpg", "700x300") |> Images.shape()
  end

  # A JPEG of `size`, with `xmp` in an APP1 segment straight after SOI, as
  # cameras write it.
  defp jpeg(dir, name, size, xmp \\ nil) do
    path = Path.join(dir, name)
    {_, 0} = System.cmd("magick", ["-size", size, "gradient:red-blue", path])

    if xmp do
      <<0xFF, 0xD8, rest::binary>> = File.read!(path)
      payload = "http://ns.adobe.com/xap/1.0/\0" <> xmp
      segment = <<0xFF, 0xE1, byte_size(payload) + 2::16>> <> payload
      File.write!(path, <<0xFF, 0xD8>> <> segment <> rest)
    end

    path
  end
end