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 all 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))
89 changes: 86 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,20 +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)
tick_signal = QtCore.Signal()

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.ticker_thread = ElapsedTimeTicker(self, self.main.status_update_signal, self.tick_signal)
self.ticker_thread.start()

layout = QtWidgets.QGridLayout()

Expand All @@ -33,13 +39,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,9 +61,12 @@ def __init__(self, parent, app: FastFlixApp):

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

def cleanup(self):
self.inner_widget.log_updater.terminate()
self.ticker_thread.stop_signal.emit()

def get_movie_length(self):
if not self.current_video:
Expand Down Expand Up @@ -87,7 +99,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 +123,37 @@ 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:
logger.exception("Unable to parse start time, assuming it was now")
self.started_at = datetime.datetime.now(datetime.timezone.utc)
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:
logger.exception("Unable to calculate elapsed time")
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 == "running":
self.set_started_at(msg)


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


class ElapsedTimeTicker(QtCore.QThread):
stop_signal = QtCore.Signal()

def __init__(self, parent, status_update_signal, tick_signal):
super().__init__(parent)
self.parent = parent
self.tick_signal = tick_signal

self.send_tick_signal = False
self.stop_received = False

status_update_signal.connect(self.on_status_update)
self.stop_signal.connect(self.on_stop)

def __del__(self):
self.wait()

def run(self):
while not self.stop_received:
time.sleep(0.2)

if not self.send_tick_signal:
continue

self.tick_signal.emit()

logger.debug("Ticker thread stopped")

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

if update_type in ["complete", "cancelled", "error"]:
self.send_tick_signal = False
elif update_type == "running":
self.send_tick_signal = True

def on_stop(self):
self.stop_received = True


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