#!/bin/bash
#  serview - play a .ser or .ser.mj2 astronomy capture with ffplay.
#            No MATLAB, no runtime.  macOS and Linux; serview.ps1 is the
#            same thing for Windows, and the two are kept in step.
#
#  usage:  serview <file.ser|file.ser.mj2> [-info] [-nostretch] [-raw] [-loop]
#                  [-rate n] [-bayer rggb|grbg|gbrg|bggr] [-bigendian]
#                  [-ffplay path] [-noconsole]
#          serview -associate | -unassociate          (Linux)
#
#  A .ser.mj2 is an ordinary Motion JPEG 2000 file, so any player built on
#  FFmpeg already decodes it.  Two things stop it looking right, and this
#  script fixes both:
#
#   1. A 16-bit capture stores TWO images per frame - a 12-bit picture then
#      its 4-bit remainder - so a player shows picture, black, picture,
#      black at twice the frame count.  The remainder is dropped here, which
#      for viewing costs nothing: it is the bottom 4 bits of 16.
#   2. Astronomy data sits in the bottom fraction of its range and no player
#      stretches it, so the picture comes out nearly black.  FFmpeg's
#      normalize filter is applied to bring it up.
#
#  The playback rate is taken from the capture's own timestamps, not from
#  the container: serCompress writes at VideoWriter's default 30 fps
#  regardless of how fast the camera actually ran.
#
#  A plain .ser is 178 bytes of header, the frames, then a timestamp per
#  frame - which is what FFmpeg's rawvideo demuxer wants once it is told the
#  geometry and to step over the header.  Bayer captures are demosaiced by
#  FFmpeg using the pattern in the header.
#
#  Options
#    -info        Print what the file says about itself, which ffplay was
#                 found, its version and whether it has the filters needed,
#                 and play nothing.  Works with no ffplay at all.
#    -nostretch   Leave the brightness alone, for judging exposure.
#    -raw         Every stored image, remainder planes included, at the
#                 container's own rate.  What a plain player would show.
#    -loop        Round and round.
#    -bayer P     Override the colour filter pattern of a plain .ser.  Only
#                 for a header that no longer matches its pixels; a blue
#                 picture is the raw sensor, not a wrong pattern.
#    -bigendian   Read 16-bit samples big-endian.  Almost never needed.
#    -rate n      Override the frames per second.
#    -ffplay P    Path to ffplay, when it is somewhere this cannot find.
#    -noconsole   Messages go to a dialog instead of the terminal.  What
#                 serview.app, and the Linux desktop entry, pass when a file
#                 is double-clicked.
#    -associate   Linux only.  Adds the viewer, and SER Tools if it is beside
#                 this script, to the applications menu, and makes the viewer
#                 what a double-click on a .ser or .ser.mj2 opens.  For this
#                 user only, so no sudo.  -unassociate takes it all out again.
#                 The Linux counterpart of servieww.exe and serview.app: a
#                 desktop can only hand a file to a program that has a
#                 .desktop entry, and nothing else creates one.
#
#  Needs ffplay, part of FFmpeg:   brew install ffmpeg   (macOS)
#                                  sudo apt install ffmpeg  (Debian, Ubuntu)
#  Or put ffplay beside this script.
#
#  Written for the bash 3.2 that ships with macOS: no arrays of arrays, no
#  ${var,,}, no mapfile.  Binary fields are read with od, which is POSIX and
#  reports in the machine's own byte order - little-endian on every Mac and
#  PC, which is also SER's.
#
#  Part of BiggSky SER Tools.  See SERZ-FORMAT.md for the file layout.

set -u

# ---- how messages get out --------------------------------------------------
NOCONSOLE=0
TITLE='BiggSky SER viewer'

# The one place the two platforms part company for more than a path: how a
# message reaches someone with no terminal, and what to tell them to type to
# get FFmpeg.  Linux has no single package manager, so the hint names the
# one this machine actually has.
case "$(uname -s)" in
    Darwin) OS=mac;   FFINSTALL='brew install ffmpeg' ;;
    *)      OS=linux; FFINSTALL='your package manager'
            for pm in 'apt:sudo apt install ffmpeg' 'dnf:sudo dnf install ffmpeg' \
                      'zypper:sudo zypper install ffmpeg' 'pacman:sudo pacman -S ffmpeg'; do
                command -v "${pm%%:*}" >/dev/null 2>&1 && { FFINSTALL=${pm#*:}; break; }
            done ;;
esac

dialog() {   # dialog <text> [error]
    if [ "$OS" = mac ]; then
        if [ "${2:-}" = error ]; then icon=stop; else icon=note; fi
        osascript >/dev/null 2>&1 <<EOF
display dialog "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')" with title "$TITLE" buttons {"OK"} default button 1 with icon $icon
EOF
        return
    fi
    # Linux: whichever dialog program this desktop has, GNOME's then KDE's,
    # then the X11 one every system with a display can run.  Exit status 1
    # is the user closing the box, which counts as shown; anything higher is
    # the program refusing an option, so the next one is tried.
    if [ "${2:-}" = error ]; then z=--error; k=--error; else z=--info; k=--msgbox; fi
    if command -v zenity >/dev/null 2>&1; then
        zenity $z --no-markup --title="$TITLE" --text="$1" >/dev/null 2>&1
        [ $? -le 1 ] && return
    fi
    if command -v kdialog >/dev/null 2>&1; then
        kdialog --title "$TITLE" $k "$1" >/dev/null 2>&1
        [ $? -le 1 ] && return
    fi
    if command -v xmessage >/dev/null 2>&1; then
        xmessage -center -title "$TITLE" "$1" >/dev/null 2>&1 && return
    fi
    if command -v notify-send >/dev/null 2>&1; then
        notify-send "$TITLE" "$1" >/dev/null 2>&1 && return
    fi
    printf '\n%s\n' "$1" >&2
}

fail() {     # fail <text> [code]   - one plain message and a non-zero exit
    if [ "$NOCONSOLE" = 1 ]; then dialog "$1" error
    else printf '\n%s\n' "$1" >&2; fi
    exit "${2:-1}"
}

# ---- reading numbers out of a file -------------------------------------------
# od -j skips, -N reads, -t picks the type.  Output has leading spaces.
# Each little-endian field is read as hex bytes and assembled in shell
# arithmetic, which is 64-bit in every bash and zsh.  Not od's own -t d8:
# on macOS that prints the first byte of each word, sign-extended, which
# turned every timestamp into a small negative number.
le()  {   # le <file> <offset> <nbytes>  -> unsigned value
    hex=$(od -An -t x1 -j "$2" -N "$3" "$1" 2>/dev/null | tr -d ' \n')
    [ ${#hex} -eq $(( $3 * 2 )) ] || { echo ''; return; }
    n=0; i=${#hex}
    while [ $i -gt 0 ]; do i=$((i - 2)); n=$(( (n << 8) | 0x${hex:$i:2} )); done
    echo "$n"
}
i32() { v=$(le "$1" "$2" 4); [ -n "$v" ] && [ "$v" -ge 2147483648 ] && v=$((v - 4294967296)); echo "$v"; }
u32() { le "$1" "$2" 4; }
i64() { le "$1" "$2" 8; }    # a timestamp or a size: never near 2^63
u64() { le "$1" "$2" 8; }
txt() { dd if="$1" bs=1 skip="$2" count="$3" 2>/dev/null | tr -d '\0'; }
# GNU stat first, and captured rather than printed.  The other order - BSD's
# "stat -f %z" - means "file SYSTEM status" to GNU stat, which prints a whole
# report about the disk to stdout before failing on the missing file "%z",
# so every size on Linux came out as a paragraph and every file was refused.
fsize() {
    s=$(stat -c %s "$1" 2>/dev/null) || s=$(stat -f %z "$1" 2>/dev/null)
    echo "$s"
}
calc() { awk "BEGIN { printf \"%s\", ($1) }"; }

# ---- the SERZ metadata box at the end of a .ser.mj2 -------------------------
# Read from the last twelve bytes rather than scanned for, so this costs
# two seeks on a file of any size.  Sets M_* on success, returns 1 otherwise.
read_serz_box() {
    f=$1; sz=$(fsize "$f")
    [ "$sz" -ge 200 ] || return 1
    boxSize=$(u32 "$f" $((sz - 12)))
    [ "$(txt "$f" $((sz - 8)) 8)" = SERZEND1 ] || return 1
    [ "$boxSize" -gt 24 ] && [ "$boxSize" -le "$sz" ] || return 1
    b=$((sz - boxSize))
    [ "$(txt "$f" $((b + 8)) 4)" = SERZ ] || return 1

    M_version=$(u32 "$f" $((b + 12)))
    M_layout=$(u32 "$f" $((b + 16)))
    M_bitDepth=$(u32 "$f" $((b + 20)))
    M_planes=$(u32 "$f" $((b + 24)))
    M_origBytes=$(u64 "$f" $((b + 28)))
    M_headerLen=$(u32 "$f" $((b + 36)))
    M_trailerLen=$(u32 "$f" $((b + 40)))

    # Where the SER header starts depends on the version, because each one
    # added fields before it.  Reading a v4 box with the v3 offset yields a
    # plausible-looking garbage header rather than an error.
    case "$M_version" in
        1) h=44 ;; 2) h=52 ;; 3) h=56 ;; *) h=88 ;;
    esac
    [ $((h + 178)) -le "$boxSize" ] || return 1
    h=$((b + h))
    M_colorID=$(i32 "$f" $((h + 18)))
    M_width=$(i32   "$f" $((h + 26)))
    M_height=$(i32  "$f" $((h + 30)))
    M_depth=$(i32   "$f" $((h + 34)))
    M_frames=$(i32  "$f" $((h + 38)))

    # The capture's real rate, from its own timestamps: .NET ticks, 100 ns.
    M_fps=0
    tAt=$((h + M_headerLen)); nT=$((M_trailerLen / 8))
    if [ "$nT" -ge 2 ] && [ $((tAt + 8 * nT)) -le "$sz" ]; then
        t0=$(i64 "$f" "$tAt"); t1=$(i64 "$f" $((tAt + 8 * (nT - 1))))
        M_fps=$(calc "($t1 - $t0) > 0 ? sprintf(\"%.3f\", ($nT - 1) / (($t1 - $t0) / 1e7)) : 0")
    fi
    return 0
}

# ---- a plain .ser --------------------------------------------------------------
read_ser_header() {
    f=$1; sz=$(fsize "$f")
    [ "$sz" -ge 178 ] || return 1
    M_fileID=$(txt "$f" 0 14)
    M_colorID=$(i32 "$f" 18)
    M_width=$(i32 "$f" 26)
    M_height=$(i32 "$f" 30)
    M_depth=$(i32 "$f" 34)
    M_frames=$(i32 "$f" 38)
    M_fps=0; M_truncated=0

    # Three checks, because reading any file at all as a SER header yields
    # numbers: the signature, plausible geometry, and a file big enough to
    # hold what it claims - which also catches a capture cut off by a full
    # disk.
    case "$M_fileID" in LUCAM-RECORDER*) ;; *) return 1 ;; esac
    [ "$M_width" -gt 0 ] && [ "$M_height" -gt 0 ] && [ "$M_frames" -gt 0 ] || return 1
    [ "$M_width" -le 65535 ] && [ "$M_height" -le 65535 ] || return 1

    if [ "$M_colorID" -ge 100 ]; then cc=3; else cc=1; fi
    if [ "$M_depth" -eq 16 ] || [ "$M_depth" -eq 48 ]; then bpp=2; else bpp=1; fi
    M_bytesPerPixel=$((cc * bpp))
    frameBytes=$((M_width * M_height * cc * bpp))
    M_payload=$((frameBytes * M_frames))
    if [ "$sz" -lt $((178 + M_payload)) ]; then
        # Short for its own header.  Play what is there rather than refusing,
        # but say so and trim the count so the run time is right.
        M_frames=$(((sz - 178) / frameBytes))
        M_truncated=1
        [ "$M_frames" -gt 0 ] || return 1
        M_payload=$((frameBytes * M_frames))
    fi

    # The real capture rate, from the trailer.  Optional in the format.
    tAt=$((178 + M_payload))
    if [ "$sz" -ge $((tAt + 8 * M_frames)) ] && [ "$M_frames" -ge 2 ]; then
        t0=$(i64 "$f" "$tAt"); t1=$(i64 "$f" $((tAt + 8 * (M_frames - 1))))
        M_fps=$(calc "($t1 - $t0) > 0 ? sprintf(\"%.3f\", ($M_frames - 1) / (($t1 - $t0) / 1e7)) : 0")
    fi
    return 0
}

# The FFmpeg rawvideo pixel format for a SER's ColorID and depth.  The Bayer
# pattern is taken from the header and believed: a raw one-shot-colour frame
# IS blue before white balance, so judging the pattern by the colour cast
# picks the wrong one about as often as the right one.
pixel_format() {
    if [ "$BIGENDIAN" = 1 ]; then e=be; else e=le; fi
    if [ "$M_depth" -eq 16 ] || [ "$M_depth" -eq 48 ]; then two=1; else two=0; fi
    if [ -n "$BAYER" ]; then
        if [ $two = 1 ]; then echo "bayer_${BAYER}16$e"; else echo "bayer_${BAYER}8"; fi
        return
    fi
    if [ "$M_colorID" -ge 100 ]; then
        if [ "$M_colorID" -eq 101 ]; then base=bgr; else base=rgb; fi
        if [ $two = 1 ]; then echo "${base}48$e"; else echo "${base}24"; fi
    elif [ "$M_colorID" -ge 8 ] && [ "$M_colorID" -le 11 ]; then
        case "$M_colorID" in 8) p=rggb ;; 9) p=grbg ;; 10) p=gbrg ;; 11) p=bggr ;; esac
        if [ $two = 1 ]; then echo "bayer_${p}16$e"; else echo "bayer_${p}8"; fi
    else
        # Mono, and the CYYM/YCMY family FFmpeg has no demosaic for - shown
        # as the raw mosaic in grey, which is honest and still useful.
        if [ $two = 1 ]; then echo "gray16$e"; else echo gray; fi
    fi
}

color_name() {
    case "$1" in
        0) echo mono ;;
        8) echo 'Bayer RGGB' ;;  9) echo 'Bayer GRBG' ;;
        10) echo 'Bayer GBRG' ;; 11) echo 'Bayer BGGR' ;;
        16) echo 'Bayer CYYM' ;; 17) echo 'Bayer YCMY' ;;
        18) echo 'Bayer YMCY' ;; 19) echo 'Bayer MYYC' ;;
        100) echo RGB ;;         101) echo BGR ;;
        *) echo "ColorID $1" ;;
    esac
}

layout_name() {
    case "$1" in
        0) echo 'mono or Bayer, stored directly' ;;
        1) echo 'RGB as three grey planes (legacy)' ;;
        2) echo '16-bit as high/low byte planes (legacy)' ;;
        3) echo '48-bit RGB, three channels x hi/lo' ;;
        4) echo '16-bit as quotient + remainder' ;;
        5) echo '8-bit RGB as one 3-component image' ;;
        *) echo "unknown ($1)" ;;
    esac
}

# ---- finding an ffplay that can do the job ---------------------------------
# A LIST, best first, because "an ffplay exists" is not the same question as
# "an ffplay that can do this exists": a cut-down build is found, runs, and
# stops with "No such filter: 'normalize'" after printing everything as
# though it were about to work.  Homebrew's folders are named explicitly
# because a double-clicked app gets a PATH without them.
#
# HERE is the real folder, through any symlink: someone who links serview
# into ~/bin still has ffplay, the icon and SER Tools found beside the
# original.  readlink -f is GNU and recent macOS; older Macs fall back.
SELF=$(readlink -f "$0" 2>/dev/null) || SELF=$0
HERE=$(cd "$(dirname "$SELF")" && pwd)
FF_DIRS="$HERE /opt/homebrew/bin /usr/local/bin /opt/local/bin $HOME/.local/bin /snap/bin"

find_ffplay() {   # prints candidates one per line, best first
    p=$(command -v ffplay 2>/dev/null) && [ -n "$p" ] && echo "$p"
    for d in $FF_DIRS; do [ -x "$d/ffplay" ] && echo "$d/ffplay"; done
    # The Ubuntu snap names it by the package: ffmpeg.ffplay.
    [ -x /snap/bin/ffmpeg.ffplay ] && echo /snap/bin/ffmpeg.ffplay
    return 0
}

ffplay_caps() {   # sets CAP_version CAP_filters for the given exe
    CAP_version=$("$1" -hide_banner -version 2>&1 | head -1 | sed 's/^ffplay version //; s/ Copyright.*$//')
    # "  T. framestep    V->V   Select one frame every N frames."  The name
    # is the token before the one holding "->", which is steadier than
    # counting the flag characters.
    CAP_filters=$("$1" -hide_banner -filters 2>/dev/null | awk '{for (i = 2; i <= NF; i++) if ($i ~ /->/) { print $(i-1); break }}')
    CAP_protocols=$("$1" -hide_banner -protocols 2>/dev/null | tr -d ' ')
}
has_filter()   { printf '%s\n' "$CAP_filters"   | grep -qx "$1"; }
has_protocol() { printf '%s\n' "$CAP_protocols" | grep -qx "$1"; }

select_ffplay() {   # sets FF and CAP_*, or FFTROUBLE and returns 1
    FF=''; FFTROUBLE=''
    if [ -n "$FFPLAY_HINT" ]; then
        if [ -x "$FFPLAY_HINT" ]; then cands=$FFPLAY_HINT
        else FFTROUBLE="ffplay not found where you pointed: $FFPLAY_HINT"; return 1; fi
    else
        cands=$(find_ffplay | awk '!seen[$0]++')
    fi
    if [ -z "$cands" ]; then
        FFTROUBLE="ffplay was not found.  Install FFmpeg with
    $FFINSTALL
or put ffplay beside this script, or pass -ffplay <path>.
Looked in: PATH; $(echo $FF_DIRS | sed 's/ /; /g')"
        return 1
    fi
    first=''
    for c in $cands; do
        ffplay_caps "$c"
        [ -n "$first" ] || first=$c
        if has_filter normalize && has_filter framestep; then FF=$c; return; fi
    done
    FF=$first; ffplay_caps "$FF"
}

# ---- desktop integration (Linux) -----------------------------------------------
# What servieww.exe is on Windows and serview.app on macOS: something a
# double-click can be pointed at.  On Linux that is a .desktop entry, plus -
# for .ser, which no desktop has heard of - a MIME type saying what a .ser
# is: the extension, and "LUCAM-RECORDER" at the start for a file that has
# lost it.  Everything goes in this user's own folders, so no sudo, and
# every file is named so that -unassociate finds exactly what was written.
DATA=${XDG_DATA_HOME:-$HOME/.local/share}
APPS=$DATA/applications
MIME=$DATA/mime
VIEWER_DESKTOP=biggsky-serview.desktop
TOOLS_DESKTOP=biggsky-sertools.desktop
MIME_XML=$MIME/packages/biggsky-ser.xml

refresh_desktop() {
    command -v update-mime-database    >/dev/null 2>&1 && update-mime-database "$MIME" >/dev/null 2>&1
    command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$APPS" >/dev/null 2>&1
    return 0
}

# One Exec argument, quoted as the Desktop Entry spec wants.  Two layers of
# escaping apply, the file's and then the command line's, which is why a
# backslash becomes four; and % is the spec's own field marker.
desktop_quote() {
    printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\\\\\/g' -e 's/["$`]/\\\\&/g' -e 's/%/%%/g')"
}

associate() {
    [ "$OS" = linux ] || fail "-associate is for Linux.  On macOS, point the file types at serview.app with Get Info in the Finder - the Help tab has the steps." 2
    mkdir -p "$APPS" "$MIME/packages" || fail "Cannot create $APPS or $MIME/packages."
    icon=''
    [ -f "$HERE/sertools.png" ] && icon=$HERE/sertools.png

    cat > "$MIME_XML" <<'EOF' || fail "Cannot write $MIME_XML."
<?xml version="1.0" encoding="UTF-8"?>
<!-- Written by "serview -associate".  "serview -unassociate" removes it. -->
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
  <mime-type type="video/x-ser">
    <comment>SER astronomy capture</comment>
    <glob pattern="*.ser"/>
    <magic priority="60"><match type="string" offset="0" value="LUCAM-RECORDER"/></magic>
  </mime-type>
  <mime-type type="video/mj2">
    <comment>Motion JPEG 2000 video</comment>
    <glob pattern="*.mj2"/>
    <glob pattern="*.mjp2"/>
  </mime-type>
</mime-info>
EOF

    {
        echo '[Desktop Entry]'
        echo 'Type=Application'
        echo 'Name=BiggSky SER viewer'
        echo 'GenericName=Astronomy movie player'
        echo 'Comment=Play a .ser or .ser.mj2 capture - needs FFmpeg, not MATLAB'
        echo "Exec=$(desktop_quote "$HERE/serview") -noconsole %f"
        [ -n "$icon" ] && echo "Icon=$icon"
        echo 'Terminal=false'
        echo 'MimeType=video/x-ser;video/mj2;'
        echo 'Categories=AudioVideo;Video;Player;Science;Astronomy;'
    } > "$APPS/$VIEWER_DESKTOP" || fail "Cannot write $APPS/$VIEWER_DESKTOP."
    wrote="    $APPS/$VIEWER_DESKTOP"

    # SER Tools gets a menu entry but no file types.  It is slow to start
    # for a quick look, and on Windows an association with it nobody asked
    # for was the first thing a tester reported.
    if [ -f "$HERE/serToolsApp" ]; then
        {
            echo '[Desktop Entry]'
            echo 'Type=Application'
            echo 'Name=BiggSky SER Tools'
            echo 'Comment=Compress SER captures losslessly, verify and play them'
            echo "Exec=$(desktop_quote "$HERE/serToolsApp") %f"
            [ -n "$icon" ] && echo "Icon=$icon"
            echo 'Terminal=false'
            echo 'Categories=Graphics;Science;Astronomy;'
        } > "$APPS/$TOOLS_DESKTOP" && wrote="$wrote
    $APPS/$TOOLS_DESKTOP"
    fi
    wrote="$wrote
    $MIME_XML"

    refresh_desktop
    if command -v xdg-mime >/dev/null 2>&1 && \
       xdg-mime default "$VIEWER_DESKTOP" video/x-ser video/mj2 >/dev/null 2>&1; then
        how='A double-click on a .ser or .ser.mj2 now opens the viewer.'
    else
        how='xdg-mime is not installed (it comes with xdg-utils), so nothing was
made the default: choose "BiggSky SER viewer" under Open With in the file
manager instead, and tick the option to always use it.'
    fi
    command -v update-mime-database >/dev/null 2>&1 || how="$how
update-mime-database is not installed (it comes with shared-mime-info), so
the desktop may not recognise .ser until it is."
    printf '%s\n' "Wrote
$wrote

$how
If the file manager still offers the old program, log out and back in.
serview -unassociate takes all of this out again."
}

unassociate() {
    [ "$OS" = linux ] || fail "-unassociate is for Linux." 2
    rm -f "$APPS/$VIEWER_DESKTOP" "$APPS/$TOOLS_DESKTOP" "$MIME_XML"
    # xdg-mime records the default in mimeapps.list.  Take our entry out of
    # each line rather than deleting lines, which can name other programs
    # too, and drop any line it leaves with nothing after the "=".
    for list in "${XDG_CONFIG_HOME:-$HOME/.config}/mimeapps.list" "$APPS/mimeapps.list"; do
        [ -f "$list" ] && sed -i -e 's/biggsky-serview\.desktop;\{0,1\}//g' -e '/^[^=[]*=$/d' "$list"
    done
    refresh_desktop
    echo 'Removed the BiggSky menu entries, the .ser file type and the default.'
}

# ---- arguments ---------------------------------------------------------------
FILE=''; INFO=0; NOSTRETCH=0; RAW=0; LOOP=0; BAYER=''; BIGENDIAN=0; RATE=0; FFPLAY_HINT=''; ASSOC=0
FF=''; FFTROUBLE=''; CAP_version=''; CAP_filters=''; CAP_protocols=''
while [ $# -gt 0 ]; do
    o=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
    case "$o" in
        -info|--info)           INFO=1 ;;
        -nostretch|--nostretch) NOSTRETCH=1 ;;
        -raw|--raw)             RAW=1 ;;
        -loop|--loop)           LOOP=1 ;;
        -noconsole|--noconsole) NOCONSOLE=1 ;;
        -bigendian|--bigendian) BIGENDIAN=1 ;;
        -associate|--associate)     ASSOC=1 ;;
        -unassociate|--unassociate) ASSOC=2 ;;
        -bayer|--bayer)
            shift; BAYER=$(printf '%s' "${1:-}" | tr 'A-Z' 'a-z')
            case "$BAYER" in rggb|grbg|gbrg|bggr) ;; *) fail "-bayer wants rggb, grbg, gbrg or bggr, not '${1:-}'" 2 ;; esac ;;
        -rate|--rate)           shift; RATE=${1:-0} ;;
        -ffplay|--ffplay)       shift; FFPLAY_HINT=${1:-} ;;
        -h|-help|--help)        FILE='' ; break ;;
        -*)                     fail "Unknown option: $1" 2 ;;
        *)  if [ -z "$FILE" ]; then FILE=$1; else fail "One file at a time: $1" 2; fi ;;
    esac
    shift
done

case $ASSOC in 1) associate; exit 0 ;; 2) unassociate; exit 0 ;; esac

if [ -z "$FILE" ]; then
    if [ "$OS" = mac ]; then
        how='Pass a file on the command line, or drop one on serview.app.'
    else
        how='Pass a file on the command line.  Run "serview -associate" once to open
.ser and .ser.mj2 by double-click and put SER Tools in the applications menu.'
    fi
    cat <<EOF
serview - play a .ser or .ser.mj2 without installing MATLAB

  serview <file.ser|file.ser.mj2> [-info] [-nostretch] [-raw] [-loop]
          [-rate n] [-bayer rggb|grbg|gbrg|bggr] [-bigendian] [-ffplay path]
  serview -associate | -unassociate       (Linux)

$how
Needs ffplay:  $FFINSTALL
EOF
    exit 2
fi

if [ ! -f "$FILE" ]; then
    # Say what IS there, since a path typed by hand usually goes wrong in
    # its last folder.
    msg="No such file: $FILE"
    dir=$FILE
    while [ -n "$dir" ] && [ ! -d "$dir" ]; do
        parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break; dir=$parent
    done
    if [ -d "$dir" ]; then
        near=$(ls "$dir" 2>/dev/null | grep -i -E '\.(ser|mj2)$' | head -5)
        if [ -n "$near" ]; then msg="$msg
In $dir:
$(printf '%s\n' "$near" | sed 's/^/    /')"
        else msg="$msg
$dir holds no .ser or .ser.mj2."; fi
    fi
    fail "$msg"
fi
NAME=$(basename "$FILE")

# A compressed archive and a raw capture are read differently but play the
# same way, so the difference is settled once, here.
case "$(printf '%s' "$NAME" | tr 'A-Z' 'a-z')" in *.mj2) ISARCHIVE=1 ;; *) ISARCHIVE=0 ;; esac
HAVEMETA=0
if [ $ISARCHIVE = 1 ]; then read_serz_box "$FILE" && HAVEMETA=1
else read_ser_header "$FILE" && HAVEMETA=1; fi

# Built as text rather than printed as it goes, because with -noconsole the
# same text has to go into a dialog instead.
REPORT=''
add() { REPORT="$REPORT$1
"; }
PIXFMT=''
SZ=$(fsize "$FILE")
if [ $HAVEMETA = 1 ] && [ $ISARCHIVE = 1 ]; then
    add "$NAME"
    add "  SERZ v$M_version, layout $M_layout - $(layout_name "$M_layout")"
    add "  $M_width x $M_height, $M_frames frames, $M_depth-bit, $M_planes plane(s) per frame"
    [ -n "$M_fps" ] && [ "$M_fps" != 0 ] && add "  captured at $M_fps fps"
    if [ "$M_origBytes" -gt 0 ]; then
        add "  $(calc "sprintf(\"%.2f MB, from %.2f MB (%.1f%%)\", $SZ/1048576, $M_origBytes/1048576, 100*$SZ/$M_origBytes)")"
    fi
elif [ $HAVEMETA = 1 ]; then
    PIXFMT=$(pixel_format)
    add "$NAME"
    add "  SER, $(color_name "$M_colorID"), $M_depth-bit"
    add "  $M_width x $M_height, $M_frames frames"
    [ -n "$M_fps" ] && [ "$M_fps" != 0 ] && add "  captured at $M_fps fps"
    add "  $(calc "sprintf(\"%.2f\", $SZ/1048576)") MB, played as $PIXFMT"
    [ -n "$BAYER" ] && add "  Bayer pattern overridden - the header says $(color_name "$M_colorID")"
    if [ "$M_colorID" -ge 16 ] && [ "$M_colorID" -le 19 ]; then
        add '  no demosaic exists for this filter array - shown as a grey mosaic'
    fi
    [ "$M_truncated" = 1 ] && add "  SHORT: the header claims more frames than the file holds - playing the $M_frames that are there"
elif [ $ISARCHIVE = 1 ]; then
    add "$NAME carries no readable SERZ box - it may be damaged, or not one of ours.  Playing it as an ordinary movie."
    M_planes=1; M_fps=0
else
    fail "$NAME does not look like a SER capture - its header has no usable width, height or frame count."
fi

# ---- which ffplay, and can it do the job? ----------------------------------
# Looked up before the report is shown, so -info answers "is this machine
# set up properly?" as well as "what is in this file?".
# With -info a missing ffplay is part of the answer, not a reason to stop.
select_ffplay || { [ $INFO = 1 ] || fail "$FFTROUBLE"; }

NONORMALIZE=0
if [ -n "$FF" ]; then
    add ''
    add "  ffplay ${CAP_version:-version unknown}"
    add "  $FF"
    if ! has_filter framestep; then
        add '  WARNING: this build has no "framestep" filter, so a 16-bit'
        add '           capture will play doubled, every second frame black.'
    fi
    if ! has_filter normalize; then
        NONORMALIZE=1
        add '  WARNING: this build has no "normalize" filter, so the picture'
        add '           will not be brightened and may look nearly black.'
        add "           Install a full FFmpeg:  $FFINSTALL"
    fi
fi

if [ $INFO = 1 ]; then
    [ -n "$FF" ] || add "
$FFTROUBLE"
elif [ "$NOCONSOLE" = 0 ]; then
    printf '%s' "$REPORT"
fi

# ---- the filter chain ------------------------------------------------------
# framestep rather than select='not(mod(n\,P))': same job, no comma to escape.
FILTERS=''
addf() { if [ -z "$FILTERS" ]; then FILTERS=$1; else FILTERS="$FILTERS,$1"; fi; }
if [ $ISARCHIVE = 1 ] && [ $HAVEMETA = 1 ]; then PLANES=$M_planes; else PLANES=1; fi

if [ $RAW = 0 ] && [ "$PLANES" -gt 1 ] && { has_filter framestep || [ -z "$FF" ]; }; then
    # The first plane of each frame is the picture in every layout that has
    # more than one: the quotient for layout 4, the high byte for 2 and 3,
    # red for 1.  The rest carry precision or colour that cannot be put back
    # together in a filter graph, so a grey preview is what this offers.
    addf "framestep=step=$PLANES"
fi

FPS=$RATE
if [ "$(calc "$FPS <= 0")" = 1 ] && [ -n "$M_fps" ] && [ "$M_fps" != 0 ]; then FPS=$M_fps; fi
if [ $RAW = 0 ] && [ "$(calc "$FPS > 0")" = 1 ] && [ $ISARCHIVE = 1 ]; then
    # Re-time to the capture rate.  Without this, dropping planes leaves the
    # kept frames on their original timestamps and the movie plays at
    # 30/planes fps - half speed on every 16-bit file.  Only for an archive:
    # a raw .ser gets its rate on the INPUT with -framerate instead.
    addf "setpts=N/($FPS*TB)"
fi

# -raw means "what a plain player would show", so it takes the stretch with
# it.  A build without the filter is skipped rather than allowed to fail.
if [ $NOSTRETCH = 0 ] && [ $RAW = 0 ] && [ $NONORMALIZE = 0 ]; then
    addf 'normalize=smoothing=10'
fi

# No -autoexit: a short capture is over in a second or two and a window that
# vanishes the moment you have found the file is not a viewer.  ffplay holds
# the last frame until q, and -loop runs it round again.
set -- -hide_banner -loglevel warning -window_title "$NAME  -  BiggSky SER Tools"
[ $LOOP = 1 ] && set -- "$@" -loop 0

INPUT=$FILE
if [ $ISARCHIVE = 0 ]; then
    # A raw capture has nothing in it to say what it is, so the demuxer has
    # to be told: the geometry, the pixel format from the SER header, and
    # where the frames start and stop.  Input options, so before the file.
    if [ "$(calc "$FPS > 0")" = 1 ]; then RAWFPS=$FPS; else RAWFPS=30; fi
    set -- "$@" -f rawvideo -pixel_format "$PIXFMT" \
                -video_size "${M_width}x${M_height}" -framerate "$RAWFPS"
    if [ -z "$FF" ] || has_protocol subfile; then
        # FFmpeg's subfile protocol hands the demuxer exactly the frames, as
        # a seekable stream, so it never sees the 178-byte header or the
        # timestamp trailer.  Left to read the whole file, rawvideo takes the
        # trailer as one more frame, finds it short, and prints "Packet
        # corrupt" and "Invalid buffer size" on the way out - alarming, and
        # the -t below does not stop it.  The option pairs are separated by
        # one comma and the list closed by two; the form in FFmpeg's own
        # documentation, with two between every pair, does not parse.
        INPUT="subfile,,start,178,end,$((178 + M_payload)),,:$FILE"
    else
        set -- "$@" -skip_initial_bytes 178 \
                    -t "$(calc "sprintf(\"%.3f\", $M_frames / $RAWFPS)")"
    fi
fi
[ -n "$FILTERS" ] && set -- "$@" -vf "$FILTERS"

if [ $INFO = 1 ]; then
    # The command, quoted so it can be pasted, for when ffplay itself is the
    # thing to argue with.
    cmd="${FF:-ffplay}"; for a in "$@" "$INPUT"; do cmd="$cmd '$a'"; done
    add ''
    add "  would run:"
    add "  $cmd"
    if [ "$NOCONSOLE" = 1 ]; then dialog "$REPORT"; else printf '%s' "$REPORT"; fi
    exit 0
fi

if [ "$NOCONSOLE" = 0 ]; then
    echo
    [ -n "$FILTERS" ] && echo "  filter: $FILTERS"
    echo '  space pauses, left/right seek, q quits'
    echo
fi

exec "$FF" "$@" "$INPUT"
