# these functions are appended to an include file that is sent to gtkdialog and allows for functions to be used within gtkdialog actions

# functions

_check_ffmpeg_install(){
    echo "Using ffmpeg at ${FFMPEG_BIN}"
    echo
    if [ ! -f "${FFMPEG_BIN}" ] ; then
        echo "${FFMPEG_BIN} is not found. Please install ffmpeg-ma via:"
        echo "    brew install mediaarea/mediaarea/ffmpeg-ma"
        echo "Or install a version of ffmpeg that is compiled with decklink support if you wish to use that input."
        echo
    fi
    if [ ! -f "${FFPLAY_BIN}" ] ; then
        echo "${FFPLAY_BIN} is not found."
        echo
    fi
    if [ ! -f "${FFPROBE_BIN}" ] ; then
        echo "${FFPROBE_BIN} is not found."
        echo
    fi
    echo
    FFMPEG_V="$("${FFMPEG_BIN}" -version 2>&1)"
    echo "FFmpeg configuration: ${FFMPEG_V}"
    echo
    if [ "$(echo "${FFMPEG_V}" | grep "Library not loaded" >/dev/null)" ] ; then
        echo "Please reinstall 'ffmpeg-ma':"
        echo "    brew reinstall mediaarea/mediaarea/ffmpeg-ma"
        echo "Or install a version of ffmpeg that is compiled with decklink support if you wish to use that input."
        echo "Exiting."
        exit 1
    fi
    if [ -z "$("${FFMPEG_BIN}" -nostdin -v 0 -sources decklink)" ] ; then
        echo "vrecord is set to use a decklink input but ${FFMPEG_BIN} does not appear to support decklink inputs."
        echo "Please review installation and troubleshooting information for vrecord or install ffmpeg-ma."
        exit 1
    fi
}

_update_config_file(){
    # write config file
    {
        echo "# Set these variables to a valid option or leave as empty quotes (like \"\") to request each run."
        echo "STARTUP_VIEW=\"${STARTUP_VIEW}\""
        echo "DEVICE_INPUT_CHOICE=\"${DEVICE_INPUT_CHOICE}\""
        echo "VIDEO_INPUT_CHOICE=\"${VIDEO_INPUT_CHOICE}\""
        echo "AUDIO_INPUT_CHOICE=\"${AUDIO_INPUT_CHOICE}\""
        echo "CONTAINER_CHOICE=\"${CONTAINER_CHOICE}\""
        echo "VIDEO_CODEC_CHOICE=\"${VIDEO_CODEC_CHOICE}\""
        echo "FFV1_SLICE_CHOICE=\"${FFV1_SLICE_CHOICE}\""
        echo "AUDIO_CODEC_CHOICE=\"${AUDIO_CODEC_CHOICE}\""
        echo "AUDIO_DEV_CHOICE=\"${AUDIO_DEV_CHOICE}\""
        echo "AUDIO_MODE_CODEC_CHOICE=\"${AUDIO_MODE_CODEC_CHOICE}\""
        echo "AUDIO_CHANNEL_CHOICE=\"${AUDIO_CHANNEL_CHOICE}\""
        echo "AUDIO_MODE_SR_CHOICE=\"${AUDIO_MODE_SR_CHOICE}\""
        echo "VIDEO_BIT_DEPTH_CHOICE=\"${VIDEO_BIT_DEPTH_CHOICE}\""
        echo "ASPECT_RATIO_CHOICE=\"${ASPECT_RATIO_CHOICE}\""
        echo "NTSC_43_SAR_CHOICE=\"${NTSC_43_SAR_CHOICE}\""
        echo "NTSC_169_SAR_CHOICE=\"${NTSC_169_SAR_CHOICE}\""
        echo "PAL_43_SAR_CHOICE=\"${PAL_43_SAR_CHOICE}\""
        echo "PAL_169_SAR_CHOICE=\"${PAL_169_SAR_CHOICE}\""
        echo "AUDIO_MAPPING_CHOICE=\"${AUDIO_MAPPING_CHOICE}\""
        echo "TIMECODE_CHOICE=\"${TIMECODE_CHOICE}\""
        echo "STANDARD_CHOICE=\"${STANDARD_CHOICE}\""
        echo "QCTOOLSXML_CHOICE=\"${QCTOOLSXML_CHOICE}\""
        echo "MP4_CHOICE=\"${MP4_CHOICE}\""
        echo "FRAMEMD5_CHOICE=\"${FRAMEMD5_CHOICE}\""
        echo "EMBED_LOGS_CHOICE=\"${EMBED_LOGS_CHOICE}\""
        echo "PLAYBACKVIEW_CHOICE=\"${PLAYBACKVIEW_CHOICE}\""
        echo "PLAYBACKVIEW_CHOICE_PASS=\"${PLAYBACKVIEW_CHOICE_PASS}\""
        echo "DIR=\"${DIR}\""
        echo "LOGDIR=\"${LOGDIR}\""
        echo "INVERT_PHASE=\"${INVERT_PHASE}\""
        echo "DURATION=\"${DURATION}\""
        echo "PREFIX=\"${PREFIX}\""
        echo "USER_SUFFIX=\"${USER_SUFFIX}\""
        echo "YES_SUFFIX=\"${YES_SUFFIX}\""
        echo "TECHNICIAN=\"${TECHNICIAN}\""
        echo "DVRESCUE_INPUT_CHOICE=\"${DVRESCUE_INPUT_CHOICE}\""
        echo "DECKLINK_INPUT_CHOICE=\"${DECKLINK_INPUT_CHOICE}\""
        echo "DECKLINK_UTILITY_CHOICE=\"${DECKLINK_UTILITY_CHOICE}\""
        echo "WAVEFORM_SCALE_CHOICE=\"${WAVEFORM_SCALE_CHOICE}\""
        echo "MONITOR_AUDIO_CHOICE=\"${MONITOR_AUDIO_CHOICE}\""
        echo "SIGNAL_VIEW_CHOICE=\"${SIGNAL_VIEW_CHOICE}\""
        echo "DV_CONTAINER_CHOICE=\"${DV_CONTAINER_CHOICE}\""
        echo "DV_RESCUE_OPTION_S=\"${DV_RESCUE_OPTION_S}\""
        echo "DV_RESCUE_OPTION_D=\"${DV_RESCUE_OPTION_D}\""
        echo "DV_RESCUE_OPTION_T=\"${DV_RESCUE_OPTION_T}\""
        echo "DV_RESCUE_OPTION_TC=\"${DV_RESCUE_OPTION_TC}\""
        echo "CC2VTT=\"${CC2VTT}\""
        echo "CC2SRT=\"${CC2SRT}\""
        echo "HD_CHOICE=\"${HD_CHOICE}\""
    } > "${CONFIG_FILE}"
    . "${CONFIG_FILE}"
}

_validate_form(){
    if [ "${VIDEO_CODEC_CHOICE}" = "FFV1 version 3" ] && [ "${CONTAINER_CHOICE}" = "MXF" ] ; then
        echo "ERROR: Incompatible video codecs and containers have been selected."
    elif [ "${VIDEO_CODEC_CHOICE}" = "FFV1 version 3" ] && [ "${CONTAINER_CHOICE}" = "MP4" ] ; then
        echo "ERROR: Incompatible video codecs and containers have been selected."
    elif [ "${AUDIO_CODEC_CHOICE}" = "24-bit FLAC" ] && [ "${CONTAINER_CHOICE}" = "QuickTime" ] ; then
        echo "ERROR: Incompatible audio codecs and containers have been selected."
    elif [ "${MP4_CHOICE}" = "true" ] && [ "${CONTAINER_CHOICE}" = "MP4" ] ; then
        echo "ERROR: You can't use MP4 for both the access copy option and the preservation copy. Too much MP4."
    fi
    if [ -z "${DIR}" ] ; then
        NEW_DEFAULT_DIR="$(pwd)"
        echo "WARNING: The recording directory is not set. ${NEW_DEFAULT_DIR} will be used."
        DIR="${NEW_DEFAULT_DIR}"
    fi
    if [ -d "${DIR}" ] ; then
        if [ $(mount | grep $(df -P "${DIR}" | tail +2 | awk '{print $1}') | grep -c "(.*local,") = "0" ] && [ "${OS_TYPE}" != "linux" ] ; then
            echo "WARNING: The recording directory at ${DIR} is not a local directory. Please verify that you can write to the disk fast enough."
        fi
        if [ "${OS_TYPE}" = "linux" ] ; then
            FREE_SPACE="$(df -BG "${DIR}" | tail +2 | awk '{print $4}' | tr 'G' ' ')"
        else
            FREE_SPACE="$(df -g "${DIR}" | tail +2 | awk '{print $4}')"
        fi
        if [ "${FREE_SPACE}" -le 40 ] ; then
            echo "WARNING: The recording directory at ${DIR} only has ${FREE_SPACE} gigabytes available."
        fi
    else
        echo "ERROR: The recording directory (${DIR}) does not exist. Please set or $(pwd) will be used instead."
    fi
    if [ ! -d "${LOGDIR}" ] && [ -n "${LOGDIR}" ] ; then
        echo "ERROR: The auxiliary directory (${LOGDIR}) does not exist. Create this folder or leave blank to use the recording directory."
    fi
    # validate duration
    if [ -n "${DURATION}" ] ; then
        if ! [ "$(echo "${DURATION} > 0" | bc)" = "1" ] ; then
            echo "ERROR: Illegal value for recording time. The duration must be a positive number."
        fi
    fi
    if [ "${VIDEO_CODEC_CHOICE}" = "ProRes" -o "${VIDEO_CODEC_CHOICE}" = "ProRes (HQ)" ] && [ "${VIDEO_BIT_DEPTH_CHOICE}" = "8 bit" ] ; then
        echo "WARNING: ProRes (which is a 10 bit encoding) is selected but the input device is set to use 8 bits."
    fi
    if [ "${VIDEO_CODEC_CHOICE}" = "h264" ] ; then
        echo "WARNING: For licensing compatability, vrecord records h264 using libopenh264 which only supports progressive encoding. To preserve interlacement metadata select another encoding."
    fi
    if [ "${INVERT_PHASE_2}" = "true" ] ; then
        echo "WARNING: Option to invert phase of second audio channel has been selected."
    fi
    if [ "${INVERT_PHASE_4}" = "true" ] ; then
        echo "WARNING: Option to invert phase of fourth audio channel has been selected."
    fi

    if [ "${STANDARD_CHOICE}" = "Hi59" ] && [ "${PLAYBACKVIEW_CHOICE}" != "Unfiltered" ] ; then
        echo "WARNING: For playback of HD signals, we recommend the 'Unfiltered' view."
    fi
    if [ "${STANDARD_CHOICE}" = "Hi59" ] && [ "${ASPECT_RATIO_CHOICE}" != "16/9" ] ; then
        echo "WARNING: We noticed that you're recording Hi59 but to ${ASPECT_RATIO_CHOICE} rather than 16/9. Maybe it's fine, just noting."
    fi

    if [ "${SIGNAL_INT_CHOICE}" != "auto" ] && [ -n "${SIGNAL_INT_CHOICE}" ] ; then
        echo "WARNING: The configuration ignores the interlacement of the input and forces it to ${SIGNAL_INT_CHOICE}. Set to 'auto' if you prefer to keep the interlacement as the device describes it."
    fi
}

_get_output_filename(){
    # Get user suffix preference of default per video codec
    if [[ -z "${DIR}" ]] ; then
        DIR="$(pwd)"
    fi
    if [ "${YES_SUFFIX}" = 'true' ] ; then
        SUFFIX=""
        if [ -n "${USER_SUFFIX}" ] ; then
            SUFFIX="${USER_SUFFIX}"
        elif [ "${DEVICE_INPUT_CHOICE}" = "0" ] ; then
            case "${VIDEO_CODEC_CHOICE}" in
                "FFV1 version 3")   SUFFIX="_ffv1" ;;
                "JPEG2000")         SUFFIX="_j2k" ;;
                "ProRes")           SUFFIX="_prores" ;;
                "ProRes (HQ)")      SUFFIX="_prores" ;;
                "h264")             SUFFIX="_h264" ;;
                "HuffYUV")          SUFFIX="_huff" ;;
            esac
        fi
    fi

    # Get extension by container choice
    if [ "${DEVICE_INPUT_CHOICE}" = "0" ] ; then
        case "${CONTAINER_CHOICE}" in
            "Matroska")             EXTENSION="mkv" ;;
            "QuickTime")            EXTENSION="mov" ;;
            "AVI")                  EXTENSION="avi" ;;
            "MXF")                  EXTENSION="mxf" ;;
            "MP4")                  EXTENSION="mp4" ;;
        esac
    elif [ "${DEVICE_INPUT_CHOICE}" = "1" ] ; then
        EXTENSION="dv"
    elif [ "${DEVICE_INPUT_CHOICE}" = "2" ] ; then
        case "${AUDIO_MODE_CODEC_CHOICE}" in
            "24-bit PCM")           EXTENSION="wav" ;;
            "24-bit FLAC")          EXTENSION="flac" ;;
        esac
    fi

    echo "${DIR}/${PREFIX}${ID}${SUFFIX}.${EXTENSION}"
}

_get_decklink_input_list(){
    # get information on what input device options are available
    #unset DECKLINK_DEVICES
    "${FFMPEG_BIN}" -nostdin -v 0 -sources decklink | awk -F'[][]' '{print $2}' | grep -v "^$"
}

_get_format_list(){
    if [ -z ${HD_CHOICE} ] ; then
        . "${CONFIG_FILE}"
    fi
    if [ ${HD_CHOICE} != "true" ] ; then
      echo "NTSC
PAL"
    else
        echo "NTSC
PAL
23ps - 1080p23.98
24ps - 1080p24
Hp25 - 1080p25
Hp29 - 1080p29.97
Hp30 - 1080p30
Hi50 - 1080i50
Hi59 - 1080i59.94
Hi60 - 1080i60
hp50 - 720p50
hp59 - 720p59.94
hp60 - 720p60"
    fi
}

_get_dvrescue_input_list(){
    # set dvrescue input options
    unset DVRESCUE_DEVICES
    dvrescue -list_devices | grep "\[DV\]"
    if [ "${OS_TYPE}" = "linux" ] ; then
        echo "FFmpeg iec61883 Default"
    fi
}

_get_audio_device_list(){
    if [ "${OS_TYPE}" = "linux" ] ; then
        arecord -l | grep -E '\[.*\]' | cut -d ':' -f1-2 | awk '{$1=$1;print}'
    elif [ "${OS_TYPE}" = "macOS" ] ; then
        "${FFMPEG_BIN}" -nostdin -hide_banner -f avfoundation -list_devices 1 -i dummy 2>&1 | grep -A 10 "AVFoundation audio devices" | grep -o "\[[0-9]\].*" | cut -d " " -f2-
    fi
}

_get_summary(){
    if [[ ! -f "${CONFIG_FILE}" ]] ; then
        echo "VRecord configuration file is missing, please visit the Settings panel."
    else
        . "${CONFIG_FILE}"
        if [ "${DEVICE_INPUT_CHOICE}" = "0" ] ; then
            echo "Device Input: Decklink"
            echo "Settings: ${VIDEO_CODEC_CHOICE} ${VIDEO_BIT_DEPTH_CHOICE} ${CONTAINER_CHOICE} File"
            echo "from ${VIDEO_INPUT_CHOICE} video input and ${AUDIO_INPUT_CHOICE} audio input"
            echo "Audio channel mapping: ${AUDIO_MAPPING_CHOICE}"
            echo "Recording audio to ${AUDIO_CODEC_CHOICE}"
            echo "Input utility: ${DECKLINK_UTILITY_CHOICE}"
            echo "Timecode format: ${TIMECODE_CHOICE}"
            echo "Standard: ${STANDARD_CHOICE}"
            echo "Inputs recorded to ${DIR}"
            echo "Auxiliary files created in ${LOGDIR}"
            echo "Access MP4: ${MP4_CHOICE}"
            echo "Frame MD5s: ${FRAMEMD5_CHOICE}"
            echo "QCTools XML: ${QCTOOLSXML_CHOICE}"
            echo "Playback: ${PLAYBACKVIEW_CHOICE} view (for recording) and ${PLAYBACKVIEW_CHOICE_PASS} view (for passthrough)"
        elif [ "${DEVICE_INPUT_CHOICE}" = "1" ] ; then
            echo "Device Input: DV"
            echo "Copying video from ${DVRESCUE_INPUT_CHOICE}."
            echo "Inputs recorded to ${DIR}"
            echo "Auxiliary files created in ${LOGDIR}"
        elif [ "${DEVICE_INPUT_CHOICE}" = "2" ] ; then
            echo "Device Input: Audio"
            echo "Recording audio from ${AUDIO_DEV_CHOICE}."
            echo "Audio codec: ${AUDIO_MODE_CODEC_CHOICE}"
            echo "${AUDIO_CHANNEL_CHOICE} channels"
            echo "Sampling rate: ${AUDIO_MODE_SR_CHOICE} "
            echo "Inputs recorded to ${DIR}"
            echo "Auxiliary files created in ${LOGDIR}"
        fi
    fi
}
