#!/bin/bash
#
# Copyright 2019 RnD Center "ELVEES", JSC
#
# This script tests Runtime Power Management support for VPU by starting
# an encoding process and checking if the VPU power domain state and the
# reference count are changed accordingly.

set -euo pipefail

vpu_refcnt() {
    refcnt=$(</sys/devices/platform/37100000.codec/driver/module/refcnt)
    return $refcnt
}

vpu_pd_is_enabled() {
    pd_status=$(($(devmem 0x3809508c) >> 2))
    return $pd_status
}

if ! vpu_refcnt; then
    echo "Test requires VPU to not be in use" > /dev/stderr
    exit 1
elif vpu_pd_is_enabled; then
    echo "VPU is not in use but the power domain is enabled" > /dev/stderr
    exit 1
fi

fc-avico -d 10 &
proc_id=$!

# Wait till file is generated, which means encoding started
while [ ! -e /tmp/fc-avico/encoded*.264 ]; do
    sleep 1
done

if vpu_refcnt || ! vpu_pd_is_enabled; then
    echo "VPU is not in use" > /dev/stderr
    exit 1
fi

kill $proc_id
wait $proc_id 2>/dev/null
sleep 1

if ! vpu_refcnt; then
    echo "VPU is still in use" > /dev/stderr
    exit 1
elif vpu_pd_is_enabled; then
    echo "VPU power domain is still enabled" > /dev/stderr
    exit 1
fi
