from typing import Optional
from typing import Union
import base64


def html_from_compressed_video(data: bytes,
                               width: int,
                               height: int,
                               *,
                               title: Optional[str] = None,
                               border: Union[bool, str] = False,
                               loop: bool = True,
                               autoplay: bool = True) -> str:
  """Returns an HTML string with a video tag containing H264-encoded data.

  Args:
    data: MP4-compressed video bytes.
    width: Width of HTML video in pixels.
    height: Height of HTML video in pixels.
    title: Optional text shown centered above the video.
    border: If bool, whether image has black boundary, or if str, css style.
    loop: If True, the playback repeats forever.
    autoplay: If True, video playback starts without having to click.
  """
  b64 = base64.b64encode(data).decode('utf-8')
  border = (f'{border}; ' if isinstance(border, str) else
            'border:1px solid black; ' if border else '')
  options = (f'controls width="{width}" height="{height}"'
             f' style="{border}object-fit:cover;"'
             f"{' loop' if loop else ''}{' autoplay' if autoplay else ''}")
  s = f"""<video {options}>
      <source src="data:video/x-m4v;base64,{b64}" type="video/mp4"/>
      This browser does not support the video tag.
      </video>"""
  if title:
    s = f"""<div style="display:flex; align-items:left;">
      <div style="display:flex; flex-direction:column; align-items:center;">
      <div>{title}</div><div>{s}</div></div></div>"""
  return s