# Path: utils/files.py
# def write_timestamped_results(data):
#     fname = get_timestamped_fname()
#     with open(fname, 'w') as f:
#         f.write(data)
#     print('Wrote results to %s' % fname)
# 
# def write_results(data, path):
#     with open(path, 'w') as f:
#         f.write(data)
#     print('Wrote %s' % path)
# 
# Path: utils/process.py
# def run_gst_cmd(cmd):
#     try:
#         rc, stdout, stderr = run_cmd(cmd, shell=False)
#         took = parse_gst_execution_time(stdout)
#     except Exception as e:
#         print(e)
#         took = 0
#     return took
# 
# def run_cmd(cmd, shell=False):
#     env = dict(os.environ)
#     env["LANG"] = "C"
#     if shell:
#         args = cmd
#     else:
#         args = shlex.split(cmd)
#     p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
#     stdout, stderr = p.communicate()
#     rc = p.returncode
#     if rc != 0:
#         if '|' in cmd:
#             raise Exception('Command %s failed, maybe shell=True is required' %cmd)
#         else:
#             raise Exception('Command %s failed, error: %s' % (cmd, stderr))
#     elif contains_errors(stderr):
#         raise Exception('Command %s had an error' %cmd)
#     return rc, stdout, stderr
# 
# Path: utils/colors.py
# def print_red(text):
#     print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
# 
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
#     result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
#     if not result:
#         print('Plugin %s not found' % plugin_name)
#     return result
# 
# def get_gst_version():
#     return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]


import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results 
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red 
from utils.gstreamer import is_plugin_present, get_gst_version
    from utils.run import run_test
    MAX_BUFFERS = 1000

    # If set, will simulate live operation by setting sync=true on sinks
    # Will add more and more encoders until it takes longer to encode
    # than realtime
    ENABLE_LIVE = False

    # If set, instead of testing each available plugin one after another
    # will combine them to try to maximize performance
    ENABLE_PARALLEL_PLUGINS = False

    # If set, will compare the output with the input using qpsnr (ssim, psnr, ...)
    ENABLE_QUALITY_ANALYSIS = False
    # Available methods: psnr, avg_psnr, ssim, avg_ssim, see qpsnr -h for more info
    QUALITY_METHOD = 'avg_ssim'
    # Reference file path used for quality analysis (will be remuxed from the raw sample)
    RAW_REF_FILE = 'reference.mkv'
    # Subfolder which will contain rendered files (named after OUTPUT_FILE_TEMPLATE)
    OUTPUT_FOLDER = 'out'
    OUTPUT_FILE_TEMPLATE = 'output-%s.mkv'

    # each plugin is a list: ['plugin_name', 'plugin_bin_description'] 
    # available keys are
    # {bitrate_kb} : bitrate in kbits/s
    # {bitrate} : bitrate in bits/s
    # {keyframes} : GOP (set to 30)
    # {cpu_count} : dynamic, equals to the number of threads on the system
    PLUGINS = [
            ['x264enc', 'x264enc speed-preset=ultrafast bitrate={bitrate_kb} tune=zerolatency key-int-max={keyframes}'],
    ]

# Path: utils/files.py
# def write_timestamped_results(data):
#     fname = get_timestamped_fname()
#     with open(fname, 'w') as f:
#         f.write(data)
#     print('Wrote results to %s' % fname)
# 
# def write_results(data, path):
#     with open(path, 'w') as f:
#         f.write(data)
#     print('Wrote %s' % path)
# 
# Path: utils/process.py
# def run_gst_cmd(cmd):
#     try:
#         rc, stdout, stderr = run_cmd(cmd, shell=False)
#         took = parse_gst_execution_time(stdout)
#     except Exception as e:
#         print(e)
#         took = 0
#     return took
# 
# def run_cmd(cmd, shell=False):
#     env = dict(os.environ)
#     env["LANG"] = "C"
#     if shell:
#         args = cmd
#     else:
#         args = shlex.split(cmd)
#     p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
#     stdout, stderr = p.communicate()
#     rc = p.returncode
#     if rc != 0:
#         if '|' in cmd:
#             raise Exception('Command %s failed, maybe shell=True is required' %cmd)
#         else:
#             raise Exception('Command %s failed, error: %s' % (cmd, stderr))
#     elif contains_errors(stderr):
#         raise Exception('Command %s had an error' %cmd)
#     return rc, stdout, stderr
# 
# Path: utils/colors.py
# def print_red(text):
#     print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
# 
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
#     result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
#     if not result:
#         print('Plugin %s not found' % plugin_name)
#     return result
# 
# def get_gst_version():
#     return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]


# Path: common/encoding.py
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results 
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red 
from utils.gstreamer import is_plugin_present, get_gst_version
    from utils.run import run_test

    MAX_BUFFERS = 1000

    # If set, will simulate live operation by setting sync=true on sinks
    # Will add more and more encoders until it takes longer to encode
    # than realtime
    ENABLE_LIVE = False

    # If set, instead of testing each available plugin one after another
    # will combine them to try to maximize performance
    ENABLE_PARALLEL_PLUGINS = False

    # If set, will compare the output with the input using qpsnr (ssim, psnr, ...)
    ENABLE_QUALITY_ANALYSIS = False
    # Available methods: psnr, avg_psnr, ssim, avg_ssim, see qpsnr -h for more info
    QUALITY_METHOD = 'avg_ssim'
    # Reference file path used for quality analysis (will be remuxed from the raw sample)
    RAW_REF_FILE = 'reference.mkv'
    # Subfolder which will contain rendered files (named after OUTPUT_FILE_TEMPLATE)
    OUTPUT_FOLDER = 'out'
    OUTPUT_FILE_TEMPLATE = 'output-%s.mkv'

    # each plugin is a list: ['plugin_name', 'plugin_bin_description'] 
    # available keys are
    # {bitrate_kb} : bitrate in kbits/s
    # {bitrate} : bitrate in bits/s
    # {keyframes} : GOP (set to 30)
    # {cpu_count} : dynamic, equals to the number of threads on the system
    PLUGINS = [
            ['x264enc', 'x264enc speed-preset=ultrafast bitrate={bitrate_kb} tune=zerolatency key-int-max={keyframes}'],
    ]

    PLUGINS_INTEL = []