Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add time elapsed to enoding status tab #163

Merged
merged 4 commits into from
Jan 9, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions fastflix/command_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import re
import secrets
import shlex
import datetime
from pathlib import Path
from subprocess import PIPE
from threading import Thread
Expand All @@ -29,6 +30,7 @@ def __init__(self, log_queue):
self.success_detected = False
self.error_message = []
self.success_message = []
self.started_at = None

def start_exec(self, command, work_dir: str = None, shell: bool = False, errors=(), successes=()):
self.clean()
Expand All @@ -51,6 +53,8 @@ def start_exec(self, command, work_dir: str = None, shell: bool = False, errors=
encoding="utf-8",
)

self.started_at = datetime.datetime.now(datetime.timezone.utc)

Thread(target=self.read_output).start()

def start_piped_exec(self, command_one, command_two, work_dir, errors=(), successes=()):
Expand Down Expand Up @@ -82,6 +86,7 @@ def start_piped_exec(self, command_one, command_two, work_dir, errors=(), succes
)

self.error_detected = False
self.started_at = datetime.datetime.now(datetime.timezone.utc)

Thread(target=self.read_output).start()

Expand Down Expand Up @@ -145,6 +150,7 @@ def clean(self):
self.error_detected = False
self.success_detected = False
self.killed = False
self.started_at = None

def kill(self, log=True):
if self.process_two:
Expand Down
3 changes: 2 additions & 1 deletion fastflix/conversion_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,13 @@ def start_command():
logger.addHandler(new_file_handler)
prevent_sleep_mode()
currently_encoding = True
status_queue.put(("running", commands_to_run[0][0], commands_to_run[0][1]))
runner.start_exec(
commands_to_run[0][2],
work_dir=commands_to_run[0][3],
)

status_queue.put(("running", commands_to_run[0][0], commands_to_run[0][1], runner.started_at.isoformat()))

while True:
if currently_encoding and not runner.is_alive():
reusables.remove_file_handlers(logger)
Expand Down
7 changes: 7 additions & 0 deletions fastflix/data/languages.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1769,6 +1769,13 @@ Time Left:
ita: Tempo rimanente
spa: Tiempo restante
zho: 剩余时间
Time Elapsed:
deu: Verstrichene Zeit
eng: Time elapsed
fra: Temps écoulé
ita: Tempo trascorso
spa: Tiempo transcurrido
zho: 时间流逝
Title:
deu: Titel
eng: Title
Expand Down
11 changes: 11 additions & 0 deletions fastflix/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,14 @@ def clean_logs(signal, app, **_):
for file in compress:
file.unlink(missing_ok=True)
signal.emit(100)


def timedelta_to_str(delta):
if not isinstance(delta, (timedelta,)):
logger.warning(f"Wanted timedelta found but found {type(delta)}")
return "N/A"

output_string = str(delta)
output_string = output_string.split(".")[0] # Remove .XXX microseconds

return output_string
13 changes: 6 additions & 7 deletions fastflix/widgets/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1546,7 +1546,7 @@ def conversion_cancelled(self, data):
self.set_convert_button()

try:
video_uuid, command_uuid = data.split(":")
video_uuid, command_uuid, *_ = data.split("__")
cancelled_video = self.find_video(video_uuid)
except Exception:
return
Expand All @@ -1561,7 +1561,6 @@ def conversion_cancelled(self, data):
sm.exec_()
if sm.clickedButton().text() == t("Delete"):
try:
video_uuid, command_uuid = data.split(":")
cancelled_video = self.find_video(video_uuid)
cancelled_video.video_settings.output_path.unlink(missing_ok=True)
except OSError:
Expand Down Expand Up @@ -1595,7 +1594,7 @@ def dragMoveEvent(self, event):
def status_update(self, status):
logger.debug(f"Updating status from command worker: {status}")
try:
command, video_uuid, command_uuid = status.split(":")
command, video_uuid, command_uuid, *_ = status.split("__")
except ValueError:
logger.exception(f"Could not process status update from the command worker: {status}")
return
Expand Down Expand Up @@ -1670,16 +1669,16 @@ def run(self):
if status[0] == "complete":
self.main.completed.emit(0)
elif status[0] == "error":
self.main.status_update_signal.emit(":".join(status))
self.main.status_update_signal.emit("__".join(status))
self.main.completed.emit(1)
elif status[0] == "cancelled":
self.main.cancelled.emit(":".join(status[1:]))
self.main.status_update_signal.emit(":".join(status))
self.main.cancelled.emit("__".join(status[1:]))
self.main.status_update_signal.emit("__".join(status))
elif status[0] == "exit":
try:
self.terminate()
finally:
self.main.close_event.emit()
return
else:
self.main.status_update_signal.emit(":".join(status))
self.main.status_update_signal.emit("__".join(status))
67 changes: 64 additions & 3 deletions fastflix/widgets/panels/status_panel.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import logging
import re
import datetime
from datetime import timedelta

from qtpy import QtCore, QtWidgets
Expand All @@ -10,21 +11,25 @@
from fastflix.language import t
from fastflix.models.fastflix_app import FastFlixApp
from fastflix.models.video import Video
from fastflix.shared import time_to_number
from fastflix.shared import time_to_number, timedelta_to_str

logger = logging.getLogger("fastflix")


class StatusPanel(QtWidgets.QWidget):
speed = QtCore.Signal(str)
bitrate = QtCore.Signal(str)
signal_elapsed_time = QtCore.Signal(str)
benedicteb marked this conversation as resolved.
Show resolved Hide resolved

def __init__(self, parent, app: FastFlixApp):
super().__init__(parent)
self.app = app
self.main = parent.main
self.current_video: Video = None

self.started_at = None
self.time_elapsed_ticker_thread = ElapsedTimeTicker(self)

layout = QtWidgets.QGridLayout()

self.hide_nal = QtWidgets.QCheckBox(t("Hide NAL unit messages"))
Expand All @@ -33,13 +38,16 @@ def __init__(self, parent, app: FastFlixApp):
self.eta_label = QtWidgets.QLabel(f"{t('Time Left')}: N/A")
self.eta_label.setToolTip(t("Estimated time left for current command"))
self.eta_label.setStyleSheet("QLabel{margin-right:50px}")
self.time_elapsed_label = QtWidgets.QLabel(f"{t('Time Elapsed')}: N/A")
self.time_elapsed_label.setStyleSheet("QLabel{margin-right:50px}")
self.size_label = QtWidgets.QLabel(f"{t('Size Estimate')}: N/A")
self.size_label.setToolTip(t("Estimated file size based on bitrate"))

h_box = QtWidgets.QHBoxLayout()
h_box.addWidget(QtWidgets.QLabel(t("Encoder Output")), alignment=QtCore.Qt.AlignLeft)
h_box.addStretch(1)
h_box.addWidget(self.eta_label)
h_box.addWidget(self.time_elapsed_label)
h_box.addWidget(self.size_label)
h_box.addStretch(1)
h_box.addWidget(self.hide_nal, alignment=QtCore.Qt.AlignRight)
Expand All @@ -52,6 +60,8 @@ def __init__(self, parent, app: FastFlixApp):

self.speed.connect(self.update_speed)
self.bitrate.connect(self.update_bitrate)
self.signal_elapsed_time.connect(self.update_time_elapsed)
self.main.status_update_signal.connect(self.on_status_update)

def cleanup(self):
self.inner_widget.log_updater.terminate()
Expand Down Expand Up @@ -87,7 +97,7 @@ def update_speed(self, combined):
else:
if not speed:
self.eta_label.setText(f"{t('Time Left')}: N/A")
self.eta_label.setText(f"{t('Time Left')}: {data}")
self.eta_label.setText(f"{t('Time Left')}: {timedelta_to_str(data)}")

def update_bitrate(self, bitrate):
if not bitrate or bitrate.strip() == "N/A":
Expand All @@ -111,6 +121,40 @@ def update_bitrate(self, bitrate):
def update_title_bar(self):
pass

def set_started_at(self, msg):
try:
started_at = datetime.datetime.fromisoformat(msg.split("__")[-1])
except Exception as e:
logger.warning(f"Unable to parse start time - {str(e)}")
benedicteb marked this conversation as resolved.
Show resolved Hide resolved
return
benedicteb marked this conversation as resolved.
Show resolved Hide resolved

self.started_at = started_at

def update_time_elapsed(self):
now = datetime.datetime.now(datetime.timezone.utc)

if not self.started_at:
logger.warning("Unable to update time elapsed because start time isn't set")
return

try:
time_elapsed = now - self.started_at
except Exception as e:
logger.warning(f"Unable to calculate elapsed time - {str(e)}")
benedicteb marked this conversation as resolved.
Show resolved Hide resolved
return

self.time_elapsed_label.setText(f"{t('Time Elapsed')}: {timedelta_to_str(time_elapsed)}")

def on_status_update(self, msg):
update_type = msg.split("__")[0]

if update_type in ["complete", "cancelled", "error"]:
self.time_elapsed_ticker_thread.running = False
benedicteb marked this conversation as resolved.
Show resolved Hide resolved
self.time_elapsed_ticker_thread = ElapsedTimeTicker(self)
cdgriffith marked this conversation as resolved.
Show resolved Hide resolved
elif update_type == "running":
self.set_started_at(msg)
self.time_elapsed_ticker_thread.start()


class Logs(QtWidgets.QTextBrowser):
log_signal = QtCore.Signal(str)
Expand Down Expand Up @@ -163,6 +207,23 @@ def closeEvent(self, event):
self.hide()


class ElapsedTimeTicker(QtCore.QThread):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.running = True

def __del__(self):
self.wait()

def run(self):
while self.running:
self.parent.signal_elapsed_time.emit("tick")
benedicteb marked this conversation as resolved.
Show resolved Hide resolved
time.sleep(0.3)
benedicteb marked this conversation as resolved.
Show resolved Hide resolved

logger.debug("Time elapsed ticker exited")


class LogUpdater(QtCore.QThread):
def __init__(self, parent, log_queue):
super().__init__(parent)
Expand Down