Page 1 of 1

Parsing FFprobe XML in BASH

Posted: Fri Jan 08, 2016 4:49 am
by peter_b
HowTo parse an FFprobe XML file in a BASH script, using XMLStarlet:

Code: Select all

function parse_ffprobe_xml
{
    local XML_FILE="$1"
    local CODEC_TYPE="$2"

    local XPATH_QUERY="/ffprobe/streams/stream[@codec_type='$CODEC_TYPE']"

    PROBED_PIXFMT=$($XMLSTARLET sel -t -v "$XPATH_QUERY/@pix_fmt" "$XML_FILE")
    PROBED_WIDTH=$($XMLSTARLET sel -t -v "$XPATH_QUERY/@width" "$XML_FILE")
    PROBED_FPS=$($XMLSTARLET sel -t -v "$XPATH_QUERY/@r_frame_rate" "$XML_FILE")
    PROBED_DURATION=$($XMLSTARLET sel -t -v "$XPATH_QUERY/@duration" "$XML_FILE")
    PROBED_DURATION_TS=$($XMLSTARLET sel -t -v "$XPATH_QUERY/@duration_ts" "$XML_FILE")

    # Round FPS to 3 digits after the comma:
    ROUNDED_FPS=$(echo "scale=3;$PROBED_FPS" | bc -l)

    # Round duration to nanoseconds (=9 digits):
    ROUNDED_DURATION=$(echo "scale=9;$PROBED_DURATION/1" | bc -l)
}

Parsing VMD/METS XML in BASH

Posted: Fri Jan 08, 2016 4:51 am
by peter_b
HowTo parse the Library of Congress' "Video Metadata" (VMD.psd) values stored in a METS XML file, using a BASH script and XMLStarlet:

Code: Select all

##
# Parse a video METS file, extract certain values from the XML
# and export them as BASH variables.
#
# Currently parsed:
#   METS_ASPECT_RATIO: Aspect ratio of video
#   METS_WIDTH:        Pixel width of video
#   METS_FPS:          Frames per second of video
#
function parse_mets_xml
{
    local METS_FILE="$1"
    local XPATH_VIDEO_INFO="/mets/amdSec/techMD/mdWrap/xmlData/VIDEOMD/video_info"

    if [[ ! -e "$METS_FILE" || ! -s "$METS_FILE" ]]; then
        ERROR_MSG="ERROR: Invalid METS filename given ($METS_FILE)"
        return 1
    fi

    # Select whatever values you like from the METS XML using "xmlstarlet" and XPath expressions:
    METS_ASPECT_RATIO=$($XMLSTARLET sel -t -v "$XPATH_VIDEO_INFO/aspect_ratio" "$METS_FILE")
    METS_WIDTH=$($XMLSTARLET sel -t -v "$XPATH_VIDEO_INFO/frame/pixels_horizontal" "$METS_FILE")
    METS_FPS=$($XMLSTARLET sel -t -v "$XPATH_VIDEO_INFO/frame/frame_rate" "$METS_FILE")
}