# 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
                                                # Assuming that encoders should not be late by more than 1 sec 
                                                if int(took) > realtime_duration:
                                                    # If multiple passes are expected, run at least twice
                                                    if self.PASS_COUNT == 1 or (self.PASS_COUNT > 1 and i > 0):
                                                        print('Slower than realtime, aborting next tests')
                                                        abort = True
                                                    else:
                                                        print('Slower than realtime, trying again')
                                        else:
                                            fps = 0
                                        fps_results.append(fps)
                                    sample_desc = "%s-%sch" % (sample, channel_count)
                                    mean_fps = int(round(mean(fps_results)))
                                    variation_fps = int(max(max(fps_results) - mean_fps, mean_fps - min(fps_results)))
                                    result = "%s\t%s\t%s\t%s" %(plugin_string, sample_desc, mean_fps, variation_fps)
                                    if self.ENABLE_QUALITY_ANALYSIS:
                                        result += '\t%.2f\t%.2f\t%s' %(quality, min(min_quality_results), quality_log)
                                    info += "\n%s" %result
                                    success = True
        if os.path.exists(self.RAW_BUF_FILE):
            os.remove(self.RAW_BUF_FILE)
        write_timestamped_results(info)
        return (success, info)

    def get_quality_score(self, raw_caps, framerate, files):
        print('Running quality analysis with %s' % self.QUALITY_METHOD)
        muxed_raw_file = os.path.join(self.OUTPUT_FOLDER, self.RAW_REF_FILE)
        cmd = 'gst-launch-1.0 filesrc location=%s ! %s ! matroskamux ! filesink location=%s' % (self.RAW_BUF_FILE, raw_caps, muxed_raw_file)
        rc, stdout, stderr = run_cmd(cmd)
        cmd = 'qpsnr -a %s -o fps=%s -r %s %s' % (self.QUALITY_METHOD, framerate, muxed_raw_file, ' '.join([os.path.join(self.OUTPUT_FOLDER, f) for f in files]))

# 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

                                                # Assuming that encoders should not be late by more than 1 sec 
                                                if int(took) > realtime_duration:
                                                    # If multiple passes are expected, run at least twice
                                                    if self.PASS_COUNT == 1 or (self.PASS_COUNT > 1 and i > 0):
                                                        print('Slower than realtime, aborting next tests')
                                                        abort = True
                                                    else:
                                                        print('Slower than realtime, trying again')
                                        else:
                                            fps = 0
                                        fps_results.append(fps)
                                    sample_desc = "%s-%sch" % (sample, channel_count)
                                    mean_fps = int(round(mean(fps_results)))
                                    variation_fps = int(max(max(fps_results) - mean_fps, mean_fps - min(fps_results)))
                                    result = "%s\t%s\t%s\t%s" %(plugin_string, sample_desc, mean_fps, variation_fps)
                                    if self.ENABLE_QUALITY_ANALYSIS:
                                        result += '\t%.2f\t%.2f\t%s' %(quality, min(min_quality_results), quality_log)
                                    info += "\n%s" %result
                                    success = True
        if os.path.exists(self.RAW_BUF_FILE):
            os.remove(self.RAW_BUF_FILE)
        write_timestamped_results(info)
        return (success, info)

    def get_quality_score(self, raw_caps, framerate, files):
        print('Running quality analysis with %s' % self.QUALITY_METHOD)
        muxed_raw_file = os.path.join(self.OUTPUT_FOLDER, self.RAW_REF_FILE)
        cmd = 'gst-launch-1.0 filesrc location=%s ! %s ! matroskamux ! filesink location=%s' % (self.RAW_BUF_FILE, raw_caps, muxed_raw_file)
        rc, stdout, stderr = run_cmd(cmd)
        cmd = 'qpsnr -a %s -o fps=%s -r %s %s' % (self.QUALITY_METHOD, framerate, muxed_raw_file, ' '.join([os.path.join(self.OUTPUT_FOLDER, f) for f in files]))

        rc, stdout, stderr = run_cmd(cmd)