1 /***********************************************************************
2 
3                           C I N E   E N C O D E R
4                                 JULY, 2020
5                             COPYRIGHT (C) 2020
6 
7  FILE: mainwindow.cpp
8  MODIFIED: November, 2021
9  COMMENT:
10  LICENSE: GNU General Public License v3.0
11 
12 ***********************************************************************/
13 
14 #include "mainwindow.h"
15 #include "ui_mainwindow.h"
16 #include "about.h"
17 #include "donate.h"
18 #include "settings.h"
19 #include "preset.h"
20 #include "taskcomplete.h"
21 #include "dialog.h"
22 
23 
24 #if defined (Q_OS_UNIX)
25     #ifndef UNICODE
26         #define UNICODE
27     #endif
28     #include <unistd.h>
29     #include <signal.h>
30     #include <MediaInfo/MediaInfo.h>
31     using namespace MediaInfoLib;
32 #elif defined(Q_OS_WIN64)
33     #ifdef __MINGW64__
34         #ifdef _UNICODE
35             #define _itot _itow
36         #else
37             #define _itot itoa
38         #endif
39     #endif
40     #include <windows.h>
41     #include "MediaInfoDLL/MediaInfoDLL.h"
42     using namespace MediaInfoDLL;
43 #endif
44 
45 
46 
Widget(QWidget * parent)47 Widget::Widget(QWidget *parent):
48     QWidget(parent),
49     ui(new Ui::Widget),
50     _windowActivated(false)
51 {
52     ui->setupUi(this);
53 #ifdef Q_OS_WIN64
54     this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint |
55                          Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint);
56 #else
57     this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
58 #endif
59     this->setMouseTracking(true);
60     this->setAcceptDrops(true);
61 
62     // **************************** Set front label ***********************************//
63 
64     QHBoxLayout *raiseLayout = new QHBoxLayout(ui->tableWidget);
65     ui->tableWidget->setLayout(raiseLayout);
66     raiseThumb = new QLabel(ui->tableWidget);
67     raiseLayout->addWidget(raiseThumb);
68     raiseThumb->setAlignment(Qt::AlignCenter);
69     raiseThumb->setText(tr("No media"));
70     raiseThumb->setStyleSheet("color: #09161E; font: 64pt; font-style: oblique;");
71 
72     audioThumb = new QLabel(ui->frameTab_2);
73     ui->gridLayoutAudio->addWidget(audioThumb);
74     audioThumb->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
75     audioThumb->setAlignment(Qt::AlignCenter);
76     audioThumb->setText(tr("No audio"));
77     audioThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
78 
79     subtitleThumb = new QLabel(ui->frameTab_3);
80     ui->gridLayoutSubtitle->addWidget(subtitleThumb);
81     subtitleThumb->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
82     subtitleThumb->setAlignment(Qt::AlignCenter);
83     subtitleThumb->setText(tr("No subtitle"));
84     subtitleThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
85 
86     // **************************** Create docks ***********************************//
87 
88     QGridLayout *layout = new QGridLayout(ui->frame_middle);
89     ui->frame_middle->setLayout(layout);
90     window = new QMainWindow(ui->frame_middle);
91     layout->addWidget(window);
92     layout->setContentsMargins(6, 2, 6, 2);
93     layout->setVerticalSpacing(0);
94     layout->setHorizontalSpacing(0);
95     window->setObjectName("CentralWindow");
96     window->setWindowFlags(Qt::Widget);
97     window->setDockNestingEnabled(true);
98     centralWidget = new QWidget(window);
99     centralWidget->setObjectName("centralwidget");
100     window->setCentralWidget(centralWidget);
101 
102     QGridLayout *centralwidgetLayout = new QGridLayout(centralWidget);
103     centralWidget->setLayout(centralwidgetLayout);
104     centralwidgetLayout->addWidget(ui->frame_task);
105     centralwidgetLayout->setContentsMargins(0, 0, 0, 0);
106 
107     QList<QString> dockNames = {tr("Presets"), tr("Preview"), tr("Source"), tr("Output"),
108                                 tr("Streams"), tr("Log"), tr("Metadata"), tr("Split")};
109     QList<Qt::DockWidgetArea> dockArea = {Qt::LeftDockWidgetArea, Qt::BottomDockWidgetArea,
110                                           Qt::BottomDockWidgetArea, Qt::BottomDockWidgetArea,
111                                           Qt::RightDockWidgetArea, Qt::RightDockWidgetArea,
112                                           Qt::RightDockWidgetArea, Qt::RightDockWidgetArea};
113     QList<QString> objNames = {"Dock_presets", "Dock_preview", "Dock_source", "Dock_output",
114                                "Dock_options", "Dock_log", "Dock_metadata", "Dock_split"};
115     QList<QFrame*> dockFrames= {ui->frameLeft, ui->frame_preview, ui->frame_source, ui->frame_output,
116                                 ui->frameRight, ui->frameLog, ui->frameMetadata, ui->frameSplit};
117     QWidget *arrWidgets[DOCKS_COUNT];
118     QGridLayout *arrLayout[DOCKS_COUNT];
119     for (int ind = 0; ind < DOCKS_COUNT; ind++) {
120         docks[ind] = new QDockWidget(dockNames.at(ind), window);
121         docks[ind]->setObjectName(objNames[ind]);
122         docks[ind]->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
123         docks[ind]->setFeatures(QDockWidget::AllDockWidgetFeatures);
124         arrWidgets[ind] = new QWidget(docks[ind]);
125         arrWidgets[ind]->setObjectName(QString("dockWidgetContents_") + QString::number(ind));
126         docks[ind]->setWidget(arrWidgets[ind]);
127         window->addDockWidget(dockArea[ind], docks[ind]);
128         arrLayout[ind] = new QGridLayout(arrWidgets[ind]);
129         arrWidgets[ind]->setLayout(arrLayout[ind]);
130         arrLayout[ind]->addWidget(dockFrames[ind]);
131         arrLayout[ind]->setContentsMargins(0, 0, 0, 0);
132         arrLayout[ind]->setHorizontalSpacing(0);
133         arrLayout[ind]->setVerticalSpacing(0);
134     }
135 
136     // **************************** Set Event Filters ***********************************//
137 
138     ui->centralwidget->installEventFilter(this);
139     ui->centralwidget->setAttribute(Qt::WA_Hover, true);
140     ui->frame_main->installEventFilter(this);
141     ui->frame_main->setAttribute(Qt::WA_Hover, true);
142     ui->frame_main->setAttribute(Qt::WA_NoMousePropagation, true);
143     ui->frame_top->installEventFilter(this);
144     raiseThumb->installEventFilter(this);
145 }
146 
~Widget()147 Widget::~Widget()
148 {
149     delete ui;
150 }
151 
showEvent(QShowEvent * event)152 void Widget::showEvent(QShowEvent *event)   /*** Call set parameters ***/
153 {
154     QWidget::showEvent(event);
155     if (!_windowActivated) {
156         _windowActivated = true;
157         std::cout << "Window Activated ..." << std::endl;
158         setParameters();
159     }
160 }
161 
closeEvent(QCloseEvent * event)162 void Widget::closeEvent(QCloseEvent *event) /*** Show prompt when close app ***/
163 {
164     event->ignore();
165     if (call_dialog(tr("Quit program?"))) {
166 
167         if (processEncoding->state() != QProcess::NotRunning) processEncoding->kill();
168         if (processThumbCreation->state() != QProcess::NotRunning) processThumbCreation->kill();
169 
170         QFile _prs_file(_preset_file);
171         if (_prs_file.open(QIODevice::WriteOnly)) {
172             QDataStream out(&_prs_file);
173             out.setVersion(QDataStream::Qt_4_0);
174             out << PRESETS_VERSION;
175             out << _cur_param << _pos_top << _pos_cld << _preset_table;
176             _prs_file.close();
177         }
178 
179         // Save Version
180         _settings->setValue("Version", SETTINGS_VERSION);
181 
182         // Save Main Widget
183         _settings->beginGroup("MainWidget");
184         _settings->setValue("MainWidget/geometry", this->saveGeometry());
185         _settings->endGroup();
186 
187         // Save Main Window
188         _settings->beginGroup("MainWindow");
189         _settings->setValue("MainWindow/state", window->saveState());
190         _settings->setValue("MainWindow/geometry", window->saveGeometry());
191         _settings->beginWriteArray("MainWindow/docks_geometry");
192             for (int ind = 0; ind < DOCKS_COUNT; ind++) {
193                 _settings->setArrayIndex(ind);
194                 _settings->setValue("MainWindow/docks_geometry/dock_size", docks[ind]->size());
195             }
196             _settings->endArray();
197         _settings->endGroup();
198 
199         // Save Tables
200         _settings->beginGroup("Tables");
201         _settings->setValue("Tables/table_widget_state", ui->tableWidget->horizontalHeader()->saveState());
202         _settings->setValue("Tables/tree_widget_state", ui->treeWidget->header()->saveState());
203         _settings->endGroup();
204 
205         // Save Settings Widget
206         _settings->beginGroup("SettingsWidget");
207         _settings->setValue("SettingsWidget/geometry", _settingsWindowGeometry);
208         _settings->endGroup();
209 
210         // Save Preset Widget
211         _settings->beginGroup("PresetWidget");
212         _settings->setValue("PresetWidget/geometry", _presetWindowGeometry);
213         _settings->endGroup();
214 
215         // Save Settings
216         _settings->beginGroup("Settings");
217         _settings->setValue("Settings/prefix_type", _prefxType);
218         _settings->setValue("Settings/suffix_type", _suffixType);
219         _settings->setValue("Settings/prefix_name", _prefixName);
220         _settings->setValue("Settings/suffix_name", _suffixName);
221         _settings->setValue("Settings/timer_interval", _timer_interval);
222         _settings->setValue("Settings/theme", _theme);
223         _settings->setValue("Settings/protection", _protection);
224         _settings->setValue("Settings/show_hdr_mode", _showHDR_mode);
225         _settings->setValue("Settings/temp_folder", _temp_folder);
226         _settings->setValue("Settings/output_folder", _output_folder);
227         _settings->setValue("Settings/open_dir", _openDir);
228         _settings->setValue("Settings/batch_mode", _batch_mode);
229         _settings->setValue("Settings/tray", _hideInTrayFlag);
230         _settings->setValue("Settings/language", _language);
231         _settings->setValue("Settings/font", _font);
232         _settings->setValue("Settings/font_size", _fontSize);
233         _settings->setValue("Settings/enviroment", _desktopEnv);
234         _settings->setValue("Settings/row_size", _rowSize);
235         _settings->endGroup();
236 
237         if (_hideInTrayFlag) {
238             trayIcon->hide();
239         }
240         event->accept();
241     }
242 }
243 
paintEvent(QPaintEvent * event)244 void Widget::paintEvent(QPaintEvent *event) /*** Disable QTab draw base ***/
245 {
246     if (event->type() == QEvent::Paint) {
247         QList<QTabBar*> tabBars = window->findChildren<QTabBar*>();
248         foreach (QTabBar *tabBar, tabBars) {
249             if (tabBar->drawBase()) {
250                  tabBar->setDrawBase(false);
251             }
252         }
253     }
254 }
255 
trayIconActivated(QSystemTrayIcon::ActivationReason reason)256 void Widget::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
257 {
258     switch (reason) {
259         case QSystemTrayIcon::Trigger:
260         case QSystemTrayIcon::DoubleClick:
261             if (_expandWindowsState) {
262                 this->showMaximized();
263             }
264             else {
265                 this->showNormal();
266             }
267             break;
268         default:
269             break;
270     }
271 }
272 
setTrayIconActions()273 void Widget::setTrayIconActions()
274 {
275     minimizeAction = new QAction(tr("Hide"), this);
276     restoreAction = new QAction(tr("Show"), this);
277     quitAction = new QAction(tr("Exit"), this);
278 
279     connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
280     connect(restoreAction, &QAction::triggered, this, [this](){
281         if (_expandWindowsState) {
282             this->showMaximized();
283         }
284         else {
285             this->showNormal();
286         }
287     });
288     connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
289 
290     trayIconMenu = new QMenu(this);
291     trayIconMenu->addAction(minimizeAction);
292     trayIconMenu->addAction(restoreAction);
293     trayIconMenu->addAction(quitAction);
294 }
295 
showTrayIcon()296 void Widget::showTrayIcon()
297 {
298     trayIcon = new QSystemTrayIcon(this);
299     trayIcon->setIcon(QIcon(":/resources/icons/64x64/cine-encoder.png"));
300     trayIcon->setContextMenu(trayIconMenu);
301     connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
302 }
303 
desktopEnvDetection()304 void Widget::desktopEnvDetection()
305 {
306 #if defined (Q_OS_UNIX)
307     QProcess process_env;
308     process_env.setProcessChannelMode(QProcess::MergedChannels);
309     QStringList arguments;
310     arguments << "XDG_CURRENT_DESKTOP";
311     process_env.start("printenv", arguments);
312     if (process_env.waitForFinished()) {
313         QString line = process_env.readAllStandardOutput();
314         if (line.indexOf("GNOME") != -1) {
315             _desktopEnv = "gnome";
316         } else {
317             _desktopEnv = "other";
318         }
319     } else {
320         std::cout << "printenv not found" << std::endl;
321         _desktopEnv = "other";
322     }
323 #else
324     _desktopEnv = "other";
325 #endif
326 }
327 
createConnections()328 void Widget::createConnections()
329 {
330     timer = new QTimer(this);
331     connect(timer, SIGNAL(timeout()), this, SLOT(repeatHandler_Type_1()));
332     timerCallSetThumbnail = new QTimer(this);
333     timerCallSetThumbnail->setSingleShot(true);
334     timerCallSetThumbnail->setInterval(800);
335     connect(timerCallSetThumbnail, SIGNAL(timeout()), this, SLOT(repeatHandler_Type_2()));
336 
337     // ***************************** Top menu actions ***********************************//
338 
339     add_files = new QAction(tr("Add files"), this);
340     remove_files = new QAction(tr("Remove from the list"), this);
341     close_prog = new QAction(tr("Close"), this);
342     connect(add_files, &QAction::triggered, this, &Widget::on_actionAdd_clicked);
343     connect(remove_files, &QAction::triggered, this, &Widget::on_actionRemove_clicked);
344     connect(close_prog, &QAction::triggered, this, &Widget::on_closeWindow_clicked);
345 
346     encode_files = new QAction(tr("Encode/Pause"), this);
347     stop_encode = new QAction(tr("Stop"), this);
348     connect(encode_files, &QAction::triggered, this, &Widget::on_actionEncode_clicked);
349     connect(stop_encode, &QAction::triggered, this, &Widget::on_actionStop_clicked);
350 
351     edit_metadata = new QAction(tr("Edit metadata"), this);
352     select_audio = new QAction(tr("Select audio streams"), this);
353     select_subtitles = new QAction(tr("Select subtitles"), this);
354     split_video = new QAction(tr("Split video"), this);
355     connect(edit_metadata, &QAction::triggered, this, &Widget::showMetadataEditor);
356     connect(select_audio, &QAction::triggered, this, &Widget::showAudioStreamsSelection);
357     connect(select_subtitles, &QAction::triggered, this, &Widget::showSubtitlesSelection);
358     connect(split_video, &QAction::triggered, this, &Widget::showVideoSplitter);
359 
360     settings = new QAction(tr("Settings"), this);
361     connect(settings, &QAction::triggered, this, &Widget::on_actionSettings_clicked);
362 
363     reset_view = new QAction(tr("Reset state"), this);
364     connect(reset_view, &QAction::triggered, this, &Widget::resetView);
365 
366     about = new QAction(tr("About"), this);
367     donate = new QAction(tr("Donate"), this);
368     connect(about, &QAction::triggered, this, &Widget::on_actionAbout_clicked);
369     connect(donate, &QAction::triggered, this, &Widget::on_actionDonate_clicked);
370 
371     menuFiles = new QMenu(this);
372     menuFiles->addAction(add_files);
373     menuFiles->addAction(remove_files);
374     menuFiles->addSeparator();
375     menuFiles->addAction(close_prog);
376     ui->menuFileButton->setMenu(menuFiles);
377 
378     menuEdit = new QMenu(this);
379     menuEdit->addAction(encode_files);
380     menuEdit->addAction(stop_encode);
381     ui->menuEditButton->setMenu(menuEdit);
382 
383     menuTools = new QMenu(this);
384     menuTools->addAction(edit_metadata);
385     menuTools->addSeparator();
386     menuTools->addAction(select_audio);
387     menuTools->addAction(select_subtitles);
388     menuTools->addSeparator();
389     menuTools->addAction(split_video);
390     ui->menuToolsButton->setMenu(menuTools);
391 
392     menuView = new QMenu(this);
393     for (int i = 0; i < DOCKS_COUNT; i++) {
394         menuView->addAction(docks[i]->toggleViewAction());
395     }
396     menuView->addAction(reset_view);
397     ui->menuViewButton->setMenu(menuView);
398     docks[dockIndex::LOG_DOCK]->toggleViewAction()->setChecked(false);
399     docks[dockIndex::SPLIT_DOCK]->toggleViewAction()->setChecked(false);
400     docks[dockIndex::LOG_DOCK]->setVisible(false);
401     docks[dockIndex::SPLIT_DOCK]->setVisible(false);
402 
403     menuPreferences = new QMenu(this);
404     menuPreferences->addAction(settings);
405     ui->menuPreferencesButton->setMenu(menuPreferences);
406 
407     menuAbout = new QMenu(this);
408     menuAbout->addAction(about);
409     menuAbout->addSeparator();
410     menuAbout->addAction(donate);
411     ui->menuAboutButton->setMenu(menuAbout);
412 
413     // ***************************** Table menu actions ***********************************//
414 
415     ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
416     itemMenu = new QMenu(this);
417     itemMenu->addAction(remove_files);
418     itemMenu->addSeparator();
419     itemMenu->addAction(encode_files);
420     itemMenu->addSeparator();
421     itemMenu->addAction(edit_metadata);
422     itemMenu->addSeparator();
423     itemMenu->addAction(select_audio);
424     itemMenu->addAction(select_subtitles);
425     itemMenu->addSeparator();
426     itemMenu->addAction(split_video);
427     connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, this, &Widget::provideContextMenu);
428 
429     // ***************************** Tree menu actions ***********************************//
430 
431     ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
432     QAction* add_section = new QAction(tr("Add section"), this);
433     QAction* add_preset = new QAction(tr("Add preset"), this);
434     QAction* rename_section_preset = new QAction(tr("Rename"), this);
435     QAction* remove_section_preset = new QAction(tr("Remove"), this);
436     connect(add_section, &QAction::triggered, this, &Widget::add_section);
437     connect(add_preset, &QAction::triggered, this, &Widget::add_preset);
438     connect(rename_section_preset, &QAction::triggered, this, &Widget::renameSectionPreset);
439     connect(remove_section_preset, &QAction::triggered, this, &Widget::on_actionRemove_preset_clicked);
440 
441     QAction* apply_preset = new QAction(tr("Apply"), this);
442     QAction* edit_preset = new QAction(tr("Edit"), this);
443     connect(apply_preset, &QAction::triggered, this, &Widget::on_buttonApplyPreset_clicked);
444     connect(edit_preset, &QAction::triggered, this, &Widget::on_actionEdit_preset_clicked);
445 
446     sectionMenu = new QMenu(this);
447     sectionMenu->addAction(add_section);
448     sectionMenu->addAction(add_preset);
449     sectionMenu->addAction(rename_section_preset);
450     sectionMenu->addAction(remove_section_preset);
451 
452     presetMenu = new QMenu(this);
453     presetMenu->addAction(add_section);
454     presetMenu->addAction(add_preset);
455     presetMenu->addAction(rename_section_preset);
456     presetMenu->addAction(remove_section_preset);
457     presetMenu->addSeparator();
458     presetMenu->addAction(apply_preset);
459     presetMenu->addAction(edit_preset);
460     connect(ui->treeWidget, &QTreeWidget::customContextMenuRequested, this, &Widget::providePresetContextMenu);
461 
462     // ***************************** Preset menu actions ***********************************//
463 
464     addsection = new QAction(tr("Add section"), this);
465     addpreset = new QAction(tr("Add new preset"), this);
466     addsection->setIcon(QIcon(":/resources/icons/16x16/cil-folder.png"));
467     addpreset->setIcon(QIcon(":/resources/icons/16x16/cil-file.png"));
468     connect(addsection, &QAction::triggered, this, &Widget::add_section);
469     connect(addpreset, &QAction::triggered, this, &Widget::add_preset);
470 
471     menu = new QMenu(this);
472     menu->addAction(addsection);
473     menu->addSeparator();
474     menu->addAction(addpreset);
475     ui->actionAdd_preset->setMenu(menu);
476 
477     // ************************ Metadata Elements Actions ****************************//
478 
479     QList<QLineEdit *> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit *>();
480     foreach (QLineEdit *lineEdit, linesEditMetadata) {
481         QList<QAction*> actionList = lineEdit->findChildren<QAction*>();
482         if (!actionList.isEmpty()) {
483             connect(actionList.first(), &QAction::triggered, this, [this, lineEdit]() {
484             lineEdit->clear();
485             lineEdit->insert("");
486             lineEdit->setModified(true);
487             ui->frame_middle->setFocus();
488             });
489         }
490     }
491 
492     // ************************ Audio Elements Actions ****************************//
493     QList<QLabel*> labelsAudio = ui->frameTab_2->findChildren<QLabel*>();
494     foreach (QLabel *label, labelsAudio) {
495         label->setVisible(false);
496     }
497     audioThumb->setVisible(true);
498 
499     for (int stream = 0; stream < AMOUNT_AUDIO_STREAMS; stream++) {
500         // Check Boxes
501         QCheckBox *checkBoxAudio = ui->frameTab_2->findChild<QCheckBox *>("checkBoxAudio_"
502             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
503         connect(checkBoxAudio, &QCheckBox::clicked, this, [this, checkBoxAudio, stream](){
504             if (_row != -1) {
505                 QString state_qstr = "0";
506                 int state = checkBoxAudio->checkState();
507                 if (state == 2) {
508                     state_qstr = "1";
509                 }
510                 QTableWidgetItem *newItem_checkstate = new QTableWidgetItem(state_qstr);
511                 ui->tableWidget->setItem(_row, columnIndex::T_AUDIOCHECK_1 + stream, newItem_checkstate);
512                 _audioStreamCheckState[stream] = state_qstr.toInt();
513             }
514         });
515         checkBoxAudio->setEnabled(true);
516         checkBoxAudio->setVisible(false);
517         // Line Edit Lang
518         QLineEdit *lineEditLangAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditLangAudio_"
519             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
520         connect(lineEditLangAudio, &QLineEdit::editingFinished, this, [this, lineEditLangAudio, stream](){
521             if (_row != -1) {
522                 if (!lineEditLangAudio->isModified()) {
523                     return;
524                 }
525                 lineEditLangAudio->setModified(false);
526                 QString langAudio = lineEditLangAudio->text();
527                 QTableWidgetItem *newItem_langAudio = new QTableWidgetItem(langAudio);
528                 ui->tableWidget->setItem(_row, columnIndex::T_AUDIOLANG_1 + stream, newItem_langAudio);
529                 _audioLang[stream] = langAudio;
530             }
531         });
532         QList<QAction*> actionLangAudioList = lineEditLangAudio->findChildren<QAction*>();
533         if (!actionLangAudioList.isEmpty()) {
534             connect(actionLangAudioList.first(), &QAction::triggered, this, [this, lineEditLangAudio]() {
535             lineEditLangAudio->clear();
536             lineEditLangAudio->insert("");
537             lineEditLangAudio->setModified(true);
538             ui->frame_middle->setFocus();
539             });
540         }
541         lineEditLangAudio->setEnabled(true);
542         lineEditLangAudio->setVisible(false);
543         // Line Edit Title
544         QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
545             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
546         connect(lineEditTitleAudio, &QLineEdit::editingFinished, this, [this, lineEditTitleAudio, stream](){
547             if (_row != -1) {
548                 if (!lineEditTitleAudio->isModified()) {
549                     return;
550                 }
551                 lineEditTitleAudio->setModified(false);
552                 QString titleAudio = lineEditTitleAudio->text();
553                 QTableWidgetItem *newItem_titleAudio = new QTableWidgetItem(titleAudio);
554                 ui->tableWidget->setItem(_row, columnIndex::T_AUDIOTITLE_1 + stream, newItem_titleAudio);
555                 _audioTitle[stream] = titleAudio;
556             }
557         });
558         QList<QAction*> actionTitleAudioList = lineEditTitleAudio->findChildren<QAction*>();
559         if (!actionTitleAudioList.isEmpty()) {
560             connect(actionTitleAudioList.first(), &QAction::triggered, this, [this, lineEditTitleAudio]() {
561             lineEditTitleAudio->clear();
562             lineEditTitleAudio->insert("");
563             lineEditTitleAudio->setModified(true);
564             ui->frame_middle->setFocus();
565             });
566         }
567         lineEditTitleAudio->setEnabled(true);
568         lineEditTitleAudio->setVisible(false);
569     }
570 
571     // ************************ Subtitle Elements Actions ****************************//
572     QList<QLabel*> labelsSubtitle = ui->frameTab_3->findChildren<QLabel*>();
573     foreach (QLabel *label, labelsSubtitle) {
574         label->setVisible(false);
575     }
576     subtitleThumb->setVisible(true);
577 
578     for (int stream = 0; stream < AMOUNT_SUBTITLES; stream++) {
579         // Check Boxes
580         QCheckBox *checkBoxSubtitle = ui->frameTab_3->findChild<QCheckBox *>("checkBoxSubtitle_"
581             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
582         connect(checkBoxSubtitle, &QCheckBox::clicked, this, [this, checkBoxSubtitle, stream](){
583             if (_row != -1) {
584                 QString state_qstr = "0";
585                 int state = checkBoxSubtitle->checkState();
586                 if (state == 2) {
587                     state_qstr = "1";
588                 }
589                 QTableWidgetItem *newItem_checkstate = new QTableWidgetItem(state_qstr);
590                 ui->tableWidget->setItem(_row, columnIndex::T_SUBCHECK_1 + stream, newItem_checkstate);
591                 _subtitleCheckState[stream] = state_qstr.toInt();
592             }
593         });
594         checkBoxSubtitle->setEnabled(true);
595         checkBoxSubtitle->setVisible(false);
596         // Line Edit Lang
597         QLineEdit *lineEditLangSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditLangSubtitle_"
598             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
599         connect(lineEditLangSubtitle, &QLineEdit::editingFinished, this, [this, lineEditLangSubtitle, stream](){
600             if (_row != -1) {
601                 if (!lineEditLangSubtitle->isModified()) {
602                     return;
603                 }
604                 lineEditLangSubtitle->setModified(false);
605                 QString langSubtitle = lineEditLangSubtitle->text();
606                 QTableWidgetItem *newItem_langSubtitle = new QTableWidgetItem(langSubtitle);
607                 ui->tableWidget->setItem(_row, columnIndex::T_SUBLANG_1 + stream, newItem_langSubtitle);
608                 _subtitleLang[stream] = langSubtitle;
609             }
610         });
611         QList<QAction*> actionLangSubtitleList = lineEditLangSubtitle->findChildren<QAction*>();
612         if (!actionLangSubtitleList.isEmpty()) {
613             connect(actionLangSubtitleList.first(), &QAction::triggered, this, [this, lineEditLangSubtitle]() {
614             lineEditLangSubtitle->clear();
615             lineEditLangSubtitle->insert("");
616             lineEditLangSubtitle->setModified(true);
617             ui->frame_middle->setFocus();
618             });
619         }
620         lineEditLangSubtitle->setEnabled(true);
621         lineEditLangSubtitle->setVisible(false);
622         // Line Edit Title
623         QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
624             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
625         connect(lineEditTitleSubtitle, &QLineEdit::editingFinished, this, [this, lineEditTitleSubtitle, stream](){
626             if (_row != -1) {
627                 if (!lineEditTitleSubtitle->isModified()) {
628                     return;
629                 }
630                 lineEditTitleSubtitle->setModified(false);
631                 QString titleSubtitle = lineEditTitleSubtitle->text();
632                 QTableWidgetItem *newItem_titleSubtitle = new QTableWidgetItem(titleSubtitle);
633                 ui->tableWidget->setItem(_row, columnIndex::T_TITLESUB_1 + stream, newItem_titleSubtitle);
634                 _subtitleTitle[stream] = titleSubtitle;
635             }
636         });
637         QList<QAction*> actionTitleSubtitleList = lineEditTitleSubtitle->findChildren<QAction*>();
638         if (!actionTitleSubtitleList.isEmpty()) {
639             connect(actionTitleSubtitleList.first(), &QAction::triggered, this, [this, lineEditTitleSubtitle]() {
640             lineEditTitleSubtitle->clear();
641             lineEditTitleSubtitle->insert("");
642             lineEditTitleSubtitle->setModified(true);
643             ui->frame_middle->setFocus();
644             });
645         }
646         lineEditTitleSubtitle->setEnabled(true);
647         lineEditTitleSubtitle->setVisible(false);
648     }
649 }
650 
setParameters()651 void Widget::setParameters()    /*** Set parameters ***/
652 {
653     // ***************************** Set parameters ***********************************//
654     createConnections();
655     openingFiles.setParent(this);
656     openingFiles.setModal(true);
657     trayIcon = new QSystemTrayIcon(this);
658     _new_param.resize(PARAMETERS_COUNT);
659     _cur_param.resize(PARAMETERS_COUNT);
660     _preset_table.resize(PARAMETERS_COUNT+1);
661     for (int i = 0; i < PARAMETERS_COUNT+1; i++) {
662       _preset_table[i].resize(5);
663     }
664 
665     // ****************************** Initialize variables ************************************//
666     QDesktopWidget *screenSize = QApplication::desktop();
667     int screenWidth = screenSize->width();
668     int screenHeight = screenSize->height();
669     int widthMainWindow = 1024;
670     int heightMainWindow = 650;
671     int x_pos = static_cast<int>(round(static_cast<float>(screenWidth - widthMainWindow)/2));
672     int y_pos = static_cast<int>(round(static_cast<float>(screenHeight - heightMainWindow)/2));
673     _desktopEnv = "default";
674     mouseClickCoordinate.setX(0);
675     mouseClickCoordinate.setY(0);
676     _settingsWindowGeometry = "default";
677     _presetWindowGeometry = "default";
678     _openDir = QDir::homePath();
679     _settings_path = QDir::homePath() + QString("/CineEncoder");
680     _thumb_path = _settings_path + QString("/thumbnails");
681     _preset_file = _settings_path + QString("/presets.ini");
682     _settings = new QSettings(_settings_path + QString("/settings.ini"), QSettings::IniFormat, this);
683     _status_encode_btn = "start";
684     _timer_interval = 30;
685     _curTime = 0;
686     _language = "";
687     _font = "";
688     _fontSize = 8;
689     _curFilename = "";
690     _curPath = "";
691     _input_file = "";
692     _output_folder = "";
693     _output_file = "";
694     _temp_folder = "";
695     _temp_file = "";
696     _prefixName = "output";
697     _suffixName = "_encoded_";
698     _prefxType = 0;
699     _suffixType = 0;
700     _pos_top = -1;
701     _pos_cld = -1;
702     _rowSize = 25;
703     _expandWindowsState = false;
704     _hideInTrayFlag = false;
705     clickPressedFlag = false;
706     clickPressed_Left_ResizeFlag = false;
707     clickPressed_Left_Top_ResizeFlag = false;
708     clickPressed_Top_ResizeFlag = false;
709     clickPressed_Right_Top_ResizeFlag = false;
710     clickPressed_Right_ResizeFlag = false;
711     clickPressed_Right_Bottom_ResizeFlag = false;
712     clickPressed_Bottom_ResizeFlag = false;
713     clickPressed_Left_Bottom_ResizeFlag = false;
714     _protection = false;
715     _batch_mode = false;
716     _showHDR_mode = false;
717     _row = -1;
718     _theme = 3;
719     QListView *comboboxPresetListView = new QListView(ui->comboBoxPreset);
720     QListView *comboboxModeListView = new QListView(ui->comboBoxMode);
721     QListView *comboboxViewListView = new QListView(ui->comboBoxView);
722     ui->comboBoxPreset->setView(comboboxPresetListView);
723     ui->comboBoxMode->setView(comboboxModeListView);
724     ui->comboBoxView->setView(comboboxViewListView);
725     ui->comboBoxPreset->setVisible(false);
726     ui->comboBoxView->setVisible(false);
727     animation = new QMovie(this);
728     animation->setFileName(":/resources/icons/Animated/cil-spinner-circle.gif");
729     animation->setScaledSize(QSize(18, 18));
730     processEncoding = new QProcess(this);
731     processThumbCreation = new QProcess(this);
732     processEncoding->setProcessChannelMode(QProcess::MergedChannels);
733     processEncoding->setWorkingDirectory(QDir::homePath());
734 
735     // ****************************** Setup widgets ************************************//
736     ui->labelAnimation->setMovie(animation);
737     ui->labelAnimation->hide();
738     ui->label_Progress->hide();
739     ui->label_Remaining->hide();
740     ui->label_RemTime->hide();
741     ui->progressBar->hide();
742     ui->tableWidget->setRowCount(0);
743     ui->tableWidget->horizontalHeader()->setVisible(true);
744     ui->tableWidget->setAlternatingRowColors(true);
745     ui->tableWidget->verticalHeader()->setFixedWidth(0);
746     ui->tableWidget->setColumnWidth(columnIndex::FILENAME, 250);
747     ui->tableWidget->setColumnWidth(columnIndex::FORMAT, 80);
748     ui->tableWidget->setColumnWidth(columnIndex::RESOLUTION, 85);
749     ui->tableWidget->setColumnWidth(columnIndex::DURATION, 70);
750     ui->tableWidget->setColumnWidth(columnIndex::FPS, 70);
751     ui->tableWidget->setColumnWidth(columnIndex::AR, 60);
752     ui->tableWidget->setColumnWidth(columnIndex::STATUS, 80);
753     ui->tableWidget->setIconSize(QSize(16, 16));
754 
755     for (int i = columnIndex::COLORRANGE; i <= columnIndex::MAXFALL; i++) {
756         ui->tableWidget->setColumnWidth(i, 82);
757     }
758 
759     for (int i = columnIndex::BITRATE; i <= columnIndex::COLORSPACE; i++) {
760         ui->tableWidget->hideColumn(i);
761     }
762 
763     for (int i = columnIndex::T_DUR; i <= columnIndex::T_ENDTIME; i++) {
764         ui->tableWidget->hideColumn(i);
765     }
766 
767     // ****************************** Create folders ************************************//
768     if (!QDir(_settings_path).exists()) {
769         QDir().mkdir(_settings_path);
770         std::cout << "Setting path not existed and was created ..." << std::endl;  // Debug info //
771     }
772     if (QDir(_thumb_path).exists()) {
773         unsigned int count_thumb = QDir(_thumb_path).count();
774         std::cout << "Number of thumbnails: " << count_thumb << std::endl; // Debug info //
775         if (count_thumb > 300) {
776             QDir(_thumb_path).removeRecursively();
777             std::cout << "Thumbnails removed... " << std::endl; // Debug info //
778         }
779     }
780     if (!QDir(_thumb_path).exists()) {
781         QDir().mkdir(_thumb_path);
782         std::cout << "Thumbnail path not existed and was created ..." << std::endl;  // Debug info //
783     }
784 
785     // ****************************** Read presets ************************************//
786     QFile _prs_file(_preset_file);
787     if (_prs_file.open(QIODevice::ReadOnly)) {
788         QDataStream in(&_prs_file);
789         in.setVersion(QDataStream::Qt_4_0);
790         int ver;
791         in >> ver;
792         if (ver == PRESETS_VERSION) {
793             in >> _cur_param >> _pos_top >> _pos_cld >> _preset_table;
794             _prs_file.close();
795         }
796         else {
797             _prs_file.close();
798             set_defaults();
799         }
800 
801     } else {
802         set_defaults();
803     }
804 
805     // ************************** Read settings ******************************//
806     QList<int> dockSizesX = {};
807     QList<int> dockSizesY = {};
808     if (_settings->value("Version").toInt() == SETTINGS_VERSION) {
809         // Restore Main Widget
810         _settings->beginGroup("MainWidget");
811         this->restoreGeometry(_settings->value("MainWidget/geometry").toByteArray());
812         _settings->endGroup();
813 
814         // Restore Main Window
815         _settings->beginGroup("MainWindow");
816         window->restoreState(_settings->value("MainWindow/state").toByteArray());
817         int arraySize = _settings->beginReadArray("MainWindow/docks_geometry");
818             for (int i = 0; i < arraySize && i < DOCKS_COUNT; i++) {
819                 _settings->setArrayIndex(i);
820                 QSize size = _settings->value("MainWindow/docks_geometry/dock_size").toSize();
821                 dockSizesX.append(size.width());
822                 dockSizesY.append(size.height());
823             }
824             _settings->endArray();
825         _settings->endGroup();
826 
827         // Restore Tables
828         _settings->beginGroup("Tables");
829         ui->tableWidget->horizontalHeader()->restoreState(_settings->value("Tables/table_widget_state").toByteArray());
830         ui->treeWidget->header()->restoreState(_settings->value("Tables/tree_widget_state").toByteArray());
831         _settings->endGroup();
832 
833         // Restore Settings Widget
834         _settings->beginGroup("SettingsWidget");
835         _settingsWindowGeometry = _settings->value("SettingsWidget/geometry").toByteArray();
836         _settings->endGroup();
837 
838         // Restore Preset Widget
839         _settings->beginGroup("PresetWidget");
840         _presetWindowGeometry = _settings->value("PresetWidget/geometry").toByteArray();
841         _settings->endGroup();
842 
843         // Restore Settings
844         _settings->beginGroup("Settings");
845         _prefxType = _settings->value("Settings/prefix_type").toInt();
846         _suffixType = _settings->value("Settings/suffix_type").toInt();
847         _prefixName = _settings->value("Settings/prefix_name").toString();
848         _suffixName = _settings->value("Settings/suffix_name").toString();
849         _timer_interval = _settings->value("Settings/timer_interval").toInt();
850         _theme = _settings->value("Settings/theme").toInt();
851         _protection = _settings->value("Settings/protection").toBool();
852         _showHDR_mode = _settings->value("Settings/show_hdr_mode").toBool();
853         _temp_folder = _settings->value("Settings/temp_folder").toString();
854         _output_folder = _settings->value("Settings/output_folder").toString();
855         _openDir = _settings->value("Settings/open_dir").toString();
856         _batch_mode = _settings->value("Settings/batch_mode").toBool();
857         _hideInTrayFlag = _settings->value("Settings/tray").toBool();
858         _language = _settings->value("Settings/language").toString();
859         _font = _settings->value("Settings/font").toString();
860         _fontSize = _settings->value("Settings/font_size").toInt();
861         _desktopEnv = _settings->value("Settings/enviroment").toString();
862         _rowSize = _settings->value("Settings/row_size").toInt();
863         _settings->endGroup();
864 
865     } else {
866         this->setGeometry(x_pos, y_pos, widthMainWindow, heightMainWindow);
867     }
868 
869     // ***************************** Preset parameters ***********************************//
870     ui->treeWidget->clear();
871     ui->treeWidget->setHeaderHidden(false);
872     ui->treeWidget->setAlternatingRowColors(true);
873     ui->treeWidget->setColumnWidth(0, 230);
874     ui->treeWidget->setColumnWidth(1, 55);
875     ui->treeWidget->setColumnWidth(2, 55);
876     ui->treeWidget->setColumnWidth(3, 55);
877     ui->treeWidget->setColumnWidth(4, 55);
878     ui->treeWidget->setColumnWidth(5, 55);
879     ui->treeWidget->setColumnWidth(6, 55);
880     int NUM_ROWS = _preset_table[0].size();
881     int NUM_COLUMNS = _preset_table.size();
882     QString type;
883     QFont parentFont;
884     parentFont.setBold(true);
885     for (int i = 0; i < NUM_ROWS; i++) {
886         type = _preset_table[PARAMETERS_COUNT][i];
887         if (type == "TopLewelItem") {
888             QTreeWidgetItem *root = new QTreeWidgetItem();
889             root->setText(0, _preset_table[0][i]);
890             root->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
891             root->setFont(0, parentFont);
892             setPresetIcon(root, true);
893             ui->treeWidget->addTopLevelItem(root);
894             ui->treeWidget->setCurrentItem(root);
895             root->setFirstColumnSpanned(true);
896         }
897         if (type == "ChildItem") {
898             QTreeWidgetItem *item = ui->treeWidget->currentItem();
899             QTreeWidgetItem *child = new QTreeWidgetItem();
900             for (int j = 0; j < PARAMETERS_COUNT; j++) {
901                 child->setText(j + 7, _preset_table[j][i]);
902             }
903             QString savedPresetName = child->text(30 + 7);
904             child->setText(0, savedPresetName);
905             updateInfoFields(_preset_table[1][i], _preset_table[2][i], _preset_table[3][i],
906                              _preset_table[4][i], _preset_table[11][i], _preset_table[12][i],
907                              _preset_table[21][i], child, false);
908             setItemStyle(child);
909             item->addChild(child);
910         }
911     }
912     if (_pos_top != -1 && _pos_cld != -1) {
913         QTreeWidgetItem *item = ui->treeWidget->topLevelItem(_pos_top)->child(_pos_cld);
914         ui->treeWidget->setCurrentItem(item);
915     }
916     std::cout << NUM_ROWS << " x " << NUM_COLUMNS << std::endl; // Table size
917     for (int i = 7; i <= 40; i++) {
918         ui->treeWidget->hideColumn(i);
919     }
920 
921     // ***************************** Other parameters ***********************************//
922     if (dockSizesX.count() < DOCKS_COUNT || dockSizesY.count() < DOCKS_COUNT) {
923         float coeffX[DOCKS_COUNT] = {0.25f, 0.04f, 0.48f, 0.48f, 0.25f, 0.25f, 0.25f, 0.25f};
924         float coeffY[DOCKS_COUNT] = {0.9f, 0.1f, 0.1f, 0.1f, 0.9f, 0.9f, 0.9f, 0.9f};
925         for (int ind = 0; ind < DOCKS_COUNT; ind++) {
926             int dockWidth = static_cast<int>(coeffX[ind] * widthMainWindow);
927             int dockHeight = static_cast<int>(coeffY[ind] * heightMainWindow);
928             dockSizesX.append(dockWidth);
929             dockSizesY.append(dockHeight);
930         }
931     }
932     QTimer::singleShot(200, this, [this, dockSizesX, dockSizesY](){
933         setDocksParameters(dockSizesX, dockSizesY);
934     });
935 
936     if (_timer_interval < 15) _timer_interval = 30;
937     timer->setInterval(_timer_interval*1000);
938 
939     if (_rowSize != 0) ui->horizontalSlider_resize->setValue(_rowSize);
940 
941     if (_fontSize == 0) _fontSize = 8;
942 
943     if (_language == "") {
944         QLocale locale = QLocale::system();
945         if (locale.language() == QLocale::Chinese) {
946             _language = "zh";
947         }
948         else if (locale.language() == QLocale::German) {
949             _language = "de";
950         }
951         else if (locale.language() == QLocale::Russian) {
952             _language = "ru";
953         }
954         else {
955             _language = "en";
956         }
957     }
958 
959     if (_desktopEnv == "default") {
960         std::cout << "Detect desktop env. ..." << std::endl;
961         desktopEnvDetection();
962     }
963     std::cout << "Desktop env.: " << _desktopEnv.toStdString() << std::endl;
964 
965     if (this->isMaximized()) _expandWindowsState = true;
966 
967     if (_batch_mode) {
968         ui->comboBoxMode->blockSignals(true);
969         ui->comboBoxMode->setCurrentIndex(1);
970         ui->comboBoxMode->blockSignals(false);
971     }
972     setTrayIconActions();
973     showTrayIcon();
974     if (_hideInTrayFlag) trayIcon->show();
975     setTheme(_theme);
976 }
977 
setDocksParameters(QList<int> dockSizesX,QList<int> dockSizesY)978 void Widget::setDocksParameters(QList<int> dockSizesX, QList<int> dockSizesY)
979 {
980     // ************************** Set Docks Parameters ********************************//
981     QList<QDockWidget*> docksVis;
982     QList<int> dockVisSizesX;
983     QList<int> dockVisSizesY;
984     for (int i = 0; i < DOCKS_COUNT; i++) {
985         if (docks[i]->isVisible() && !docks[i]->isFloating()){
986             docksVis.append(docks[i]);
987             dockVisSizesX.append(dockSizesX.at(i));
988             dockVisSizesY.append(dockSizesY.at(i));
989         }
990     }
991     window->resizeDocks(docksVis, dockVisSizesX, Qt::Horizontal);
992     window->resizeDocks(docksVis, dockVisSizesY, Qt::Vertical);
993     for (int i = 0; i < DOCKS_COUNT; i++) {
994         if (docks[i]->isVisible() && docks[i]->isFloating()){
995             docks[i]->setFloating(false); // Bypassing the error with detached docks in some Linux distributions
996             docks[i]->setFloating(true);
997         }
998     }
999 }
1000 
on_closeWindow_clicked()1001 void Widget::on_closeWindow_clicked()    /*** Close window signal ***/
1002 {
1003     this->close();
1004 }
1005 
setExpandIcon()1006 void Widget::setExpandIcon()
1007 {
1008     switch (_theme)
1009     {
1010         case 0:
1011         case 1:
1012         case 2:
1013             if (_expandWindowsState) {
1014                 ui->expandWindow->setIcon(QIcon(":/resources/icons/16x16/cil-clone.png"));
1015             } else {
1016                 ui->expandWindow->setIcon(QIcon(":/resources/icons/16x16/cil-media-stop.png"));}
1017             break;
1018         case 3:
1019             if (_expandWindowsState) {
1020                 ui->expandWindow->setIcon(QIcon(":/resources/icons/16x16/cil-clone_black.png"));
1021             } else {
1022                 ui->expandWindow->setIcon(QIcon(":/resources/icons/16x16/cil-media-stop_black.png"));}
1023             break;
1024     }
1025 }
1026 
on_expandWindow_clicked()1027 void Widget::on_expandWindow_clicked()    /*** Expand window ***/
1028 {
1029     if (!this->isMaximized()) {
1030         _expandWindowsState = true;
1031         this->showMaximized();
1032     } else {
1033         _expandWindowsState = false;
1034         this->showNormal();
1035     }
1036     setExpandIcon();
1037 }
1038 
on_hideWindow_clicked()1039 void Widget::on_hideWindow_clicked()    /*** Hide window ***/
1040 {
1041     if (_hideInTrayFlag) {
1042         this->hide();
1043     } else {
1044         this->showMinimized();
1045     }
1046 }
1047 
on_actionAbout_clicked()1048 void Widget::on_actionAbout_clicked()   /*** About ***/
1049 {
1050     About about(this);
1051     about.setModal(true);
1052     about.setParameters();
1053     about.exec();
1054 }
1055 
on_actionDonate_clicked()1056 void Widget::on_actionDonate_clicked()   /*** Donate ***/
1057 {
1058     Donate donate(this);
1059     donate.setModal(true);
1060     donate.setParameters();
1061     donate.exec();
1062 }
1063 
on_actionSettings_clicked()1064 void Widget::on_actionSettings_clicked()
1065 {
1066     Settings settings(this);
1067     settings.setParameters(&_settingsWindowGeometry, &_output_folder, &_temp_folder, &_protection,
1068                            &_showHDR_mode, &_timer_interval, &_theme, &_prefixName, &_suffixName,
1069                            &_prefxType, &_suffixType, &_hideInTrayFlag, &_language, _desktopEnv,
1070                            &_fontSize, &_font);
1071     settings.setModal(true);
1072     if (settings.exec() == QDialog::Accepted) {
1073         timer->setInterval(_timer_interval*1000);
1074         setTheme(_theme);
1075         if (_hideInTrayFlag) {
1076             trayIcon->show();
1077         } else {
1078             trayIcon->hide();
1079         }
1080         if (_row != -1) {
1081             get_output_filename();
1082         }
1083         _message = tr("You need to restart the program for the settings to take effect.");
1084         call_task_complete(_message, false);
1085     }
1086 }
1087 
showOpeningFiles(bool status)1088 void Widget::showOpeningFiles(bool status)
1089 {
1090     QPoint position;
1091     QPoint posMainWindow = this->rect().topLeft();
1092     QSize sizeMainWindow = this->size();
1093     int x_pos = posMainWindow.x() + static_cast<int>(round(static_cast<float>(sizeMainWindow.width())/2));
1094     int y_pos = posMainWindow.y() + static_cast<int>(round(static_cast<float>(sizeMainWindow.height())/2));
1095     position.setX(x_pos);
1096     position.setY(y_pos);
1097     openingFiles.setParameters(status, position);
1098 }
1099 
showOpeningFiles(QString text)1100 void Widget::showOpeningFiles(QString text)
1101 {
1102     openingFiles.setText(text);
1103 }
1104 
showOpeningFiles(int percent)1105 void Widget::showOpeningFiles(int percent)
1106 {
1107     openingFiles.setPercent(percent);
1108 }
1109 
showMetadataEditor()1110 void Widget::showMetadataEditor()
1111 {
1112     if (!docks[dockIndex::METADATA_DOCK]->isVisible()) {
1113         docks[dockIndex::METADATA_DOCK]->setVisible(true);
1114     }
1115     docks[dockIndex::METADATA_DOCK]->setFloating(true);
1116 }
1117 
showAudioStreamsSelection()1118 void Widget::showAudioStreamsSelection()
1119 {
1120     if (!docks[dockIndex::STREAMS_DOCK]->isVisible()) {
1121         docks[dockIndex::STREAMS_DOCK]->setVisible(true);
1122     }
1123     docks[dockIndex::STREAMS_DOCK]->setFloating(true);
1124     ui->tabWidgetRight->setCurrentIndex(0);
1125 }
1126 
showSubtitlesSelection()1127 void Widget::showSubtitlesSelection()
1128 {
1129     if (!docks[dockIndex::STREAMS_DOCK]->isVisible()) {
1130         docks[dockIndex::STREAMS_DOCK]->setVisible(true);
1131     }
1132     docks[dockIndex::STREAMS_DOCK]->setFloating(true);
1133     ui->tabWidgetRight->setCurrentIndex(1);
1134 }
1135 
showVideoSplitter()1136 void Widget::showVideoSplitter()
1137 {
1138     if (!docks[dockIndex::SPLIT_DOCK]->isVisible()) {
1139         docks[dockIndex::SPLIT_DOCK]->setVisible(true);
1140     }
1141     docks[dockIndex::SPLIT_DOCK]->setFloating(true);
1142 }
1143 
get_current_data()1144 void Widget::get_current_data() /*** Get current data ***/
1145 {
1146     _dur = (ui->tableWidget->item(_row, columnIndex::T_DUR)->text()).toDouble();
1147     _stream_size = ui->tableWidget->item(_row, columnIndex::T_STREAMSIZE)->text();
1148     _width = ui->tableWidget->item(_row, columnIndex::T_WIDTH)->text();
1149     _height = ui->tableWidget->item(_row, columnIndex::T_HEIGHT)->text();
1150     _fmt = ui->tableWidget->item(_row, columnIndex::FORMAT)->text();
1151     _fps = ui->tableWidget->item(_row, columnIndex::FPS)->text();
1152 
1153     double fps_double = _fps.toDouble();
1154     _fr_count = static_cast<int>(round(_dur * fps_double));
1155 
1156     _startTime = (ui->tableWidget->item(_row, columnIndex::T_STARTTIME)->text()).toDouble();
1157     _endTime = (ui->tableWidget->item(_row, columnIndex::T_ENDTIME)->text()).toDouble();
1158 
1159     //std::cout << "DURATION SEC COUNT <<<<<<<<<<<<<<<<<< : " << _dur << std::endl;
1160     //std::cout << "FRAME RATE COUNT <<<<<<<<<<<<<<<<<< : " << _fr_count << std::endl;
1161 
1162     QString curCodec = _fmt;
1163     QString curFps = _fps;
1164     QString curRes = ui->tableWidget->item(_row, columnIndex::RESOLUTION)->text();
1165     QString curAr = ui->tableWidget->item(_row, columnIndex::AR)->text();
1166     QString curBitrate = ui->tableWidget->item(_row, columnIndex::BITRATE)->text();
1167     QString curColorSampling = ui->tableWidget->item(_row, columnIndex::SUBSAMPLING)->text();
1168     QString curDepth = ui->tableWidget->item(_row, columnIndex::BITDEPTH)->text();
1169     QString curSpace = ui->tableWidget->item(_row, columnIndex::COLORSPACE)->text();
1170 
1171     _curPath = ui->tableWidget->item(_row, columnIndex::PATH)->text();
1172     _curFilename = ui->tableWidget->item(_row, columnIndex::FILENAME)->text();
1173     _input_file = _curPath + QString("/") + _curFilename;
1174     _hdr[CUR_COLOR_RANGE] = ui->tableWidget->item(_row, columnIndex::COLORRANGE)->text();       // color range
1175     _hdr[CUR_COLOR_PRIMARY] = ui->tableWidget->item(_row, columnIndex::COLORPRIM)->text();      // color primary
1176     _hdr[CUR_COLOR_MATRIX] = ui->tableWidget->item(_row, columnIndex::COLORMATRIX)->text();     // color matrix
1177     _hdr[CUR_TRANSFER] = ui->tableWidget->item(_row, columnIndex::TRANSFER)->text();            // transfer
1178     _hdr[CUR_MAX_LUM] = ui->tableWidget->item(_row, columnIndex::MAXLUM)->text();               // max lum
1179     _hdr[CUR_MIN_LUM] = ui->tableWidget->item(_row, columnIndex::MINLUM)->text();               // min lum
1180     _hdr[CUR_MAX_CLL] = ui->tableWidget->item(_row, columnIndex::MAXCLL)->text();               // max cll
1181     _hdr[CUR_MAX_FALL] = ui->tableWidget->item(_row, columnIndex::MAXFALL)->text();             // max fall
1182     _hdr[CUR_MASTER_DISPLAY] = ui->tableWidget->item(_row, columnIndex::MASTERDISPLAY)->text(); // master display
1183     _hdr[CUR_CHROMA_COORD] = ui->tableWidget->item(_row, columnIndex::T_CHROMACOORD)->text();   // chr coord
1184     _hdr[CUR_WHITE_COORD] = ui->tableWidget->item(_row, columnIndex::T_WHITECOORD)->text();     // white coord
1185 
1186     _videoMetadata[VIDEO_TITLE] = ui->tableWidget->item(_row, columnIndex::T_VIDEOTITLE)->text();
1187     _videoMetadata[VIDEO_AUTHOR] = ui->tableWidget->item(_row, columnIndex::T_VIDEOAUTHOR)->text();
1188     _videoMetadata[VIDEO_YEAR] = ui->tableWidget->item(_row, columnIndex::T_VIDEOYEAR)->text();
1189     _videoMetadata[VIDEO_PERFORMER] = ui->tableWidget->item(_row, columnIndex::T_VIDEOPERF)->text();
1190     _videoMetadata[VIDEO_DESCRIPTION] = ui->tableWidget->item(_row, columnIndex::T_VIDEODESCR)->text();
1191     _videoMetadata[VIDEO_MOVIENAME] = ui->tableWidget->item(_row, columnIndex::T_VIDEOMOVIENAME)->text();
1192 
1193     for (int p = 0; p < AMOUNT_AUDIO_STREAMS; p++) {
1194         _audioStreamCheckState[p] = (ui->tableWidget->item(_row, p + columnIndex::T_AUDIOCHECK_1)->text()).toInt();
1195         _audioLang[p] = ui->tableWidget->item(_row, p + columnIndex::T_AUDIOLANG_1)->text();
1196         _audioTitle[p] = ui->tableWidget->item(_row, p + columnIndex::T_AUDIOTITLE_1)->text();
1197     }
1198 
1199     for (int p = 0; p < AMOUNT_SUBTITLES; p++) {
1200         _subtitleCheckState[p] = (ui->tableWidget->item(_row, p + columnIndex::T_SUBCHECK_1)->text()).toInt();
1201         _subtitleLang[p] = ui->tableWidget->item(_row, p + columnIndex::T_SUBLANG_1)->text();
1202         _subtitleTitle[p] = ui->tableWidget->item(_row, p + columnIndex::T_TITLESUB_1)->text();
1203     }
1204 
1205     //******************************** Set icons *****************************//
1206 
1207     double halfTime = _dur/2;
1208     QString tmb_file = setThumbnail(_curFilename, halfTime, "high", 1);
1209 
1210     QSize imageSize = QSize(85, 48);
1211     if (_rowSize == 25) {
1212         QString icons[4][5] = {
1213             {"cil-hdr",       "cil-camera-roll",       "cil-hd",       "cil-4k",       "cil-file"},
1214             {"cil-hdr",       "cil-camera-roll",       "cil-hd",       "cil-4k",       "cil-file"},
1215             {"cil-hdr",       "cil-camera-roll",       "cil-hd",       "cil-4k",       "cil-file"},
1216             {"cil-hdr_black", "cil-camera-roll_black", "cil-hd_black", "cil-4k_black", "cil-file_black"}
1217         };
1218 
1219         if (_hdr[CUR_MASTER_DISPLAY] != "") {
1220             tmb_file = ":/resources/icons/16x16/" + icons[_theme][0] + ".png";
1221         }
1222         else if (_height.toInt() >=1 && _height.toInt() < 720) {
1223             tmb_file = ":/resources/icons/16x16/" + icons[_theme][1] + ".png";
1224         }
1225         else if (_height.toInt() >= 720 && _height.toInt() < 2160) {
1226             tmb_file = ":/resources/icons/16x16/" + icons[_theme][2] + ".png";
1227         }
1228         else if (_height.toInt() >= 2160) {
1229             tmb_file = ":/resources/icons/16x16/" + icons[_theme][3] + ".png";
1230         }
1231         else {
1232             tmb_file = ":/resources/icons/16x16/" + icons[_theme][4] + ".png";
1233         }
1234         imageSize = QSize(16, 16);
1235     }
1236     QPixmap pxmp(tmb_file);
1237     QPixmap scaled = pxmp.scaled(imageSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
1238     ui->tableWidget->item(_row, columnIndex::FILENAME)->setIcon(QIcon(scaled));
1239 
1240     //******************************** Set description *****************************//
1241 
1242     ui->label_source->setText(_curFilename);
1243 
1244     if (curCodec != "") {
1245         curCodec += ", ";
1246     }
1247     if (curRes != "") {
1248         curRes += ", ";
1249     }
1250     if (curFps != "") {
1251         curFps += " fps, ";
1252     }
1253     if (curAr != "") {
1254         curAr += ", ";
1255     }
1256     if (curSpace != "") {
1257         curSpace += ", ";
1258     }
1259     if (curColorSampling != "") {
1260         curColorSampling += ", ";
1261     }
1262     if (curDepth != "") {
1263         curDepth += tr(" bit, ");
1264     }
1265     if (curBitrate != "") {
1266         curBitrate += tr(" kbps; ");
1267     }
1268     QString sourceParam = curCodec + curRes + curFps + curAr + curSpace + curColorSampling + curDepth + curBitrate;
1269 
1270     int countAudioStreams = 0;
1271     QString curAudioStream("");
1272     while (countAudioStreams < AMOUNT_AUDIO_STREAMS) {
1273         curAudioStream = ui->tableWidget->item(_row, countAudioStreams + columnIndex::T_AUDIO_1)->text();
1274         if (curAudioStream == "") {
1275             break;
1276         }
1277         countAudioStreams++;
1278         sourceParam += tr("Audio #") + QString::number(countAudioStreams) + QString(": ") + curAudioStream + QString("; ");
1279     }
1280 
1281     int countSubtitles = 0;
1282     QString curSubtitle("");
1283     while (countSubtitles < AMOUNT_SUBTITLES) {
1284         curSubtitle = ui->tableWidget->item(_row, countSubtitles + columnIndex::T_SUBTITLE_1)->text();
1285         if (curSubtitle == "") {
1286             break;
1287         }
1288         countSubtitles++;
1289     }
1290 
1291 
1292     if (curCodec == "Undef, ") {
1293         sourceParam = tr("Undefined");
1294     }
1295     ui->textBrowser_1->clear();
1296     ui->textBrowser_1->setText(sourceParam);
1297     get_output_filename();
1298 
1299     //******************************** Set time widgets *****************************//
1300 
1301     ui->horizontalSlider->setMaximum(_fr_count);
1302     ui->lineEditStartTime->setText(timeConverter(_startTime));
1303     ui->lineEditEndTime->setText(timeConverter(_endTime));
1304 
1305     //******************************** Set video widgets *****************************//
1306 
1307     QList<QLineEdit *> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit *>();
1308     foreach (QLineEdit *lineEdit, linesEditMetadata) {
1309         lineEdit->setEnabled(true);
1310     }
1311 
1312     ui->lineEditTitleVideo->setText(_videoMetadata[VIDEO_TITLE]);
1313     ui->lineEditAuthorVideo->setText(_videoMetadata[VIDEO_AUTHOR]);
1314     ui->lineEditYearVideo->setText(_videoMetadata[VIDEO_YEAR]);
1315     ui->lineEditPerfVideo->setText(_videoMetadata[VIDEO_PERFORMER]);
1316     ui->lineEditDescriptionVideo->setText(_videoMetadata[VIDEO_DESCRIPTION]);
1317     ui->lineEditMovieNameVideo->setText(_videoMetadata[VIDEO_MOVIENAME]);
1318 
1319     foreach (QLineEdit *lineEdit, linesEditMetadata) {
1320         lineEdit->setCursorPosition(0);
1321     }
1322 
1323     //******************************** Set audio widgets *****************************//
1324     if (countAudioStreams > 0) {
1325         audioThumb->setVisible(false);
1326     }
1327     for (int q = 0; q < AMOUNT_AUDIO_STREAMS; q++) {
1328         QCheckBox *checkBoxAudio = ui->frameTab_2->findChild<QCheckBox *>("checkBoxAudio_"
1329             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1330         checkBoxAudio->setChecked(bool(_audioStreamCheckState[q]));
1331         QLineEdit *lineEditLangAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditLangAudio_"
1332             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1333         lineEditLangAudio->setText(_audioLang[q]);
1334         lineEditLangAudio->setCursorPosition(0);
1335         QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
1336             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1337         lineEditTitleAudio->setText(_audioTitle[q]);
1338         lineEditTitleAudio->setCursorPosition(0);
1339         QLabel *labelAudio = ui->frameTab_2->findChild<QLabel *>("labelTitleAudio_"
1340             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1341         if (q < countAudioStreams) {
1342             checkBoxAudio->setVisible(true);
1343             lineEditLangAudio->setVisible(true);
1344             lineEditTitleAudio->setVisible(true);
1345             labelAudio->setVisible(true);
1346         }
1347     }
1348 
1349     //******************************** Set subtitle widgets *****************************//
1350     if (countSubtitles > 0) {
1351         subtitleThumb->setVisible(false);
1352     }
1353     for (int q = 0; q < AMOUNT_SUBTITLES; q++) {
1354         QCheckBox *checkBoxSubtitle = ui->frameTab_3->findChild<QCheckBox *>("checkBoxSubtitle_"
1355             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1356         checkBoxSubtitle->setChecked(bool(_subtitleCheckState[q]));
1357         QLineEdit *lineEditLangSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditLangSubtitle_"
1358             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1359         lineEditLangSubtitle->setText(_subtitleLang[q]);
1360         lineEditLangSubtitle->setCursorPosition(0);
1361         QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
1362             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1363         lineEditTitleSubtitle->setText(_subtitleTitle[q]);
1364         lineEditTitleSubtitle->setCursorPosition(0);
1365         QLabel *labelSubtitle = ui->frameTab_3->findChild<QLabel *>("labelTitleSub_"
1366             + QString::number(q+1), Qt::FindDirectChildrenOnly);
1367         if (q < countSubtitles) {
1368             checkBoxSubtitle->setVisible(true);
1369             lineEditLangSubtitle->setVisible(true);
1370             lineEditTitleSubtitle->setVisible(true);
1371             labelSubtitle->setVisible(true);
1372         }
1373     }
1374 }
1375 
setTheme(int & ind_theme)1376 void Widget::setTheme(int &ind_theme)   /*** Set theme ***/
1377 {
1378     QFile file;
1379     QString list("");
1380     switch (ind_theme)
1381     {
1382         case 0:
1383             file.setFileName(":/resources/css/style_0.css");
1384             raiseThumb->setStyleSheet("color: #09161E; font: 64pt; font-style: oblique;");
1385             audioThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1386             subtitleThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1387             break;
1388         case 1:
1389             file.setFileName(":/resources/css/style_1.css");
1390             raiseThumb->setStyleSheet("color: #09161E; font: 64pt; font-style: oblique;");
1391             audioThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1392             subtitleThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1393             break;
1394         case 2:
1395             file.setFileName(":/resources/css/style_2.css");
1396             raiseThumb->setStyleSheet("color: #09161E; font: 64pt; font-style: oblique;");
1397             audioThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1398             subtitleThumb->setStyleSheet("color: #09161E; font: 24pt; font-style: oblique;");
1399             break;
1400         case 3:
1401             file.setFileName(":/resources/css/style_3.css");
1402             raiseThumb->setStyleSheet("color: #E3E3E3; font: 64pt; font-style: oblique;");
1403             audioThumb->setStyleSheet("color: #E3E3E3; font: 24pt; font-style: oblique;");
1404             subtitleThumb->setStyleSheet("color: #E3E3E3; font: 24pt; font-style: oblique;");
1405             break;
1406     }
1407     if (file.open(QFile::ReadOnly)) {
1408         list = QString::fromUtf8(file.readAll());
1409         file.close();
1410     }
1411     this->setStyleSheet(styleCreator(list));
1412     int i = 11;
1413     if (!_showHDR_mode)
1414     {
1415         while (i <= 19) {
1416             ui->tableWidget->hideColumn(i);
1417             i++;
1418         }
1419     } else {
1420         while (i <= 19) {
1421             ui->tableWidget->showColumn(i);
1422             i++;
1423         }
1424     }
1425     setExpandIcon();
1426 }
1427 
styleCreator(const QString & list)1428 QString Widget::styleCreator(const QString &list)    /*** Parsing CSS ***/
1429 {
1430     QString style = list;
1431     QStringList varDetect;
1432     QStringList splitList;
1433     QStringList varSplitter;
1434     QStringList varNames;
1435     QStringList varValues;
1436     splitList << list.split(";");
1437 
1438     for (int i = 0; i < splitList.size(); i++) {
1439         if (splitList[i].indexOf("@") != -1 && splitList[i].indexOf("=") != -1) {
1440             varDetect.append(splitList[i]);
1441         }
1442     }
1443     for (int i = 0; i < varDetect.size(); i++) {
1444 
1445         varNames.append(varDetect[i].split("=")[0].remove(" ").remove("\n"));
1446         varValues.append(varDetect[i].split("=")[1].remove(" ").remove("\n"));
1447         style = style.remove(varDetect[i] + QString(";"));
1448     }
1449     for (int i = 0; i < varNames.size(); i++) {
1450         style = style.replace(varNames[i], varValues[i]);
1451     }
1452     //std::cout << style.toStdString() << std::endl;
1453     return style;
1454 }
1455 
setStatus(QString status)1456 void Widget::setStatus(QString status)
1457 {
1458     QTableWidgetItem *newItem_status = new QTableWidgetItem(status);
1459     newItem_status->setTextAlignment(Qt::AlignCenter);
1460     ui->tableWidget->setItem(_row, columnIndex::STATUS, newItem_status);
1461 }
1462 
restore_initial_state()1463 void Widget::restore_initial_state()    /*** Restore initial state ***/
1464 {
1465     ui->treeWidget->setEnabled(true);
1466     animation->stop();
1467     add_files->setEnabled(true);
1468     remove_files->setEnabled(true);
1469     settings->setEnabled(true);
1470     ui->lineEditCurTime->setEnabled(true);
1471     ui->lineEditStartTime->setEnabled(true);
1472     ui->lineEditEndTime->setEnabled(true);
1473     ui->buttonFramePrevious->setEnabled(true);
1474     ui->buttonFrameNext->setEnabled(true);
1475     ui->horizontalSlider->setEnabled(true);
1476     ui->buttonSetStartTime->setEnabled(true);
1477     ui->buttonSetEndTime->setEnabled(true);
1478     ui->tableWidget->setEnabled(true);
1479     ui->buttonSortUp->setEnabled(true);
1480     ui->buttonSortDown->setEnabled(true);
1481     ui->actionAdd->setEnabled(true);
1482     ui->actionRemove->setEnabled(true);
1483 
1484     ui->actionAdd_preset->setEnabled(true);
1485     ui->actionRemove_preset->setEnabled(true);
1486     ui->actionEdit_preset->setEnabled(true);
1487     ui->buttonApplyPreset->setEnabled(true);
1488     ui->comboBoxMode->setEnabled(true);
1489     ui->buttonHotInputFile->setEnabled(true);
1490     ui->buttonHotOutputFile->setEnabled(true);
1491     ui->horizontalSlider_resize->setEnabled(true);
1492 
1493     ui->actionClearMetadata->setEnabled(true);
1494     ui->actionUndoMetadata->setEnabled(true);
1495     QList<QLineEdit*> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit*>();
1496     foreach (QLineEdit *lineEdit, linesEditMetadata) {
1497         lineEdit->setEnabled(true);
1498     }
1499 
1500     ui->actionUndoTitles->setEnabled(true);
1501     ui->actionClearAudioTitles->setEnabled(true);
1502     for (int stream = 0; stream < AMOUNT_AUDIO_STREAMS; stream++) {
1503         QCheckBox *checkBoxAudio = ui->frameTab_2->findChild<QCheckBox *>("checkBoxAudio_"
1504             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1505         checkBoxAudio->setEnabled(true);
1506         QLineEdit *lineEditLangAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditLangAudio_"
1507             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1508         lineEditLangAudio->setEnabled(true);
1509         QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
1510             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1511         lineEditTitleAudio->setEnabled(true);
1512     }
1513 
1514     ui->actionClearSubtitleTitles->setEnabled(true);
1515     for (int stream = 0; stream < AMOUNT_SUBTITLES; stream++) {
1516         QCheckBox *checkBoxSubtitle = ui->frameTab_3->findChild<QCheckBox *>("checkBoxSubtitle_"
1517             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1518         checkBoxSubtitle->setEnabled(true);
1519         QLineEdit *lineEditLangSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditLangSubtitle_"
1520             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1521         lineEditLangSubtitle->setEnabled(true);
1522         QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
1523             + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
1524         lineEditTitleSubtitle->setEnabled(true);
1525     }
1526     ui->actionResetLabels->setEnabled(true);
1527     ui->actionSettings->setEnabled(true);
1528     _status_encode_btn = "start";
1529     ui->actionEncode->setIcon(QIcon(":/resources/icons/16x16/cil-play.png"));
1530     ui->actionEncode->setToolTip(tr("Encode"));
1531 }
1532 
eventFilter(QObject * watched,QEvent * event)1533 bool Widget::eventFilter(QObject *watched, QEvent *event)    /*** Resize and move window ***/
1534 {
1535     if (event->type() == QEvent::KeyPress) {
1536         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
1537         if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) {
1538             ui->frame_middle->setFocus();
1539             return true;
1540         }
1541         return false;
1542     }
1543 
1544     if (event->type() == QEvent::MouseButtonRelease) // *************** Reset ************************* //
1545     {
1546         QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1547         if (mouse_event->button() == Qt::LeftButton)
1548         {
1549             QGuiApplication::restoreOverrideCursor();
1550             clickPressedFlag = false;
1551             clickPressed_Left_ResizeFlag = false;
1552             clickPressed_Left_Top_ResizeFlag = false;
1553             clickPressed_Top_ResizeFlag = false;
1554             clickPressed_Right_Top_ResizeFlag = false;
1555             clickPressed_Right_ResizeFlag = false;
1556             clickPressed_Right_Bottom_ResizeFlag = false;
1557             clickPressed_Bottom_ResizeFlag = false;
1558             clickPressed_Left_Bottom_ResizeFlag = false;
1559             return true;
1560         }
1561         return false;
1562     }
1563 
1564     if (watched == ui->centralwidget) // *************** Resize window realisation ************************* //
1565     {
1566         if (!this->isMaximized())
1567         {
1568             if (event->type() == QEvent::HoverLeave)
1569             {
1570                 QGuiApplication::restoreOverrideCursor();
1571                 return true;
1572             }
1573             if (event->type() == QEvent::HoverMove && !clickPressed_Left_ResizeFlag
1574                      && !clickPressed_Left_Top_ResizeFlag && !clickPressed_Top_ResizeFlag
1575                      && !clickPressed_Right_Top_ResizeFlag && !clickPressed_Right_ResizeFlag
1576                      && !clickPressed_Right_Bottom_ResizeFlag && !clickPressed_Bottom_ResizeFlag
1577                      && !clickPressed_Left_Bottom_ResizeFlag)
1578             {
1579                 curWidth = this->width();
1580                 curHeight = this->height();
1581                 mouseCoordinate = ui->centralwidget->mapFromGlobal(QCursor::pos());
1582                 if ((mouseCoordinate.x() < 6) && (mouseCoordinate.y() > 62) && (mouseCoordinate.y() < (curHeight - 6)))
1583                 {
1584                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
1585                     return true;
1586                 }
1587                 if ((mouseCoordinate.x() < 6) && (mouseCoordinate.y() < 6))
1588                 {
1589                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeFDiagCursor));
1590                     return true;
1591                 }
1592                 if ((mouseCoordinate.x() > 6) && (mouseCoordinate.x() < (curWidth - 120)) && (mouseCoordinate.y() < 3))
1593                 {
1594                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
1595                     return true;
1596                 }
1597                 if ((mouseCoordinate.x() > (curWidth - 6)) && (mouseCoordinate.y() < 6))
1598                 {
1599                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeBDiagCursor));
1600                     return true;
1601                 }
1602                 if ((mouseCoordinate.x() > (curWidth - 6)) && (mouseCoordinate.y() > 62) && (mouseCoordinate.y() < (curHeight - 6)))
1603                 {
1604                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
1605                     return true;
1606                 }
1607                 if ((mouseCoordinate.x() > (curWidth - 6)) && (mouseCoordinate.y() > (curHeight - 6)))
1608                 {
1609                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeFDiagCursor));
1610                     return true;
1611                 }
1612                 if ((mouseCoordinate.x() > 6) && (mouseCoordinate.x() < (curWidth - 6)) && (mouseCoordinate.y() > (curHeight - 6)))
1613                 {
1614                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
1615                     return true;
1616                 }
1617                 if ((mouseCoordinate.x() < 6) && (mouseCoordinate.y() > (curHeight - 6)))
1618                 {
1619                     QGuiApplication::setOverrideCursor(QCursor(Qt::SizeBDiagCursor));
1620                     return true;
1621                 }
1622                 QGuiApplication::restoreOverrideCursor();
1623                 return false;
1624             }
1625             if (event->type() == QEvent::MouseButtonPress)
1626             {
1627                 QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1628                 if (mouse_event->button() == Qt::LeftButton)
1629                 {
1630                     oldWidth = this->width();
1631                     oldHeight = this->height();
1632                     mouseClickCoordinate = mouse_event->pos();
1633                     if ((mouseClickCoordinate.x() < 6) && (mouseClickCoordinate.y() > 62) && (mouseClickCoordinate.y() < (oldHeight - 6)))
1634                     {
1635                         clickPressed_Left_ResizeFlag = true;
1636                         return true;
1637                     }
1638                     if ((mouseClickCoordinate.x() < 6) && (mouseClickCoordinate.y() < 6))
1639                     {
1640                         clickPressed_Left_Top_ResizeFlag = true;
1641                         return true;
1642                     }
1643                     if ((mouseClickCoordinate.x() > 6) && (mouseClickCoordinate.x() < (oldWidth - 120)) && (mouseClickCoordinate.y() < 3))
1644                     {
1645                         clickPressed_Top_ResizeFlag = true;
1646                         return true;
1647                     }
1648                     if ((mouseClickCoordinate.x() > (oldWidth - 6)) && (mouseClickCoordinate.y() < 6))
1649                     {
1650                         clickPressed_Right_Top_ResizeFlag = true;
1651                         return true;
1652                     }
1653                     if ((mouseClickCoordinate.x() > (oldWidth - 6)) && (mouseClickCoordinate.y() > 62) && (mouseClickCoordinate.y() < (oldHeight - 6)))
1654                     {
1655                         clickPressed_Right_ResizeFlag = true;
1656                         return true;
1657                     }
1658                     if ((mouseClickCoordinate.x() > (oldWidth - 6)) && (mouseClickCoordinate.y() > (oldHeight - 6)))
1659                     {
1660                         clickPressed_Right_Bottom_ResizeFlag = true;
1661                         return true;
1662                     }
1663                     if ((mouseClickCoordinate.x() > 6) && (mouseClickCoordinate.x() < (oldWidth - 6)) && (mouseClickCoordinate.y() > (oldHeight - 6)))
1664                     {
1665                         clickPressed_Bottom_ResizeFlag = true;
1666                         return true;
1667                     }
1668                     if ((mouseClickCoordinate.x() < 6) && (mouseClickCoordinate.y() > (oldHeight - 6)))
1669                     {
1670                         clickPressed_Left_Bottom_ResizeFlag = true;
1671                         return true;
1672                     }
1673                     return false;
1674                 }
1675                 return false;
1676             }
1677             if (event->type() == QEvent::MouseMove)
1678             {
1679                 QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1680                 if (mouse_event->buttons() & Qt::LeftButton)
1681                 {
1682                     int deltaX = mouse_event->globalPos().x() - mouseClickCoordinate.x();
1683                     int deltaY = mouse_event->globalPos().y() - mouseClickCoordinate.y();
1684                     int deltaWidth = static_cast<int>(mouse_event->localPos().x()) - mouseClickCoordinate.x();
1685                     int deltaHeight = static_cast<int>(mouse_event->localPos().y()) - mouseClickCoordinate.y();
1686                     if (clickPressed_Left_ResizeFlag)
1687                     {
1688                         this->setGeometry(deltaX, this->pos().y(), this->width() - deltaWidth, oldHeight);
1689                         return true;
1690                     }
1691                     if (clickPressed_Left_Top_ResizeFlag)
1692                     {
1693                         this->setGeometry(deltaX, deltaY, this->width() - deltaWidth, this->height() - deltaHeight);
1694                         return true;
1695                     }
1696                     if (clickPressed_Top_ResizeFlag)
1697                     {
1698                         this->setGeometry(this->pos().x(), deltaY, oldWidth, this->height() - deltaHeight);
1699                         return true;
1700                     }
1701                     if (clickPressed_Right_Top_ResizeFlag)
1702                     {
1703                         this->setGeometry(this->pos().x(), deltaY, oldWidth + deltaWidth, this->height() - deltaHeight);
1704                         return true;
1705                     }
1706                     if (clickPressed_Right_ResizeFlag)
1707                     {
1708                         this->setGeometry(this->pos().x(), this->pos().y(), oldWidth + deltaWidth, oldHeight);
1709                         return true;
1710                     }
1711                     if (clickPressed_Right_Bottom_ResizeFlag)
1712                     {
1713                         this->setGeometry(this->pos().x(), this->pos().y(), oldWidth + deltaWidth, oldHeight + deltaHeight);
1714                         return true;
1715                     }
1716                     if (clickPressed_Bottom_ResizeFlag)
1717                     {
1718                         this->setGeometry(this->pos().x(), this->pos().y(), oldWidth, oldHeight + deltaHeight);
1719                         return true;
1720                     }
1721                     if (clickPressed_Left_Bottom_ResizeFlag)
1722                     {
1723                         this->setGeometry(deltaX, this->pos().y(), this->width() - deltaWidth, oldHeight + deltaHeight);
1724                         return true;
1725                     }
1726                     return false;
1727                 }
1728                 return false;
1729             }
1730             return false;
1731         }
1732         return false;
1733     }
1734 
1735     if (watched == ui->frame_main) // ******** Resize right frame realisation ********************** //
1736     {
1737         if (event->type() == QEvent::HoverMove)
1738         {
1739             QGuiApplication::restoreOverrideCursor();
1740             return true;
1741         }
1742         return false;
1743     }
1744 
1745     if (watched == ui->frame_top) // *************** Drag window realisation ************************* //
1746     {
1747         if (event->type() == QEvent::MouseButtonPress)
1748         {
1749             QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1750             if (mouse_event->button() == Qt::LeftButton)
1751             {
1752                 mouseClickCoordinate = mouse_event->pos();
1753                 clickPressedFlag = true;
1754                 return true;
1755             }
1756             return false;
1757         }
1758         if ((event->type() == QEvent::MouseMove) && clickPressedFlag == true)
1759         {
1760             QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1761             if (mouse_event->buttons() & Qt::LeftButton)
1762             {
1763                 if (this->isMaximized())
1764                 {
1765                     on_expandWindow_clicked();
1766                 }
1767                 this->move(mouse_event->globalPos() - mouseClickCoordinate);
1768                 return true;
1769             }
1770             return false;
1771         }
1772         if (event->type() == QEvent::MouseButtonDblClick)
1773         {
1774             QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1775             if (mouse_event->buttons() & Qt::LeftButton)
1776             {
1777                 on_expandWindow_clicked();
1778                 return true;
1779             }
1780             return false;
1781         }
1782         return false;
1783     }
1784 
1785     if (watched == raiseThumb) // ************** Click thumb realisation ************** //
1786     {
1787         if (event->type() == QEvent::MouseButtonPress)
1788         {
1789             QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1790             if (mouse_event->button() == Qt::LeftButton)
1791             {
1792                 on_actionAdd_clicked();
1793                 return true;
1794             }
1795             return false;
1796         }
1797         return false;
1798     }
1799     return QWidget::eventFilter(watched, event);
1800 }
1801 
1802 /************************************************
1803 ** Encoder
1804 ************************************************/
1805 
make_preset()1806 void Widget::make_preset()  /*** Make preset ***/
1807 {
1808     std::cout << "Make preset..." << std::endl;                       // Debug information //
1809     int _CODEC = _cur_param[curParamIndex::CODEC].toInt();
1810     int _MODE = _cur_param[curParamIndex::MODE].toInt();
1811     int _CONTAINER = _cur_param[curParamIndex::CONTAINER].toInt();
1812     QString _BQR = _cur_param[curParamIndex::BQR];
1813     QString _MINRATE = _cur_param[curParamIndex::MINRATE];
1814     QString _MAXRATE = _cur_param[curParamIndex::MAXRATE];
1815     QString _BUFSIZE = _cur_param[curParamIndex::BUFSIZE];
1816     int _LEVEL = _cur_param[curParamIndex::LEVEL].toInt();
1817     int _FRAME_RATE = _cur_param[curParamIndex::FRAME_RATE].toInt();
1818     int _BLENDING = _cur_param[curParamIndex::BLENDING].toInt();
1819     int _WIDTH = _cur_param[curParamIndex::WIDTH].toInt();
1820     int _HEIGHT = _cur_param[curParamIndex::HEIGHT].toInt();
1821     int _PASS = _cur_param[curParamIndex::PASS].toInt();
1822     int _PRESET = _cur_param[curParamIndex::PRESET].toInt();
1823     int _COLOR_RANGE = _cur_param[curParamIndex::COLOR_RANGE].toInt();
1824     int _MATRIX = _cur_param[curParamIndex::MATRIX].toInt();
1825     int _PRIMARY = _cur_param[curParamIndex::PRIMARY].toInt();
1826     int _TRC = _cur_param[curParamIndex::TRC].toInt();
1827     QString _MIN_LUM = _cur_param[curParamIndex::MIN_LUM].replace(",", ".");
1828     QString _MAX_LUM = _cur_param[curParamIndex::MAX_LUM].replace(",", ".");
1829     QString _MAX_CLL = _cur_param[curParamIndex::MAX_CLL].replace(",", ".");
1830     QString _MAX_FALL = _cur_param[curParamIndex::MAX_FALL].replace(",", ".");
1831     int _MASTER_DISPLAY = _cur_param[curParamIndex::MASTER_DISPLAY].toInt();
1832     QString _CHROMA_COORD = _cur_param[curParamIndex::CHROMA_COORD];
1833     QString _WHITE_COORD = _cur_param[curParamIndex::WHITE_COORD];
1834     int _AUDIO_CODEC = _cur_param[curParamIndex::AUDIO_CODEC].toInt();
1835     int _AUDIO_BITRATE = _cur_param[curParamIndex::AUDIO_BITRATE].toInt();
1836     int _AUDIO_SAMPLING = _cur_param[curParamIndex::ASAMPLE_RATE].toInt();
1837     int _AUDIO_CHANNELS = _cur_param[curParamIndex::ACHANNELS].toInt();
1838     int _REP_PRIM = _cur_param[curParamIndex::REP_PRIM].toInt();
1839     int _REP_MATRIX = _cur_param[curParamIndex::REP_MATRIX].toInt();
1840     int _REP_TRC = _cur_param[curParamIndex::REP_TRC].toInt();
1841 
1842     _preset_0 = "";
1843     _preset_pass1 = "";
1844     _preset = "";
1845     _preset_mkvmerge = "";
1846     _sub_mux_param = "";
1847     _error_message = "";
1848     _flag_two_pass = false;
1849     _flag_hdr = false;
1850     _mux_mode = false;
1851     _fr_count = 0;
1852     ui->textBrowser_log->clear();
1853 
1854     /****************************************** Resize ****************************************/
1855 
1856     QString width[16] = {
1857         "Source", "7680", "4520", "4096", "3840", "3656", "2048", "1920",
1858         "1828",   "1440", "1280", "1024", "768",  "720",  "640",  "320"
1859     };
1860 
1861     QString height[32] = {
1862         "Source", "4320", "3112", "3072", "2664", "2540", "2468", "2304",
1863         "2214",   "2204", "2160", "2056", "1976", "1744", "1556", "1536",
1864         "1332",   "1234", "1152", "1107", "1102", "1080", "1028", "988",
1865         "872",    "768",  "720",  "576",  "540",  "486",  "480",  "240"
1866     };
1867 
1868     QString resize_vf = "";
1869     if ((width[_WIDTH] != "Source") && (height[_HEIGHT] != "Source")) {
1870         resize_vf = QString("scale=%1:%2,setsar=1:1").arg(width[_WIDTH], height[_HEIGHT]);
1871     }
1872     else if ((width[_WIDTH] != "Source") && (height[_HEIGHT] == "Source")) {
1873         resize_vf = QString("scale=%1:%2,setsar=1:1").arg(width[_WIDTH], _height);
1874     }
1875     else if ((width[_WIDTH] == "Source") && (height[_HEIGHT] != "Source")) {
1876         resize_vf = QString("scale=%1:%2,setsar=1:1").arg(_width, height[_HEIGHT]);
1877     }
1878 
1879     /******************************************* FPS *****************************************/
1880 
1881     QString frame_rate[14] = {
1882         "Source", "120", "60", "59.940", "50", "48", "30",
1883         "29.970", "25",  "24", "23.976", "20", "18", "16"
1884     };
1885 
1886     QString blending[4] = {
1887         "Simple", "Interpolated", "MCI", "Blend"
1888     };
1889 
1890     QString fps_vf = "";
1891     double fps_dest;
1892 
1893     if (frame_rate[_FRAME_RATE] != "Source") {
1894         fps_dest = frame_rate[_FRAME_RATE].toDouble();
1895         if (blending[_BLENDING] == "Simple") {
1896             fps_vf = QString("fps=fps=%1").arg(frame_rate[_FRAME_RATE]);
1897         }
1898         else if (blending[_BLENDING] == "Interpolated") {
1899             fps_vf = QString("framerate=fps=%1").arg(frame_rate[_FRAME_RATE]);
1900         }
1901         else if (blending[_BLENDING] == "MCI") {
1902             fps_vf = QString("minterpolate=fps=%1:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:vsbmc=1")
1903                     .arg(frame_rate[_FRAME_RATE]);
1904         }
1905         else if (blending[_BLENDING] == "Blend") {
1906             fps_vf = QString("minterpolate=fps=%1:mi_mode=blend").arg(frame_rate[_FRAME_RATE]);
1907         }
1908     } else {
1909         fps_dest = _fps.toDouble();
1910     }
1911 
1912     /****************************************** Split ****************************************/
1913 
1914     QString _splitStartParam = "";
1915     QString _splitParam = "";
1916 
1917     if (_endTime > 0 && _startTime < _endTime) {
1918         double duration = _endTime - _startTime;
1919         _fr_count = static_cast<int>(round(duration * fps_dest));
1920         int startFrame = static_cast<int>(round(_startTime * fps_dest));
1921         int endFrame = static_cast<int>(round(_endTime * fps_dest));
1922         int amountFrames = endFrame - startFrame;
1923         _splitStartParam = QString(" -ss %1").arg(QString::number(_startTime, 'f', 3));
1924         _splitParam = QString("-vframes %1 ").arg(QString::number(amountFrames));
1925     } else {
1926         _fr_count = static_cast<int>(round(_dur * fps_dest));
1927     }
1928 
1929     /************************************** Video metadata ************************************/
1930 
1931     QString videoMetadata[6] = {"", "", "", "", "", ""};
1932     QString _videoMetadataParam = "";
1933     QString globalTitle = ui->lineEditGlobalTitle->text();
1934 
1935     if (globalTitle != "") {
1936         videoMetadata[0] = QString("-metadata:s:v:0 title=%1 ").arg(globalTitle.replace(" ", "\u00A0"));
1937     } else {
1938         if (_videoMetadata[VIDEO_TITLE] != "") {
1939             videoMetadata[0] = QString("-metadata:s:v:0 title=%1 ").arg(_videoMetadata[VIDEO_TITLE]
1940                                                                         .replace(" ", "\u00A0"));
1941         } else {
1942             videoMetadata[0] = QString("-map_metadata:s:v:0 -1 ");
1943         }
1944     }
1945     if (_videoMetadata[VIDEO_MOVIENAME] != "") {
1946         videoMetadata[1] = QString("-metadata title=%1 ").arg(_videoMetadata[VIDEO_MOVIENAME]
1947                                                               .replace(" ", "\u00A0"));
1948     }
1949     if (_videoMetadata[VIDEO_AUTHOR] != "") {
1950         videoMetadata[2] = QString("-metadata author=%1 ").arg(_videoMetadata[VIDEO_AUTHOR]
1951                                                                .replace(" ", "\u00A0"));
1952     }
1953     if (_videoMetadata[VIDEO_DESCRIPTION] != "") {
1954         videoMetadata[3] = QString("-metadata description=%1 ").arg(_videoMetadata[VIDEO_DESCRIPTION]
1955                                                                     .replace(" ", "\u00A0"));
1956     }
1957     if (_videoMetadata[VIDEO_YEAR] != "") {
1958         videoMetadata[4] = QString("-metadata year=%1 ").arg(_videoMetadata[VIDEO_YEAR].replace(" ", ""));
1959     }
1960     if (_videoMetadata[VIDEO_PERFORMER] != "") {
1961         videoMetadata[5] = QString("-metadata author=%1 ").arg(_videoMetadata[VIDEO_PERFORMER]
1962                                                                .replace(" ", "\u00A0"));
1963     }
1964     for (int i = 0; i < 6; i++) {
1965         _videoMetadataParam += videoMetadata[i];
1966     }
1967 
1968     /************************************** Audio streams ************************************/
1969 
1970     QString audioLang[AMOUNT_AUDIO_STREAMS] = {"", "", "", "", "", "", "", "", ""};
1971     QString audioTitle[AMOUNT_AUDIO_STREAMS] = {"", "", "", "", "", "", "", "", ""};
1972     QString audioMap[AMOUNT_AUDIO_STREAMS] = {"", "", "", "", "", "", "", "", ""};
1973     QString _audioMapParam = "";
1974     QString _audioMetadataParam = "";
1975     int countDestAudioStream = 0;
1976 
1977     for (int k = 0; k < AMOUNT_AUDIO_STREAMS; k++) {
1978         if (_audioStreamCheckState[k] == 1) {
1979             audioMap[k] = QString("-map 0:a:%1? ").arg(QString::number(k));
1980             audioLang[k] = QString("-metadata:s:a:%1 language=%2 ")
1981                            .arg(QString::number(countDestAudioStream), _audioLang[k].replace(" ", "\u00A0"));
1982             audioTitle[k] = QString("-metadata:s:a:%1 title=%2 ")
1983                             .arg(QString::number(countDestAudioStream), _audioTitle[k].replace(" ", "\u00A0"));
1984             countDestAudioStream++;
1985         }
1986         _audioMapParam += audioMap[k];
1987         _audioMetadataParam += audioLang[k] + audioTitle[k];
1988     }
1989 
1990     /**************************************** Subtitles **************************************/
1991 
1992     QString subtitleLang[AMOUNT_SUBTITLES] = {"", "", "", "", "", "", "", "", ""};
1993     QString subtitleTitle[AMOUNT_SUBTITLES] = {"", "", "", "", "", "", "", "", ""};
1994     QString subtitleMap[AMOUNT_SUBTITLES] = {"", "", "", "", "", "", "", "", ""};
1995     QString _subtitleMapParam = "";
1996     QString _subtitleMetadataParam = "";
1997     int countDestSubtitleStream = 0;
1998 
1999     for (int k = 0; k < AMOUNT_SUBTITLES; k++) {
2000         if (_subtitleCheckState[k] == 1) {
2001             subtitleMap[k] = QString("-map 0:s:%1? ").arg(QString::number(k));
2002             subtitleLang[k] = QString("-metadata:s:s:%1 language=%2 ")
2003                            .arg(QString::number(countDestSubtitleStream), _subtitleLang[k].replace(" ", "\u00A0"));
2004             subtitleTitle[k] = QString("-metadata:s:s:%1 title=%2 ")
2005                             .arg(QString::number(countDestSubtitleStream), _subtitleTitle[k].replace(" ", "\u00A0"));
2006             countDestSubtitleStream++;
2007         }
2008         _subtitleMapParam += subtitleMap[k];
2009         _subtitleMetadataParam += subtitleLang[k] + subtitleTitle[k];
2010     }
2011 
2012     /*********************************** Intel QSV presets ************************************/
2013     QString intelQSV_filter = "hwmap=derive_device=qsv,format=qsv";
2014 #if defined (Q_OS_WIN64)
2015     QString intelQSVhwaccel = " -hwaccel dxva2 -hwaccel_output_format dxva2_vld";
2016 #elif defined (Q_OS_UNIX)
2017     QString intelQSVhwaccel = " -hwaccel vaapi -hwaccel_output_format vaapi";
2018 #endif
2019 
2020     /************************************* XDCAM presets **************************************/
2021     QString xdcam_preset = "-pix_fmt yuv422p -c:v mpeg2video -profile:v 0 -flags ilme -top 1 "
2022                            "-metadata creation_time=now -vtag xd5c -timecode 01:00:00:00 ";
2023 
2024     /************************************* XAVC presets **************************************/
2025     QString xavc_preset = "-pix_fmt yuv422p -c:v libx264 -me_method tesa -subq 9 -partitions all -direct-pred auto "
2026                           "-psy 0 -g 0 -keyint_min 0 -x264opts filler -x264opts force-cfr -tune fastdecode ";
2027 
2028     /************************************* Codec module ***************************************/
2029 
2030     QString arr_codec[NUMBER_PRESETS][4] = {
2031         {"-pix_fmt yuv420p12le -c:v libx265 -profile:v main12 ",        "",                     "1", ""},
2032         {"-pix_fmt yuv420p10le -c:v libx265 -profile:v main10 ",        "",                     "1", ""},
2033         {"-pix_fmt yuv420p -c:v libx265 -profile:v main ",              "",                     "0", ""},
2034         {"-pix_fmt yuv420p -c:v libx264 -profile:v high ",              "",                     "0", ""},
2035         {"-pix_fmt yuv420p10le -c:v libvpx-vp9 -speed 4 -profile:v 2 ", "",                     "1", ""},
2036         {"-pix_fmt yuv420p -c:v libvpx-vp9 -speed 4 ",                  "",                     "0", ""},
2037         {"-c:v hevc_qsv -profile:v main10 ",                            intelQSVhwaccel,   "1", intelQSV_filter},
2038         {"-pix_fmt qsv -c:v hevc_qsv -profile:v main ",                 intelQSVhwaccel,   "0", intelQSV_filter},
2039         {"-pix_fmt qsv -c:v h264_qsv -profile:v high ",                 intelQSVhwaccel,   "0", intelQSV_filter},
2040         {"-c:v vp9_qsv -profile:v 2 ",                                  intelQSVhwaccel,   "1", intelQSV_filter},
2041         {"-pix_fmt qsv -c:v vp9_qsv ",                                  intelQSVhwaccel,   "0", intelQSV_filter},
2042         {"-pix_fmt qsv -c:v mpeg2_qsv -profile:v high ",                intelQSVhwaccel,   "0", intelQSV_filter},
2043         {"-pix_fmt p010le -c:v hevc_nvenc -profile:v main10 ",          " -hwaccel cuda",       "1", ""},
2044         {"-pix_fmt yuv420p -c:v hevc_nvenc -profile:v main ",           " -hwaccel cuda",       "0", ""},
2045         {"-pix_fmt yuv420p -c:v h264_nvenc -profile:v high ",           " -hwaccel cuda",       "0", ""},
2046         {"-pix_fmt yuv422p10le -c:v prores_ks -profile:v 0 ",           "",                     "1", ""},
2047         {"-pix_fmt yuv422p10le -c:v prores_ks -profile:v 1 ",           "",                     "1", ""},
2048         {"-pix_fmt yuv422p10le -c:v prores_ks -profile:v 2 ",           "",                     "1", ""},
2049         {"-pix_fmt yuv422p10le -c:v prores_ks -profile:v 3 ",           "",                     "1", ""},
2050         {"-pix_fmt yuv444p10le -c:v prores_ks -profile:v 4 ",           "",                     "1", ""},
2051         {"-pix_fmt yuv444p10le -c:v prores_ks -profile:v 5 ",           "",                     "1", ""},
2052         {"-pix_fmt yuv422p -c:v dnxhd -profile:v dnxhr_lb ",            "",                     "0", ""},
2053         {"-pix_fmt yuv422p -c:v dnxhd -profile:v dnxhr_sq ",            "",                     "0", ""},
2054         {"-pix_fmt yuv422p -c:v dnxhd -profile:v dnxhr_hq ",            "",                     "0", ""},
2055         {"-pix_fmt yuv422p10le -c:v dnxhd -profile:v dnxhr_hqx ",       "",                     "1", ""},
2056         {"-pix_fmt yuv444p10le -c:v dnxhd -profile:v dnxhr_444 ",       "",                     "1", ""},
2057         {xdcam_preset,                                                  "",                     "0", ""},
2058         {xavc_preset,                                                   " -guess_layout_max 0", "0", ""},
2059         {"-movflags +write_colr -c:v copy ",                            "",                     "1", ""}
2060     };
2061 
2062     QString hwaccel = arr_codec[_CODEC][1];
2063     QString hwaccel_filter_vf = arr_codec[_CODEC][3];
2064     _flag_hdr = static_cast<bool>(arr_codec[_CODEC][2].toInt());
2065 
2066     /************************************* Level module **************************************/
2067 
2068     QString arr_level[NUMBER_PRESETS][21] = {
2069         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2070         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2071         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2072         {"Auto", "1", "1b", "1.1", "1.2", "1.3", "2", "2.1", "2.2", "3",   "3.1", "3.2", "4",   "4.1", "4.2", "5", "5.1", "5.2", "6", "6.1", "6.2"},
2073         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2074         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2075         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2076         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2077         {"Auto", "1", "1b", "1.1", "1.2", "1.3", "2", "2.1", "2.2", "3",   "3.1", "3.2", "4",   "4.1", "4.2", "5", "5.1", "5.2", "6", "6.1", "6.2"},
2078         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2079         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2080         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2081         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2082         {"Auto", "1", "2",  "2.1", "3",   "3.1", "4", "4.1", "5",   "5.1", "5.2", "6",   "6.1", "6.2", "",    "",  "",    "",    "",  "",    ""},
2083         {"Auto", "1", "1b", "1.1", "1.2", "1.3", "2", "2.1", "2.2", "3",   "3.1", "3.2", "4",   "4.1", "4.2", "5", "5.1", "5.2", "6", "6.1", "6.2"},
2084         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2085         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2086         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2087         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2088         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2089         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2090         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2091         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2092         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2093         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2094         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2095         {"2",    "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2096         {"5.2",  "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""},
2097         {"Auto", "",  "",   "",    "",    "",    "",  "",    "",    "",    "",    "",    "",    "",    "",    "",  "",    "",    "",  "",    ""}
2098     };
2099 
2100     QString level = "";
2101     QString selected_level = arr_level[_CODEC][_LEVEL];
2102     if (selected_level != "" && selected_level != "Auto") {
2103         level = QString("-level:v %1 ").arg(selected_level);
2104     }
2105 
2106     /************************************* Mode module ***************************************/
2107 
2108     QString arr_mode[NUMBER_PRESETS][5] = {
2109         {"CBR",    "ABR", "VBR", "CRF", "CQP"},
2110         {"CBR",    "ABR", "VBR", "CRF", "CQP"},
2111         {"CBR",    "ABR", "VBR", "CRF", "CQP"},
2112         {"CBR",    "ABR", "VBR", "CRF", "CQP"},
2113         {"ABR",    "CRF", "",    "",    ""},
2114         {"ABR",    "CRF", "",    "",    ""},
2115         {"VBR",    "",    "",    "",    ""},
2116         {"VBR",    "",    "",    "",    ""},
2117         {"VBR",    "",    "",    "",    ""},
2118         {"ABR",    "CRF", "",    "",    ""},
2119         {"ABR",    "CRF", "",    "",    ""},
2120         {"VBR",    "",    "",    "",    ""},
2121         {"VBR_NV", "",    "",    "",    ""},
2122         {"VBR_NV", "",    "",    "",    ""},
2123         {"VBR_NV", "",    "",    "",    ""},
2124         {"",       "",    "",    "",    ""},
2125         {"",       "",    "",    "",    ""},
2126         {"",       "",    "",    "",    ""},
2127         {"",       "",    "",    "",    ""},
2128         {"",       "",    "",    "",    ""},
2129         {"",       "",    "",    "",    ""},
2130         {"",       "",    "",    "",    ""},
2131         {"",       "",    "",    "",    ""},
2132         {"",       "",    "",    "",    ""},
2133         {"",       "",    "",    "",    ""},
2134         {"",       "",    "",    "",    ""},
2135         {"VBR",    "",    "",    "",    ""},
2136         {"CBR",    "",    "",    "",    ""},
2137         {"",       "",    "",    "",    ""}
2138     };
2139     QString mode = "";
2140     QString bitrate = QString::number(1000000.0*_BQR.toDouble(), 'f', 0);
2141     QString minrate = QString::number(1000000.0*_MINRATE.toDouble(), 'f', 0);
2142     QString maxrate = QString::number(1000000.0*_MAXRATE.toDouble(), 'f', 0);
2143     QString bufsize = QString::number(1000000.0*_BUFSIZE.toDouble(), 'f', 0);
2144     QString selected_mode = arr_mode[_CODEC][_MODE];
2145 
2146     if (selected_mode == "CBR") {
2147         mode = QString("-b:v %1 -minrate %1 -maxrate %1 -bufsize %2 ").arg(bitrate, bufsize);
2148     }
2149     else if (selected_mode == "ABR") {
2150         mode = QString("-b:v %1 ").arg(bitrate);
2151     }
2152     else if (selected_mode == "VBR") {
2153         mode = QString("-b:v %1 -minrate %2 -maxrate %3 -bufsize %4 ").arg(bitrate, minrate, maxrate, bufsize);
2154     }
2155     else if (selected_mode == "VBR_NV") {
2156         mode = QString("-b:v %1 -minrate %2 -maxrate %3 -bufsize %4 -rc vbr_hq ").arg(bitrate, minrate, maxrate, bufsize);
2157     }
2158     else if (selected_mode == "CRF") {
2159         mode = QString("-crf %1 ").arg(_BQR);
2160     }
2161     else if (selected_mode == "CQP") {
2162         mode = QString("-b:v 0 -cq %1 -qmin %1 -qmax %1 ").arg(_BQR);
2163     }
2164 
2165     /************************************* Preset module ***************************************/
2166 
2167     QString arr_preset[NUMBER_PRESETS][10] = {
2168         {"None", "Ultrafast", "Superfast", "Veryfast", "Faster", "Fast", "Medium", "Slow",     "Slower", "Veryslow"},
2169         {"None", "Ultrafast", "Superfast", "Veryfast", "Faster", "Fast", "Medium", "Slow",     "Slower", "Veryslow"},
2170         {"None", "Ultrafast", "Superfast", "Veryfast", "Faster", "Fast", "Medium", "Slow",     "Slower", "Veryslow"},
2171         {"None", "Ultrafast", "Superfast", "Veryfast", "Faster", "Fast", "Medium", "Slow",     "Slower", "Veryslow"},
2172         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2173         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2174         {"None", "Veryfast",  "Faster",    "Fast",     "Medium", "Slow", "Slower", "Veryslow", "",       ""},
2175         {"None", "Veryfast",  "Faster",    "Fast",     "Medium", "Slow", "Slower", "Veryslow", "",       ""},
2176         {"None", "Veryfast",  "Faster",    "Fast",     "Medium", "Slow", "Slower", "Veryslow", "",       ""},
2177         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2178         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2179         {"None", "Veryfast",  "Faster",    "Fast",     "Medium", "Slow", "Slower", "Veryslow", "",       ""},
2180         {"None", "Slow",      "",          "",         "",       "",     "",       "",         "",       ""},
2181         {"None", "Slow",      "",          "",         "",       "",     "",       "",         "",       ""},
2182         {"None", "Slow",      "",          "",         "",       "",     "",       "",         "",       ""},
2183         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2184         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2185         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2186         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2187         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2188         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2189         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2190         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2191         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2192         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2193         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2194         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""},
2195         {"None", "Ultrafast", "Superfast", "Veryfast", "Faster", "Fast", "Medium", "Slow",     "Slower", "Veryslow"},
2196         {"",     "",          "",          "",         "",       "",     "",       "",         "",       ""}
2197     };
2198     QString preset = "";
2199     QString selected_preset = arr_preset[_CODEC][_PRESET];
2200     if (selected_preset != "" && selected_preset != "None") {
2201         preset = QString("-preset ") + selected_preset.toLower() + QString(" ");
2202     }
2203 
2204     /************************************* Pass module ***************************************/
2205 
2206     QString arr_pass[NUMBER_PRESETS][2] = {
2207         {"",                     "-x265-params pass=2 "},
2208         {"",                     "-x265-params pass=2 "},
2209         {"",                     "-x265-params pass=2 "},
2210         {"",                     "-pass 2 "},
2211         {"",                     "-pass 2 "},
2212         {"",                     "-pass 2 "},
2213         {"",                     ""},
2214         {"",                     ""},
2215         {"",                     ""},
2216         {"",                     ""},
2217         {"",                     ""},
2218         {"",                     ""},
2219         {"-2pass 1 ",            ""},
2220         {"-2pass 1 ",            ""},
2221         {"-2pass 1 ",            ""},
2222         {"",                     ""},
2223         {"",                     ""},
2224         {"",                     ""},
2225         {"",                     ""},
2226         {"",                     ""},
2227         {"",                     ""},
2228         {"",                     ""},
2229         {"",                     ""},
2230         {"",                     ""},
2231         {"",                     ""},
2232         {"",                     ""},
2233         {"",                     ""},
2234         {"",                     ""},
2235         {"",                     ""}
2236     };
2237     QString pass1 = "";
2238     QString pass = arr_pass[_CODEC][_PASS];
2239     if (pass == "-x265-params pass=2 ") {
2240         pass1 = "-x265-params pass=1 ";
2241         _flag_two_pass = true;
2242     }
2243     if (pass == "-pass 2 ") {
2244         pass1 = "-pass 1 ";
2245         _flag_two_pass = true;
2246     }
2247 
2248     /************************************* Audio module ***************************************/
2249 
2250     QString arr_acodec[NUMBER_PRESETS][6] = {
2251         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2252         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2253         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2254         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2255         {"Opus",  "Vorbis", "Source", "",       "",     ""},
2256         {"Opus",  "Vorbis", "Source", "",       "",     ""},
2257         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2258         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2259         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2260         {"Opus",  "Vorbis", "Source", "",       "",     ""},
2261         {"Opus",  "Vorbis", "Source", "",       "",     ""},
2262         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2263         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2264         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2265         {"AAC",   "AC3",    "DTS",    "Source", "",     ""},
2266         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2267         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2268         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2269         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2270         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2271         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2272         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2273         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2274         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2275         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2276         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2277         {"PCM16", "",       "",       "",       "",     ""},
2278         {"PCM16", "PCM24",  "PCM32",  "",       "",     ""},
2279         {"AAC",   "AC3",    "DTS",    "Vorbis", "Opus", "Source"}
2280     };
2281 
2282     QString arr_bitrate[5][17] = {
2283         {"384k",  "320k",  "256k",  "192k",  "128k",  "96k",   "",      "",      "",      "",      "",     "",     "",     "",     "",     "",     ""}, // AAC
2284         {"640k",  "448k",  "384k",  "256k",  "",      "",      "",      "",      "",      "",      "",     "",     "",     "",     "",     "",     ""}, // AC3
2285         {"3840k", "3072k", "2048k", "1920k", "1536k", "1472k", "1344k", "1280k", "1152k", "1024k", "960k", "768k", "640k", "576k", "512k", "448k", "384k"}, // DTS
2286         {"448k",  "384k",  "256k",  "128k",  "96k",   "64k",   "",      "",      "",      "",      "",     "",     "",     "",     "",     "",     ""}, // Vorbis
2287         {"448k",  "384k",  "256k",  "128k",  "96k",   "64k",   "",      "",      "",      "",      "",     "",     "",     "",     "",     "",     ""} // Opus
2288     };
2289 
2290     QString arr_sampling[12] = {
2291         "Source", "8000",  "11025", "16000", "22050",  "32000",
2292         "44100",  "48000", "88200", "96000", "176400", "192000"
2293     };
2294 
2295     QString arr_channels[3] = {
2296         "Source", "1", "2"
2297     };
2298 
2299     QString acodec = "";
2300     QString selected_acodec = arr_acodec[_CODEC][_AUDIO_CODEC];
2301     QString selected_bitrate = "";
2302 
2303     QString sampling = "";
2304     QString selected_sampling = arr_sampling[_AUDIO_SAMPLING];
2305     if (selected_sampling != "Source") {
2306         sampling = QString("-af aresample=%1:resampler=soxr ").arg(selected_sampling);
2307     }
2308 
2309     QString channels = "";
2310     QString selected_channels = arr_channels[_AUDIO_CHANNELS];
2311     if (selected_channels != "Source") {
2312         channels = QString(" -ac %1").arg(selected_channels);
2313     }
2314 
2315 
2316     if (selected_acodec == "AAC") {
2317         selected_bitrate = arr_bitrate[0][_AUDIO_BITRATE];
2318         acodec = QString("-c:a aac -b:a %1").arg(selected_bitrate);
2319     }
2320     else if (selected_acodec == "AC3") {
2321         selected_bitrate = arr_bitrate[1][_AUDIO_BITRATE];
2322         acodec = QString("-c:a ac3 -b:a %1").arg(selected_bitrate);
2323     }
2324     else if (selected_acodec == "DTS") {
2325         selected_bitrate = arr_bitrate[2][_AUDIO_BITRATE];
2326         acodec = QString("-strict -2 -c:a dca -b:a %1").arg(selected_bitrate);
2327     }
2328     else if (selected_acodec == "Vorbis") {
2329         selected_bitrate = arr_bitrate[3][_AUDIO_BITRATE];
2330         acodec = QString("-c:a libvorbis -b:a %1").arg(selected_bitrate);
2331     }
2332     else if (selected_acodec == "Opus") {
2333         selected_bitrate = arr_bitrate[4][_AUDIO_BITRATE];
2334         acodec = QString("-c:a libopus -b:a %1").arg(selected_bitrate);
2335     }
2336     else if (selected_acodec == "PCM16") {
2337         acodec = "-c:a pcm_s16le";
2338     }
2339     else if (selected_acodec == "PCM24") {
2340         acodec = "-c:a pcm_s24le";
2341     }
2342     else if (selected_acodec == "PCM32") {
2343         acodec = "-c:a pcm_s32le";
2344     }
2345     else if (selected_acodec == "Source") {
2346         acodec = "-c:a copy";
2347     }
2348     QString audio_param = sampling + acodec + channels;
2349 
2350     /************************************ Subtitle module *************************************/
2351 
2352     QString sub_param("");
2353     QString container = updateFieldContainer(_CODEC, _CONTAINER);
2354     if (container == "MKV") {
2355         _sub_mux_param = QString("-c:s copy");
2356     }
2357     else if (container == "WebM") {
2358         _sub_mux_param = QString("-c:s webvtt");
2359     }
2360     else if (container == "MP4" || container == "MOV") {
2361         _sub_mux_param = QString("-c:s mov_text");
2362     }
2363     else {
2364         _sub_mux_param = QString("-sn");
2365     }
2366 
2367     if (_flag_hdr) {
2368         sub_param = QString(" -c:s copy");
2369     }
2370     else {
2371         sub_param = QString(" ") + _sub_mux_param;
2372     }
2373 
2374     /************************************* Color module ***************************************/
2375 
2376     // color primaries
2377 
2378     QString arr_colorprim[11] = {
2379         "Source",    "bt470m",   "bt470bg",  "bt709",    "bt2020", "smpte170m",
2380         "smpte240m", "smpte428", "smpte431", "smpte432", "film"
2381     };
2382     QMap<QString, QString> curr_colorprim = {
2383         {"BT709",           "bt709"},
2384         {"BT2020",          "bt2020"},
2385         {"BT601 NTSC",      "smpte170m"},
2386         {"BT601 PAL",       "bt470bg"},
2387         {"BT470 System M",  "bt470m"},
2388         {"SMPTE 240M",      "smpte240m"},
2389         {"Generic film",    "film"},
2390         {"DCI P3",          "smpte431"},
2391         {"XYZ",             "smpte428"},
2392         {"Display P3",      "smpte432"},
2393         {"",                ""}
2394     };
2395 
2396     QString colorprim = "";
2397     QString colorprim_vf = "";
2398     QString selected_colorprim = arr_colorprim[_PRIMARY];
2399     if (!curr_colorprim.contains(_hdr[CUR_COLOR_PRIMARY])) {
2400         restore_initial_state();
2401         _message = tr("Can\'t find color primaries %1 in source map.").arg(_hdr[CUR_COLOR_PRIMARY]);
2402         call_task_complete(_message, false);
2403         return;
2404     }
2405     if (selected_colorprim == "Source") {
2406         if (_hdr[CUR_COLOR_PRIMARY] != "") {
2407             colorprim = QString("-color_primaries %1 ").arg(curr_colorprim[_hdr[CUR_COLOR_PRIMARY]]);
2408         }
2409     }
2410     else {
2411         colorprim = QString("-color_primaries %1 ").arg(selected_colorprim);
2412         if (_REP_PRIM == 2) {
2413             colorprim_vf = QString("zscale=p=%1").arg(selected_colorprim);
2414         } else {
2415 
2416         }
2417     }
2418 
2419     // color matrix
2420 
2421     QString arr_colormatrix[14] = {
2422         "Source", "bt470bg", "bt709", "bt2020nc", "bt2020c", "smpte170m", "smpte240m",
2423         "smpte2085", "chroma-derived-nc", "chroma-derived-c", "fcc", "GBR", "ICtCp", "YCgCo"
2424     };
2425     QMap<QString, QString> curr_colormatrix = {
2426         {"BT709",                   "bt709"},
2427         {"BT2020nc",                "bt2020nc"},
2428         {"BT2020c",                 "bt2020c"},
2429         {"FCC73682",                "fcc"},
2430         {"BT470SystemB/G",          "bt470bg"},
2431         {"SMPTE240M",               "smpte240m"},
2432         {"YCgCo",                   "YCgCo"},
2433         {"Y'D'zD'x",                "smpte2085"},
2434         {"Chromaticity-derivednc",  "chroma-derived-nc"},
2435         {"Chromaticity-derivedc",   "chroma-derived-c"},
2436         {"ICtCp",                   "ICtCp"},
2437         {"BT601",                   "smpte170m"},
2438         {"Identity",                "GBR"},
2439         {"",                        ""}
2440     };
2441 
2442     QString colormatrix = "";
2443     QString colormatrix_vf = "";
2444     QString selected_colormatrix = arr_colormatrix[_MATRIX];
2445     if (!curr_colormatrix.contains(_hdr[CUR_COLOR_MATRIX])) {
2446         restore_initial_state();
2447         _message = tr("Can\'t find color matrix %1 in source map.").arg(_hdr[CUR_COLOR_MATRIX]);
2448         call_task_complete(_message, false);
2449         return;
2450     }
2451     if (selected_colormatrix == "Source") {
2452         if (_hdr[CUR_COLOR_MATRIX] != "") {
2453             colormatrix = QString("-colorspace %1 ").arg(curr_colormatrix[_hdr[CUR_COLOR_MATRIX]]);
2454         }
2455     }
2456     else {
2457         colormatrix = QString("-colorspace %1 ").arg(selected_colormatrix);
2458         if (_REP_MATRIX == 2) {
2459             colormatrix_vf = QString("zscale=m=%1").arg(selected_colormatrix);
2460         } else {
2461 
2462         }
2463     }
2464 
2465     // transfer characteristics
2466 
2467     QString arr_trc[17] = {
2468         "Source", "bt470m", "bt470bg", "bt709", "bt1361e", "bt2020-10", "bt2020-12", "smpte170m",
2469         "smpte240m", "smpte428", "smpte2084", "arib-std-b67", "linear", "log100", "log316",
2470         "iec61966-2-1", "iec61966-2-4"
2471     };
2472     QMap<QString, QString> curr_transfer = {
2473         {"BT709",                    "bt709"},
2474         {"PQ",                       "smpte2084"},
2475         {"HLG",                      "arib-std-b67"},
2476         {"BT2020 (10-bit)",          "bt2020-10"},
2477         {"BT2020 (12-bit)",          "bt2020-12"},
2478         {"BT470 System M",           "bt470m"},
2479         {"BT470 System B/G",         "bt470bg"},
2480         {"SMPTE 240M",               "smpte240m"},
2481         {"Linear",                   "linear"},
2482         {"Logarithmic (100:1)",      "log100"},
2483         {"Logarithmic (31622777:1)", "log316"},
2484         {"xvYCC",                    "iec61966-2-4"},
2485         {"BT1361",                   "bt1361e"},
2486         {"sRGB/sYCC",                "iec61966-2-1"},
2487         {"SMPTE 428M",               "smpte428"},
2488         {"BT601",                    "smpte170m"},
2489         {"",                         ""}
2490     };
2491 
2492     QString transfer = "";
2493     QString transfer_vf = "";
2494     QString selected_transfer = arr_trc[_TRC];
2495     if (!curr_transfer.contains(_hdr[CUR_TRANSFER])) {
2496         restore_initial_state();
2497         _message = tr("Can\'t find transfer characteristics %1 in source map.").arg(_hdr[CUR_TRANSFER]);
2498         call_task_complete(_message, false);
2499         return;
2500     }
2501     if (selected_transfer == "Source") {
2502         if (_hdr[CUR_TRANSFER] != "") {
2503             transfer = QString("-color_trc %1 ").arg(curr_transfer[_hdr[CUR_TRANSFER]]);
2504         }
2505     }
2506     else {
2507         transfer = QString("-color_trc %1 ").arg(selected_transfer);
2508         if (_REP_TRC == 2) {
2509             transfer_vf = QString("zscale=t=%1").arg(selected_transfer);
2510         } else {
2511 
2512         }
2513     }
2514 
2515     const int vf_size = 6;
2516     QString vf_transform_arr[vf_size] = {
2517         hwaccel_filter_vf,
2518         fps_vf,
2519         resize_vf,
2520         colorprim_vf,
2521         colormatrix_vf,
2522         transfer_vf,
2523     };
2524 
2525     QString vf = "";
2526     int pos = 0;
2527     for (int n = 0; n < vf_size; n ++) {
2528         if (vf_transform_arr[n] != "") {
2529             pos++;
2530             if (pos == 1) {
2531                 vf += vf_transform_arr[n];
2532             } else {
2533                 vf += "," + vf_transform_arr[n];
2534             }
2535         }
2536     }
2537 
2538     QString transform = "";
2539     if (vf != "") {
2540         transform = QString("-vf %1 ").arg(vf);
2541     }
2542 
2543     QString codec = QString("-map 0:v:0? ") + _audioMapParam + _subtitleMapParam +
2544                     QString("-map_metadata -1 ") + _videoMetadataParam + _audioMetadataParam +
2545                     _subtitleMetadataParam + transform + arr_codec[_CODEC][0];
2546 
2547     /************************************* HDR module ***************************************/
2548 
2549     QString color_range = "";
2550     QString max_lum = "";
2551     QString min_lum = "";
2552     QString max_cll = "";
2553     QString max_fall = "";
2554     QString chroma_coord = "";
2555     QString white_coord = "";
2556     if (_flag_hdr == true) {
2557 
2558         /********************************* Color range module **********************************/
2559 
2560         if (_COLOR_RANGE == 0) {                             // color range
2561             if (_hdr[CUR_COLOR_RANGE] == "Limited") {
2562                 color_range = "-color_range tv ";
2563             }
2564             else if (_hdr[CUR_COLOR_RANGE] == "Full") {
2565                 color_range = "-color_range pc ";
2566             }
2567         }
2568         else if (_COLOR_RANGE == 1) {
2569             color_range = "-color_range pc ";
2570         }
2571         else if (_COLOR_RANGE == 2) {
2572             color_range = "-color_range tv ";
2573         }
2574 
2575         /************************************* Lum module ***************************************/
2576 
2577         if (_MAX_LUM != "") {                           // max lum
2578             max_lum = QString("-s max-luminance=%1 ").arg(_MAX_LUM);
2579         } else {
2580             if (_hdr[CUR_MAX_LUM] != "") {
2581                 max_lum = QString("-s max-luminance=%1 ").arg(_hdr[CUR_MAX_LUM]);
2582             } else {
2583                 max_lum = "-d max-luminance ";
2584             }
2585         }
2586 
2587         if (_MIN_LUM != "") {                           // min lum
2588             min_lum = QString("-s min-luminance=%1 ").arg(_MIN_LUM);
2589         } else {
2590             if (_hdr[CUR_MIN_LUM] != "") {
2591                 min_lum = QString("-s min-luminance=%1 ").arg(_hdr[CUR_MIN_LUM]);
2592             } else {
2593                 min_lum = "-d min-luminance ";
2594             }
2595         }
2596 
2597         if (_MAX_CLL != "") {                           // max cll
2598             max_cll = QString("-s max-content-light=%1 ").arg(_MAX_CLL);
2599         } else {
2600             if (_hdr[CUR_MAX_CLL] != "") {
2601                 max_cll = QString("-s max-content-light=%1 ").arg(_hdr[CUR_MAX_CLL]);
2602             } else {
2603                 max_cll = "-d max-content-light ";
2604             }
2605         }
2606 
2607         if (_MAX_FALL != "") {                           // max fall
2608             max_fall = QString("-s max-frame-light=%1 ").arg(_MAX_FALL);
2609         } else {
2610             if (_hdr[CUR_MAX_FALL] != "") {
2611                 max_fall = QString("-s max-frame-light=%1 ").arg(_hdr[CUR_MAX_FALL]);
2612             } else {
2613                 max_fall = "-d max-frame-light ";
2614             }
2615         }
2616 
2617         /************************************* Display module ***************************************/
2618 
2619         QString chroma_coord_curr_red_x = "";
2620         QString chroma_coord_curr_red_y = "";
2621         QString chroma_coord_curr_green_x = "";
2622         QString chroma_coord_curr_green_y = "";
2623         QString chroma_coord_curr_blue_x = "";
2624         QString chroma_coord_curr_blue_y = "";
2625         QString white_coord_curr_x = "";
2626         QString white_coord_curr_y = "";
2627         if (_MASTER_DISPLAY == 0) {     // From source
2628             if (_hdr[CUR_MASTER_DISPLAY] == "Display P3") {
2629                 chroma_coord_curr_red_x = "0.680";
2630                 chroma_coord_curr_red_y = "0.320";
2631                 chroma_coord_curr_green_x = "0.265";
2632                 chroma_coord_curr_green_y = "0.690";
2633                 chroma_coord_curr_blue_x = "0.150";
2634                 chroma_coord_curr_blue_y = "0.060";
2635                 white_coord_curr_x = "0.3127";
2636                 white_coord_curr_y = "0.3290";
2637             }
2638             if (_hdr[CUR_MASTER_DISPLAY] == "DCI P3") {
2639                 chroma_coord_curr_red_x = "0.680";
2640                 chroma_coord_curr_red_y = "0.320";
2641                 chroma_coord_curr_green_x = "0.265";
2642                 chroma_coord_curr_green_y = "0.690";
2643                 chroma_coord_curr_blue_x = "0.150";
2644                 chroma_coord_curr_blue_y = "0.060";
2645                 white_coord_curr_x = "0.314";
2646                 white_coord_curr_y = "0.3510";
2647             }
2648             if (_hdr[CUR_MASTER_DISPLAY] == "BT.2020") {
2649                 chroma_coord_curr_red_x = "0.708";
2650                 chroma_coord_curr_red_y = "0.292";
2651                 chroma_coord_curr_green_x = "0.170";
2652                 chroma_coord_curr_green_y = "0.797";
2653                 chroma_coord_curr_blue_x = "0.131";
2654                 chroma_coord_curr_blue_y = "0.046";
2655                 white_coord_curr_x = "0.3127";
2656                 white_coord_curr_y = "0.3290";
2657             }
2658             if (_hdr[CUR_MASTER_DISPLAY] == "BT.709") {
2659                 chroma_coord_curr_red_x = "0.640";
2660                 chroma_coord_curr_red_y = "0.330";
2661                 chroma_coord_curr_green_x = "0.30";
2662                 chroma_coord_curr_green_y = "0.60";
2663                 chroma_coord_curr_blue_x = "0.150";
2664                 chroma_coord_curr_blue_y = "0.060";
2665                 white_coord_curr_x = "0.3127";
2666                 white_coord_curr_y = "0.3290";
2667             }
2668             if (_hdr[CUR_MASTER_DISPLAY] == "Undefined") {
2669                 QStringList chr = _hdr[CUR_CHROMA_COORD].split(",");
2670                 if (chr.size() == 6) {
2671                     chroma_coord_curr_red_x = chr[0];
2672                     chroma_coord_curr_red_y = chr[1];
2673                     chroma_coord_curr_green_x = chr[2];
2674                     chroma_coord_curr_green_y = chr[3];
2675                     chroma_coord_curr_blue_x = chr[4];
2676                     chroma_coord_curr_blue_y = chr[5];
2677                 } else {
2678                     restore_initial_state();
2679                     _message = tr("Incorrect master display chroma coordinates source parameters!");
2680                     call_task_complete(_message, false);
2681                     return;
2682                 }
2683                 QStringList wht = _hdr[CUR_WHITE_COORD].split(",");
2684                 if (wht.size() == 2) {
2685                     white_coord_curr_x = wht[0];
2686                     white_coord_curr_y = wht[1];
2687                 } else {
2688                     restore_initial_state();
2689                     _message = tr("Incorrect master display white point coordinates source parameters!");
2690                     call_task_complete(_message, false);
2691                     return;
2692                 }
2693             }
2694         }
2695         if (_MASTER_DISPLAY == 1) {     // Display P3
2696             chroma_coord_curr_red_x = "0.680";
2697             chroma_coord_curr_red_y = "0.320";
2698             chroma_coord_curr_green_x = "0.265";
2699             chroma_coord_curr_green_y = "0.690";
2700             chroma_coord_curr_blue_x = "0.150";
2701             chroma_coord_curr_blue_y = "0.060";
2702             white_coord_curr_x = "0.3127";
2703             white_coord_curr_y = "0.3290";
2704         }
2705         if (_MASTER_DISPLAY == 2) {     // DCI P3
2706             chroma_coord_curr_red_x = "0.680";
2707             chroma_coord_curr_red_y = "0.320";
2708             chroma_coord_curr_green_x = "0.265";
2709             chroma_coord_curr_green_y = "0.690";
2710             chroma_coord_curr_blue_x = "0.150";
2711             chroma_coord_curr_blue_y = "0.060";
2712             white_coord_curr_x = "0.314";
2713             white_coord_curr_y = "0.3510";
2714         }
2715         if (_MASTER_DISPLAY == 3) {     // BT.2020
2716             chroma_coord_curr_red_x = "0.708";
2717             chroma_coord_curr_red_y = "0.292";
2718             chroma_coord_curr_green_x = "0.170";
2719             chroma_coord_curr_green_y = "0.797";
2720             chroma_coord_curr_blue_x = "0.131";
2721             chroma_coord_curr_blue_y = "0.046";
2722             white_coord_curr_x = "0.3127";
2723             white_coord_curr_y = "0.3290";
2724         }
2725         if (_MASTER_DISPLAY == 4) {     // BT.709
2726             chroma_coord_curr_red_x = "0.640";
2727             chroma_coord_curr_red_y = "0.330";
2728             chroma_coord_curr_green_x = "0.30";
2729             chroma_coord_curr_green_y = "0.60";
2730             chroma_coord_curr_blue_x = "0.150";
2731             chroma_coord_curr_blue_y = "0.060";
2732             white_coord_curr_x = "0.3127";
2733             white_coord_curr_y = "0.3290";
2734         }
2735         if (_MASTER_DISPLAY == 5) {     // Custom
2736             QStringList chr = _CHROMA_COORD.split(",");
2737             if (chr.size() == 6) {
2738                 chroma_coord_curr_red_x = chr[0];
2739                 chroma_coord_curr_red_y = chr[1];
2740                 chroma_coord_curr_green_x = chr[2];
2741                 chroma_coord_curr_green_y = chr[3];
2742                 chroma_coord_curr_blue_x = chr[4];
2743                 chroma_coord_curr_blue_y = chr[5];
2744             }
2745             QStringList wht = _WHITE_COORD.split(",");
2746             if (wht.size() == 2) {
2747                 white_coord_curr_x = wht[0];
2748                 white_coord_curr_y = wht[1];
2749             }
2750         }
2751 
2752         if (chroma_coord_curr_red_x == "") {
2753             chroma_coord = "-d chromaticity-coordinates-red-x -d chromaticity-coordinates-red-y "
2754                            "-d chromaticity-coordinates-green-x -d chromaticity-coordinates-green-y "
2755                            "-d chromaticity-coordinates-blue-x -d chromaticity-coordinates-blue-y ";
2756         } else {
2757             chroma_coord = QString("-s chromaticity-coordinates-red-x=%1 -s chromaticity-coordinates-red-y=%2 "
2758                                    "-s chromaticity-coordinates-green-x=%3 -s chromaticity-coordinates-green-y=%4 "
2759                                    "-s chromaticity-coordinates-blue-x=%5 -s chromaticity-coordinates-blue-y=%6 ")
2760                                    .arg(chroma_coord_curr_red_x, chroma_coord_curr_red_y, chroma_coord_curr_green_x,
2761                                         chroma_coord_curr_green_y, chroma_coord_curr_blue_x, chroma_coord_curr_blue_y);
2762         }
2763         if (white_coord_curr_x == "") {
2764             white_coord = "-d white-coordinates-x -d white-coordinates-y ";
2765         } else {
2766             white_coord = QString("-s white-coordinates-x=%1 -s white-coordinates-y=%2 ").arg(white_coord_curr_x, white_coord_curr_y);
2767         }
2768     }
2769 
2770     /************************************* Result module ***************************************/
2771 
2772     _preset_0 = "-hide_banner" + hwaccel + _splitStartParam;
2773     _preset_pass1 = _splitParam + codec + level + preset + mode + pass1 + color_range
2774             + colorprim + colormatrix + transfer + "-an -sn -f null /dev/null";
2775     _preset = _splitParam + codec + level + preset + mode + pass + color_range
2776             + colorprim + colormatrix + transfer + audio_param + sub_param;
2777     _preset_mkvmerge = QString("%1%2%3%4%5%6 ").arg(max_cll, max_fall, max_lum, min_lum, chroma_coord, white_coord);
2778     std::cout << "Flag two-pass: " << _flag_two_pass << std::endl;
2779     std::cout << "Flag HDR: " << _flag_hdr << std::endl;
2780     std::cout << "preset_0: " << _preset_0.toStdString() << std::endl;
2781     if ((_flag_two_pass == true) && (_flag_hdr == true)) {
2782         std::cout << "preset_pass1: " << _preset_pass1.toStdString() << std::endl;
2783         std::cout << "preset: " << _preset.toStdString() << std::endl;
2784         std::cout << "preset_mkvpropedit: " << _preset_mkvmerge.toStdString() << std::endl;
2785         ui->textBrowser_log->append(QString("Preset pass 1: ") + _preset_0 + QString(" -i <input file> ") +
2786                                     _preset_pass1 + QString("\n"));
2787         ui->textBrowser_log->append(QString("Preset pass 2: ") + _preset_0 + QString(" -i <input file> ") +
2788                                     _preset  + QString(" -y <output file>\n"));
2789         ui->textBrowser_log->append(QString("Preset mkvpropedit: ") + _preset_mkvmerge  + QString("\n"));
2790     }
2791     else if ((_flag_two_pass == true) && (_flag_hdr == false)) {
2792         std::cout << "preset_pass1: " << _preset_pass1.toStdString() << std::endl;
2793         std::cout << "preset: " << _preset.toStdString() << std::endl;
2794         ui->textBrowser_log->append(QString("Preset pass 1: ") + _preset_0 + QString(" -i <input file> ") +
2795                                     _preset_pass1 + QString("\n"));
2796         ui->textBrowser_log->append(QString("Preset pass 2: ") + _preset_0 + QString(" -i <input file> ") +
2797                                     _preset  + QString(" -y <output file>\n"));
2798     }
2799     else if ((_flag_two_pass == false) && (_flag_hdr == true)) {
2800         std::cout << "preset: " << _preset.toStdString() << std::endl;
2801         std::cout << "preset_mkvpropedit: " << _preset_mkvmerge.toStdString() << std::endl;
2802         ui->textBrowser_log->append(QString("Preset: ") + _preset_0 + QString(" -i <input file> ") +
2803                                     _preset  + QString(" -y <output file>\n"));
2804         ui->textBrowser_log->append(QString("Preset mkvpropedit: ") + _preset_mkvmerge  + QString("\n"));
2805     }
2806     else if ((_flag_two_pass == false) && (_flag_hdr == false)) {
2807         std::cout << "preset: " << _preset.toStdString() << std::endl;
2808         ui->textBrowser_log->append(QString("Preset: ") + _preset_0 + QString(" -i <input file> ") +
2809                                     _preset  + QString(" -y <output file>\n"));
2810     }
2811     encode();
2812 }
2813 
encode()2814 void Widget::encode()   /*** Encode ***/
2815 {
2816     std::cout << "Encode ..." << std::endl;  //  Debug info //
2817     QStringList arguments;
2818     _calling_pr_1 = true;
2819     processEncoding->disconnect();
2820     connect(processEncoding, SIGNAL(readyReadStandardOutput()), this, SLOT(progress_1()));
2821     connect(processEncoding, SIGNAL(finished(int)), this, SLOT(error()));
2822     ui->progressBar->setValue(0);
2823     if (_mux_mode == true) {
2824         std::cout << "Muxing mode ..." << std::endl;  //  Debug info //
2825         ui->label_Progress->setText(tr("Muxing:"));
2826         arguments << "-hide_banner" << "-i" << _temp_file << "-map" << "0:v:0?" << "-map" << "0:a?"
2827                   << "-map" << "0:s?" << "-movflags" << "+write_colr"
2828                   << "-c:v" << "copy" << "-c:a" << "copy" << _sub_mux_param.split(" ") << "-y" << _output_file;
2829     } else {
2830         if (_fr_count == 0) {
2831             _status_encode_btn = "start";
2832             ui->actionEncode->setIcon(QIcon(":/resources/icons/16x16/cil-play.png"));
2833             ui->actionEncode->setToolTip(tr("Encode"));
2834             _message = tr("The file does not contain FPS information!\nSelect the correct input file!");
2835             call_task_complete(_message, false);
2836             return;
2837         }
2838         setStatus(tr("Encoding"));
2839         ui->treeWidget->setEnabled(false);
2840         add_files->setEnabled(false);
2841         remove_files->setEnabled(false);
2842         settings->setEnabled(false);
2843         ui->lineEditCurTime->setEnabled(false);
2844         ui->lineEditStartTime->setEnabled(false);
2845         ui->lineEditEndTime->setEnabled(false);
2846         ui->buttonFramePrevious->setEnabled(false);
2847         ui->buttonFrameNext->setEnabled(false);
2848         ui->horizontalSlider->setEnabled(false);
2849         ui->buttonSetStartTime->setEnabled(false);
2850         ui->buttonSetEndTime->setEnabled(false);
2851         ui->tableWidget->setEnabled(false);
2852         ui->buttonSortUp->setEnabled(false);
2853         ui->buttonSortDown->setEnabled(false);
2854         ui->actionAdd->setEnabled(false);
2855         ui->actionRemove->setEnabled(false);
2856 
2857         ui->actionAdd_preset->setEnabled(false);
2858         ui->actionRemove_preset->setEnabled(false);
2859         ui->actionEdit_preset->setEnabled(false);
2860         ui->buttonApplyPreset->setEnabled(false);
2861         ui->comboBoxMode->setEnabled(false);
2862         ui->buttonHotInputFile->setEnabled(false);
2863         ui->buttonHotOutputFile->setEnabled(false);
2864         ui->horizontalSlider_resize->setEnabled(false);
2865 
2866         ui->actionClearMetadata->setEnabled(false);
2867         ui->actionUndoMetadata->setEnabled(false);
2868         QList<QLineEdit*> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit*>();
2869         foreach (QLineEdit *lineEdit, linesEditMetadata) {
2870             lineEdit->setEnabled(false);
2871         }
2872 
2873         ui->actionUndoTitles->setEnabled(false);
2874         ui->actionClearAudioTitles->setEnabled(false);
2875         for (int stream = 0; stream < AMOUNT_AUDIO_STREAMS; stream++) {
2876             QCheckBox *checkBoxAudio = ui->frameTab_2->findChild<QCheckBox *>("checkBoxAudio_"
2877                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2878             checkBoxAudio->setEnabled(false);
2879             QLineEdit *lineEditLangAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditLangAudio_"
2880                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2881             lineEditLangAudio->setEnabled(false);
2882             QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
2883                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2884             lineEditTitleAudio->setEnabled(false);
2885         }
2886 
2887         ui->actionClearSubtitleTitles->setEnabled(false);
2888         for (int stream = 0; stream < AMOUNT_SUBTITLES; stream++) {
2889             QCheckBox *checkBoxSubtitle = ui->frameTab_3->findChild<QCheckBox *>("checkBoxSubtitle_"
2890                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2891             checkBoxSubtitle->setEnabled(false);
2892             QLineEdit *lineEditLangSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditLangSubtitle_"
2893                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2894             lineEditLangSubtitle->setEnabled(false);
2895             QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
2896                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
2897             lineEditTitleSubtitle->setEnabled(false);
2898         }
2899 
2900         ui->actionResetLabels->setEnabled(false);
2901         ui->actionSettings->setEnabled(false);
2902         ui->labelAnimation->show();
2903         animation->start();
2904         ui->label_Progress->show();
2905         ui->label_Remaining->show();
2906         ui->label_RemTime->show();
2907         ui->progressBar->show();
2908 
2909 
2910         _loop_start = time(nullptr);
2911         if (_flag_two_pass == false && _flag_hdr == false) {
2912             std::cout << "Encode non HDR..." << std::endl;  //  Debug info //
2913             ui->label_Progress->setText(tr("Encoding:"));
2914             arguments << _preset_0.split(" ") << "-i" << _input_file << _preset.split(" ") << "-y" << _output_file;
2915         }
2916         else if (_flag_two_pass == false && _flag_hdr == true) {
2917             std::cout << "Encode HDR..." << std::endl;  //  Debug info //
2918             ui->label_Progress->setText(tr("Encoding:"));
2919             arguments << _preset_0.split(" ") << "-i" << _input_file << _preset.split(" ") << "-y" << _temp_file;
2920         }
2921         else if (_flag_two_pass == true) {
2922             std::cout << "Encode 1-st pass..." << std::endl;  //  Debug info //
2923             ui->label_Progress->setText(tr("1-st pass:"));
2924             arguments << _preset_0.split(" ") << "-y" << "-i" << _input_file << _preset_pass1.split(" ");
2925         }
2926     }
2927     //qDebug() << arguments;
2928     processEncoding->start("ffmpeg", arguments);
2929     if (!processEncoding->waitForStarted()) {
2930         std::cout << "cmd command not found!!!" << std::endl;
2931         processEncoding->disconnect();
2932         restore_initial_state();
2933         _message = tr("An unknown error occurred!\n Possible FFMPEG not installed.\n");
2934         call_task_complete(_message, false);
2935     }
2936 }
2937 
add_metadata()2938 void Widget::add_metadata() /*** Add metedata ***/
2939 {
2940     std::cout << "Add metadata ..." << std::endl;  //  Debug info //
2941     _calling_pr_1 = true;
2942     processEncoding->disconnect();
2943     connect(processEncoding, SIGNAL(readyReadStandardOutput()), this, SLOT(progress_2()));
2944     connect(processEncoding, SIGNAL(finished(int)), this, SLOT(error()));
2945     ui->label_Progress->setText(tr("Add data:"));
2946     ui->progressBar->setValue(0);
2947     QStringList arguments;
2948     arguments << "--edit" << "track:1" << _preset_mkvmerge.split(" ") << _temp_file;
2949     processEncoding->start("mkvpropedit", arguments);
2950     if (!processEncoding->waitForStarted()) {
2951         std::cout << "cmd command not found!!!" << std::endl;
2952         processEncoding->disconnect();
2953         restore_initial_state();
2954         _message = tr("An unknown error occured!\n Possible mkvtoolnix not installed.\n");
2955         call_task_complete(_message, false);
2956     }
2957 }
2958 
complete()2959 void Widget::complete() /*** Complete ***/
2960 {
2961     std::cout << "Complete ..." << std::endl;  //  Debug info //
2962     processEncoding->disconnect();
2963     setStatus(tr("Done!"));
2964     animation->stop();
2965     ui->label_Progress->hide();
2966     ui->label_Remaining->hide();
2967     ui->label_RemTime->hide();
2968     ui->labelAnimation->hide();
2969     ui->progressBar->hide();
2970     if (_flag_hdr == true) {
2971         QDir().remove(_temp_file);
2972     }
2973     if (_batch_mode == true) {
2974         int row = ui->tableWidget->currentRow();
2975         int numRows = ui->tableWidget->rowCount();
2976         if (numRows > (row + 1)) {
2977             ui->tableWidget->selectRow(row + 1);
2978             make_preset();
2979         } else {
2980             restore_initial_state();
2981             time_t end_t = time(nullptr);
2982             float elps_t = static_cast<float>(end_t - _strt_t);
2983             if (elps_t < 0.0f) {
2984                 elps_t = 0.0f;
2985             }
2986             if (_protection == true) {
2987                 timer->stop();
2988             }
2989             _message = tr("Task completed!\n\n Elapsed time: ") + timeConverter(elps_t);
2990             call_task_complete(_message, false);
2991         }
2992     } else {
2993         restore_initial_state();
2994         time_t end_t = time(nullptr);
2995         float elps_t = static_cast<float>(end_t - _strt_t);
2996         if (elps_t < 0.0f) {
2997             elps_t = 0.0f;
2998         }
2999         if (_protection == true) {
3000             timer->stop();
3001         }
3002         _message = tr("Task completed!\n\n Elapsed time: ") + timeConverter(elps_t);
3003         call_task_complete(_message, false);
3004     }
3005     QDir().remove(QDir::homePath() + QString("/ffmpeg2pass-0.log"));
3006     QDir().remove(QDir::homePath() + QString("/ffmpeg2pass-0.log.mbtree"));
3007     QDir().remove(QDir::homePath() + QString("/x265_2pass.log"));
3008     QDir().remove(QDir::homePath() + QString("/x265_2pass.log.cutree"));
3009 }
3010 
progress_1()3011 void Widget::progress_1()   /*** Progress 1 ***/
3012 {
3013     QString line = processEncoding->readAllStandardOutput();
3014     QString line_mod6 = line.replace("   ", " ").replace("  ", " ").replace("  ", " ").replace("= ", "=");
3015     //std::cout << line_mod6.toStdString() << std::endl;
3016     ui->textBrowser_log->append(line_mod6);
3017     int pos_err_1 = line_mod6.indexOf("[error]:");
3018     int pos_err_2 = line_mod6.indexOf("Error");
3019     int pos_err_3 = line_mod6.indexOf(" @ ");
3020     if (pos_err_1 != -1) {
3021         QStringList error = line_mod6.split(":");
3022         if (error.size() >= 2) {
3023             _error_message = error[1];
3024         }
3025     }
3026     if (pos_err_2 != -1) {
3027         _error_message = line_mod6;
3028     }
3029     if (pos_err_3 != -1) {
3030         QStringList error = line_mod6.split("]");
3031         if (error.size() >= 2) {
3032             _error_message = error[1];
3033         }
3034     }
3035     int pos_st = line_mod6.indexOf("frame=");
3036     if (pos_st == 0) {
3037         QStringList data = line_mod6.split(" ");
3038         QString frame_qstr = data[0].replace("frame=", "");
3039         int frame = frame_qstr.toInt();
3040         if (frame == 0) {
3041             frame = 1;
3042         }
3043         time_t iter_start = time(nullptr);
3044         int timer = static_cast<int>(iter_start - _loop_start);
3045         float full_time = static_cast<float>(timer * _fr_count) / (frame);
3046         float rem_time = full_time - static_cast<float>(timer);
3047         if (rem_time < 0.0f) {
3048             rem_time = 0.0f;
3049         }
3050         if (rem_time > MAXIMUM_ALLOWED_TIME) {
3051             rem_time = MAXIMUM_ALLOWED_TIME;
3052         }
3053         ui->label_RemTime->setText(timeConverter(rem_time));
3054 
3055         float percent = static_cast<float>(frame * 100) / _fr_count;
3056         int percent_int = static_cast<int>(round(percent));
3057         if (percent_int > 100) {
3058             percent_int = 100;
3059         }
3060         ui->progressBar->setValue(percent_int);
3061 
3062         if ((percent_int >= 95) && (_calling_pr_1 == true)) {
3063              disconnect(processEncoding, SIGNAL(finished(int)), this, SLOT(error()));
3064              if (_mux_mode == true) {
3065                  connect(processEncoding, SIGNAL(finished(int)), this, SLOT(complete()));
3066              } else {
3067                  if (_flag_two_pass == false && _flag_hdr == true) {
3068                      disconnect(processEncoding, SIGNAL(finished(int)), this, SLOT(encode()));
3069                      connect(processEncoding, SIGNAL(finished(int)), this, SLOT(add_metadata()));
3070                  }
3071                  if (_flag_two_pass == false && _flag_hdr == false) {
3072                      disconnect(processEncoding, SIGNAL(finished(int)), this, SLOT(encode()));
3073                      connect(processEncoding, SIGNAL(finished(int)), this, SLOT(complete()));
3074                  }
3075                  if (_flag_two_pass == true) {
3076                      connect(processEncoding, SIGNAL(finished(int)), this, SLOT(encode()));
3077                      _flag_two_pass = false;
3078                  }
3079              }
3080              _calling_pr_1 = false;
3081         }
3082     }
3083 }
3084 
progress_2()3085 void Widget::progress_2()   /*** Progress 2 ***/
3086 {
3087     QString line = processEncoding->readAllStandardOutput();
3088     ui->textBrowser_log->append(line);
3089     int pos_st = line.indexOf("Done.");
3090     int pos_nf = line.indexOf("Nothing to do.");
3091     if ((pos_st != -1) or (pos_nf != -1)) {
3092         int percent = 100;
3093         ui->progressBar->setValue(percent);
3094         if ((percent == 100) && (_calling_pr_1 == true)) {
3095             disconnect(processEncoding, SIGNAL(finished(int)), this, SLOT(error()));
3096             _mux_mode = true;
3097             _loop_start = time(nullptr);
3098             _calling_pr_1 = false;
3099             connect(processEncoding, SIGNAL(finished(int)), this, SLOT(encode()));
3100         }
3101     }
3102 }
3103 
pause()3104 void Widget::pause()    /*** Pause ***/
3105 {
3106     if (_protection) timer->stop();
3107     if (processEncoding->state() != QProcess::NotRunning) {
3108         setStatus(tr("Pause"));
3109         animation->stop();
3110 #ifdef Q_OS_WIN
3111         _PROCESS_INFORMATION *pi = processEncoding->pid();
3112         SuspendThread(pi->hThread);  // pause for Windows
3113 #else
3114         kill(pid_t(processEncoding->processId()), SIGSTOP);  // pause for Unix
3115 #endif
3116     }
3117 }
3118 
resume()3119 void Widget::resume()   /*** Resume ***/
3120 {
3121     if (_protection) timer->start();
3122     if (processEncoding->state() != QProcess::NotRunning) {
3123         setStatus(tr("Encoding"));
3124         animation->start();
3125 #ifdef Q_OS_WIN
3126         _PROCESS_INFORMATION *pi = processEncoding->pid();
3127         ResumeThread(pi->hThread);  // resume for Windows
3128 #else
3129         kill(pid_t(processEncoding->processId()), SIGCONT); // resume for Unix
3130 #endif
3131     }
3132 }
3133 
cancel()3134 void Widget::cancel()   /*** Stop execute ***/
3135 {
3136     std::cout << "Stop execute ..." << std::endl;  //  Debug info //
3137     if (_protection) timer->stop();
3138     processEncoding->disconnect();
3139     setStatus(tr("Stop"));
3140     ui->label_Progress->hide();
3141     ui->label_Remaining->hide();
3142     ui->label_RemTime->hide();
3143     ui->labelAnimation->hide();
3144     ui->progressBar->hide();
3145     restore_initial_state();
3146     _message = tr("The current encoding process has been canceled!\n");
3147     call_task_complete(_message, false);
3148 }
3149 
error()3150 void Widget::error()  /*** Error ***/
3151 {
3152     std::cout << "Error_1 ..." << std::endl;  //  Debug info //
3153     if (_protection) timer->stop();
3154     processEncoding->disconnect();
3155     setStatus(tr("Error!"));
3156     restore_initial_state();
3157     if (_error_message != "") {
3158         _message = tr("An error occurred: ") + _error_message;
3159     } else {
3160         _message = tr("Unexpected error occurred!");
3161     }
3162     call_task_complete(_message, false);
3163 }
3164 
repeatHandler_Type_1()3165 void Widget::repeatHandler_Type_1()  /*** Repeat handler ***/
3166 {
3167     std::cout<< "Call by timer..." << std::endl;
3168     on_actionEncode_clicked();
3169     call_task_complete(tr("Pause"), true);
3170     on_actionEncode_clicked();
3171 }
3172 
3173 /************************************************
3174 ** Task Window
3175 ************************************************/
3176 
on_actionAdd_clicked()3177 void Widget::on_actionAdd_clicked() /*** Add files ***/
3178 {
3179     QFileDialog openFilesWindow(nullptr);
3180     openFilesWindow.setWindowTitle("Open Files");
3181     openFilesWindow.setMinimumWidth(600);
3182     openFilesWindow.setWindowFlags(Qt::Dialog | Qt::SubWindow);
3183     openFilesWindow.setOption(QFileDialog::DontResolveSymlinks, true);
3184     if (_desktopEnv == "gnome") openFilesWindow.setOption(QFileDialog::DontUseNativeDialog, true);
3185     openFilesWindow.setFileMode(QFileDialog::ExistingFiles);
3186     openFilesWindow.setAcceptMode(QFileDialog::AcceptOpen);
3187     openFilesWindow.setDirectory(_openDir);
3188     openFilesWindow.setNameFilter(tr("Video Files: *.avi, *.m2ts, *.m4v, *.mkv, *.mov, *.mp4, "
3189                                      "*.mpeg, *.mpg, *.mxf, *.ts, *.webm (*.avi *.m2ts *.m4v "
3190                                      "*.mkv *.mov *.mp4 *.mpeg *.mpg *.mxf *.ts *.webm);;All files (*.*)"));
3191     if (openFilesWindow.exec() == QFileDialog::Accepted) {
3192         const QStringList openFileNames = openFilesWindow.selectedFiles();
3193         openFiles(openFileNames);
3194     }
3195 }
3196 
on_actionRemove_clicked()3197 void Widget::on_actionRemove_clicked()  /*** Remove file from table ***/
3198 {
3199     _row = ui->tableWidget->currentRow();
3200     if (_row != -1) {
3201         ui->tableWidget->removeRow(_row);
3202     }
3203 }
3204 
on_buttonCloseTaskWindow_clicked()3205 void Widget::on_buttonCloseTaskWindow_clicked()
3206 {
3207     on_closeWindow_clicked();
3208 }
3209 
on_buttonSortDown_clicked()3210 void Widget::on_buttonSortDown_clicked()    /*** Sort table ***/
3211 {
3212     ui->tableWidget->sortByColumn(columnIndex::FILENAME, Qt::DescendingOrder);
3213 }
3214 
on_buttonSortUp_clicked()3215 void Widget::on_buttonSortUp_clicked()    /*** Sort table ***/
3216 {
3217     ui->tableWidget->sortByColumn(columnIndex::FILENAME, Qt::AscendingOrder);
3218 }
3219 
on_actionEncode_clicked()3220 void Widget::on_actionEncode_clicked()  /*** Encode button ***/
3221 {
3222     if (_status_encode_btn == "start") {
3223         std::cout << "Status encode btn: start" << std::endl;  // Debug info //
3224         int cnt = ui->tableWidget->rowCount();
3225         if (cnt == 0) {
3226             _message = tr("Select input file first!");
3227             call_task_complete(_message, false);
3228             return;
3229         }
3230         if (_pos_cld == -1) {
3231             _message = tr("Select preset first!");
3232             call_task_complete(_message, false);
3233             return;
3234         }
3235         _status_encode_btn = "pause";
3236         ui->actionEncode->setIcon(QIcon(":/resources/icons/16x16/cil-pause.png"));
3237         ui->actionEncode->setToolTip(tr("Pause"));
3238         _strt_t = time(nullptr);
3239         if (_protection == true) {
3240             timer->start();
3241         }
3242         make_preset();
3243         return;
3244     }
3245     if (_status_encode_btn == "pause") {
3246         std::cout << "Status encode btn: pause" << std::endl;  // Debug info //
3247         pause();
3248         _status_encode_btn = "resume";
3249         ui->actionEncode->setIcon(QIcon(":/resources/icons/16x16/cil-forward.png"));
3250         ui->actionEncode->setToolTip(tr("Resume"));
3251         return;
3252     }
3253     if (_status_encode_btn == "resume") {
3254         std::cout << "Status encode btn: resume" << std::endl;  // Debug info //
3255         resume();
3256         _status_encode_btn = "pause";
3257         ui->actionEncode->setIcon(QIcon(":/resources/icons/16x16/cil-pause.png"));
3258         ui->actionEncode->setToolTip(tr("Pause"));
3259         return;
3260     }
3261 }
3262 
on_actionStop_clicked()3263 void Widget::on_actionStop_clicked()    /*** Stop ***/
3264 {
3265     std::cout << "Call Stop ..." << std::endl;  //  Debug info //
3266     if (processEncoding->state() != QProcess::NotRunning) {
3267         _message = tr("Stop encoding?");
3268         bool confirm = call_dialog(_message);
3269         if (confirm) {
3270             processEncoding->disconnect();
3271             connect(processEncoding, SIGNAL(finished(int)), this, SLOT(cancel()));
3272             processEncoding->kill();
3273         }
3274     }
3275 }
3276 
openFiles(const QStringList & openFileNames)3277 void Widget::openFiles(const QStringList &openFileNames)    /*** Open files ***/
3278 {
3279     showOpeningFiles(true);
3280     ui->labelAnimation->hide();
3281     ui->label_Progress->hide();
3282     ui->label_Remaining->hide();
3283     ui->label_RemTime->hide();
3284     ui->progressBar->hide();
3285     MediaInfo MI;
3286     int i = 1;
3287     int countFileNames = openFileNames.size();
3288     while (i <= countFileNames)
3289     {
3290         const int numRows = ui->tableWidget->rowCount();
3291         ui->tableWidget->setRowCount(numRows + 1);
3292         const QString file = openFileNames.at(i-1);
3293         const QString inputFolder = QFileInfo(file).absolutePath();
3294         const QString inputFile = QFileInfo(file).fileName();
3295         showOpeningFiles(inputFile);
3296         showOpeningFiles(0);
3297         QApplication::processEvents();
3298         if (i == 1) _openDir = inputFolder;
3299         MI.Open(file.toStdWString());
3300         QString duration_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"Duration"));
3301         double duration_double = 0.001 * duration_qstr.toDouble();
3302         float duration_float = static_cast<float>(duration_double);
3303         QString durationTime = timeConverter(duration_float);
3304         QString bitrate_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"BitRate"));
3305         int bitrate_int = static_cast<int>(0.001 * bitrate_qstr.toDouble());
3306         QString stream_size_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"StreamSize"));
3307         QString mastering_display_luminance_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"MasteringDisplay_Luminance"));
3308         QString mastering_display_luminance_rep = mastering_display_luminance_qstr.replace("min: ", "").replace("max: ", "").replace(" cd/m2", "");
3309         QString min_luminance = mastering_display_luminance_rep.split(", ")[0];
3310         QString max_luminance = mastering_display_luminance_rep.replace(min_luminance, "").replace(", ", "");
3311         QString color_primaries = QString::fromStdWString(MI.Get(Stream_Video, 0, L"colour_primaries"));
3312         QString matrix_coefficients = QString::fromStdWString(MI.Get(Stream_Video, 0, L"matrix_coefficients"));
3313         QString transfer_characteristics = QString::fromStdWString(MI.Get(Stream_Video, 0, L"transfer_characteristics"));
3314         QString mastering_display_color_primaries = QString::fromStdWString(MI.Get(Stream_Video, 0, L"MasteringDisplay_ColorPrimaries"));
3315         QString color_range = QString::fromStdWString(MI.Get(Stream_Video, 0, L"colour_range"));
3316         QString maxCll = QString::fromStdWString(MI.Get(Stream_Video, 0, L"MaxCLL"));
3317         QString maxFall = QString::fromStdWString(MI.Get(Stream_Video, 0, L"MaxFALL"));
3318         QString width_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"Width"));
3319         QString height_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"Height"));
3320         QString chroma_subsampling = QString::fromStdWString(MI.Get(Stream_Video, 0, L"ChromaSubsampling"));
3321         QString aspect_ratio = QString::fromStdWString(MI.Get(Stream_Video, 0, L"DisplayAspectRatio"));
3322         QString color_space = QString::fromStdWString(MI.Get(Stream_Video, 0, L"ColorSpace"));
3323         QString bit_depth = QString::fromStdWString(MI.Get(Stream_Video, 0, L"BitDepth"));
3324         QString fmt_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"Format"));
3325         QString fps_qstr = QString::fromStdWString(MI.Get(Stream_Video, 0, L"FrameRate"));
3326         QString size = width_qstr + "x" + height_qstr;
3327         QString videoTitle = QString::fromStdWString(MI.Get(Stream_Video, 0, L"Title"));
3328         QString videoAuthor = QString::fromStdWString(MI.Get(Stream_General, 0, L"AUTHOR"));
3329         QString videoYear = QString::fromStdWString(MI.Get(Stream_General, 0, L"YEAR"));
3330         QString videoPerformer = QString::fromStdWString(MI.Get(Stream_General, 0, L"Performer"));
3331         QString videoDescription = QString::fromStdWString(MI.Get(Stream_General, 0, L"Description"));
3332         QString videoMovieName = QString::fromStdWString(MI.Get(Stream_General, 0, L"Movie"));
3333 
3334         int len = mastering_display_color_primaries.length();
3335         QString white_coord = "";
3336         QString chroma_coord = "";
3337         if (len > 15) {
3338             QStringList mdcp = mastering_display_color_primaries.split(",");
3339             QString r = mdcp[0].replace("R: ", "").replace("x=", "").replace(" ", ",").replace("y=", "").replace("000", "0");
3340             QString g = mdcp[1].replace(" G: ", "").replace("x=", "").replace(" ", ",").replace("y=", "").replace("000", "0");
3341             QString b = mdcp[2].replace(" B: ", "").replace("x=", "").replace(" ", ",").replace("y=", "").replace("000", "0");
3342             white_coord = mdcp[3].replace(" White point: ", "").replace("x=", "").replace(" ", ",").replace("y=", "").replace("000", "0");
3343             chroma_coord = r + "," + g + "," + b;
3344             mastering_display_color_primaries = "Undefined";
3345         }
3346 
3347         if (fmt_qstr == "") {
3348             fmt_qstr = "Undef";
3349         }
3350         if (fps_qstr == "") {
3351             fps_qstr = "Undef";
3352         }
3353         if (width_qstr == "") {
3354             size = "Undef";
3355         }
3356         if (durationTime == "00:00:00") {
3357             durationTime = "Undef";
3358         }
3359 
3360         QTableWidgetItem *newItem_file = new QTableWidgetItem(inputFile);
3361         QTableWidgetItem *newItem_folder = new QTableWidgetItem(inputFolder);
3362         QTableWidgetItem *newItem_fmt = new QTableWidgetItem(fmt_qstr);
3363         QTableWidgetItem *newItem_resolution = new QTableWidgetItem(size);
3364         QTableWidgetItem *newItem_duration_time = new QTableWidgetItem(durationTime);
3365         QTableWidgetItem *newItem_fps = new QTableWidgetItem(fps_qstr);
3366         QTableWidgetItem *newItem_aspect_ratio = new QTableWidgetItem(aspect_ratio);
3367         QTableWidgetItem *newItem_bitrate = new QTableWidgetItem(QString::number(bitrate_int));
3368         QTableWidgetItem *newItem_subsampling = new QTableWidgetItem(chroma_subsampling);
3369         QTableWidgetItem *newItem_bit_depth = new QTableWidgetItem(bit_depth);
3370         QTableWidgetItem *newItem_color_space = new QTableWidgetItem(color_space);
3371         QTableWidgetItem *newItem_color_range = new QTableWidgetItem(color_range);
3372         QTableWidgetItem *newItem_color_primaries = new QTableWidgetItem(color_primaries.replace(".", ""));
3373         QTableWidgetItem *newItem_color_matrix = new QTableWidgetItem(matrix_coefficients.replace(" ", "").replace(".", "").replace("on-", "").replace("onstant", ""));
3374         QTableWidgetItem *newItem_transfer_characteristics = new QTableWidgetItem(transfer_characteristics.replace(".", ""));
3375         QTableWidgetItem *newItem_max_lum = new QTableWidgetItem(max_luminance);
3376         QTableWidgetItem *newItem_min_lum = new QTableWidgetItem(min_luminance);
3377         QTableWidgetItem *newItem_max_cll = new QTableWidgetItem(maxCll.replace(" cd/m2", ""));
3378         QTableWidgetItem *newItem_max_fall = new QTableWidgetItem(maxFall.replace(" cd/m2", ""));
3379         QTableWidgetItem *newItem_mastering_display = new QTableWidgetItem(mastering_display_color_primaries);
3380         QTableWidgetItem *newItem_chroma_coord = new QTableWidgetItem(chroma_coord);
3381         QTableWidgetItem *newItem_white_coord = new QTableWidgetItem(white_coord);
3382         QTableWidgetItem *newItem_duration = new QTableWidgetItem(QString::number(duration_double, 'f', 3));
3383         QTableWidgetItem *newItem_stream_size = new QTableWidgetItem(stream_size_qstr);
3384         QTableWidgetItem *newItem_width = new QTableWidgetItem(width_qstr);
3385         QTableWidgetItem *newItem_height = new QTableWidgetItem(height_qstr);
3386         QTableWidgetItem *newItem_videoTitle = new QTableWidgetItem(videoTitle);
3387         QTableWidgetItem *newItem_videoAuthor = new QTableWidgetItem(videoAuthor);
3388         QTableWidgetItem *newItem_videoYear = new QTableWidgetItem(videoYear);
3389         QTableWidgetItem *newItem_videoPerformer = new QTableWidgetItem(videoPerformer);
3390         QTableWidgetItem *newItem_videoDescription = new QTableWidgetItem(videoDescription);
3391         QTableWidgetItem *newItem_videoMovieName = new QTableWidgetItem(videoMovieName);
3392         QTableWidgetItem *newItem_startTime = new QTableWidgetItem("0");
3393         QTableWidgetItem *newItem_endTime = new QTableWidgetItem("0");
3394 
3395         newItem_fmt->setTextAlignment(Qt::AlignCenter);
3396         newItem_resolution->setTextAlignment(Qt::AlignCenter);
3397         newItem_duration_time->setTextAlignment(Qt::AlignCenter);
3398         newItem_fps->setTextAlignment(Qt::AlignCenter);
3399         newItem_aspect_ratio->setTextAlignment(Qt::AlignCenter);
3400         newItem_bitrate->setTextAlignment(Qt::AlignCenter);
3401         newItem_subsampling->setTextAlignment(Qt::AlignCenter);
3402         newItem_bit_depth->setTextAlignment(Qt::AlignCenter);
3403         newItem_color_space->setTextAlignment(Qt::AlignCenter);
3404         newItem_color_range->setTextAlignment(Qt::AlignCenter);
3405         newItem_color_primaries->setTextAlignment(Qt::AlignCenter);
3406         newItem_color_matrix->setTextAlignment(Qt::AlignCenter);
3407         newItem_transfer_characteristics->setTextAlignment(Qt::AlignCenter);
3408         newItem_max_lum->setTextAlignment(Qt::AlignCenter);
3409         newItem_min_lum->setTextAlignment(Qt::AlignCenter);
3410         newItem_max_cll->setTextAlignment(Qt::AlignCenter);
3411         newItem_max_fall->setTextAlignment(Qt::AlignCenter);
3412         newItem_mastering_display->setTextAlignment(Qt::AlignCenter);
3413 
3414         ui->tableWidget->setItem(numRows, columnIndex::FILENAME, newItem_file);
3415         ui->tableWidget->setItem(numRows, columnIndex::PATH, newItem_folder);
3416         ui->tableWidget->setItem(numRows, columnIndex::FORMAT, newItem_fmt);
3417         ui->tableWidget->setItem(numRows, columnIndex::RESOLUTION, newItem_resolution);
3418         ui->tableWidget->setItem(numRows, columnIndex::DURATION, newItem_duration_time);
3419         ui->tableWidget->setItem(numRows, columnIndex::FPS, newItem_fps);
3420         ui->tableWidget->setItem(numRows, columnIndex::AR, newItem_aspect_ratio);
3421         ui->tableWidget->setItem(numRows, columnIndex::BITRATE, newItem_bitrate);
3422         ui->tableWidget->setItem(numRows, columnIndex::SUBSAMPLING, newItem_subsampling);
3423         ui->tableWidget->setItem(numRows, columnIndex::BITDEPTH, newItem_bit_depth);
3424         ui->tableWidget->setItem(numRows, columnIndex::COLORSPACE, newItem_color_space);
3425         ui->tableWidget->setItem(numRows, columnIndex::COLORRANGE, newItem_color_range);
3426         ui->tableWidget->setItem(numRows, columnIndex::COLORPRIM, newItem_color_primaries);
3427         ui->tableWidget->setItem(numRows, columnIndex::COLORMATRIX, newItem_color_matrix);
3428         ui->tableWidget->setItem(numRows, columnIndex::TRANSFER, newItem_transfer_characteristics);
3429         ui->tableWidget->setItem(numRows, columnIndex::MAXLUM, newItem_max_lum);
3430         ui->tableWidget->setItem(numRows, columnIndex::MINLUM, newItem_min_lum);
3431         ui->tableWidget->setItem(numRows, columnIndex::MAXCLL, newItem_max_cll);
3432         ui->tableWidget->setItem(numRows, columnIndex::MAXFALL, newItem_max_fall);
3433         ui->tableWidget->setItem(numRows, columnIndex::MASTERDISPLAY, newItem_mastering_display);
3434         ui->tableWidget->setItem(numRows, columnIndex::T_CHROMACOORD, newItem_chroma_coord);
3435         ui->tableWidget->setItem(numRows, columnIndex::T_WHITECOORD, newItem_white_coord);
3436         ui->tableWidget->setItem(numRows, columnIndex::T_DUR, newItem_duration);
3437         ui->tableWidget->setItem(numRows, columnIndex::T_STREAMSIZE, newItem_stream_size);
3438         ui->tableWidget->setItem(numRows, columnIndex::T_WIDTH, newItem_width);
3439         ui->tableWidget->setItem(numRows, columnIndex::T_HEIGHT, newItem_height);
3440         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEOTITLE, newItem_videoTitle);
3441         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEOAUTHOR, newItem_videoAuthor);
3442         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEOYEAR, newItem_videoYear);
3443         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEOPERF, newItem_videoPerformer);
3444         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEODESCR, newItem_videoDescription);
3445         ui->tableWidget->setItem(numRows, columnIndex::T_VIDEOMOVIENAME, newItem_videoMovieName);
3446         ui->tableWidget->setItem(numRows, columnIndex::T_STARTTIME, newItem_startTime);
3447         ui->tableWidget->setItem(numRows, columnIndex::T_ENDTIME, newItem_endTime);
3448 
3449         int smplrt_int;
3450         QString audioFormat("");
3451         QString audioLang("");
3452         QString audioTitle("");
3453         QString smplrt("");
3454         QString smplrt_qstr("");
3455         QString audioCheckstate;
3456         for (int j = 0; j < AMOUNT_AUDIO_STREAMS; j++) {
3457             audioFormat = QString::fromStdWString(MI.Get(Stream_Audio, size_t(j), L"Format"));
3458             audioLang = QString::fromStdWString(MI.Get(Stream_Audio, size_t(j), L"Language"));
3459             audioTitle = QString::fromStdWString(MI.Get(Stream_Audio, size_t(j), L"Title"));
3460             smplrt_qstr = QString::fromStdWString(MI.Get(Stream_Audio, size_t(j), L"SamplingRate"));
3461             smplrt_int = static_cast<int>(smplrt_qstr.toFloat() / 1000);
3462             audioCheckstate = "0";
3463 
3464             if (smplrt_int != 0) {
3465                 smplrt = QString::number(smplrt_int);
3466             } else {
3467                 smplrt = "";
3468             }
3469             if (audioFormat != "") {
3470                 audioFormat = audioFormat + "  " + smplrt + " kHz";
3471                 audioCheckstate = "1";
3472             }
3473             QTableWidgetItem *newItem_audio = new QTableWidgetItem(audioFormat);
3474             QTableWidgetItem *newItem_lang = new QTableWidgetItem(audioLang);
3475             QTableWidgetItem *newItem_title = new QTableWidgetItem(audioTitle);
3476             QTableWidgetItem *newItem_checkstate = new QTableWidgetItem(audioCheckstate);
3477             ui->tableWidget->setItem(numRows, j + columnIndex::T_AUDIO_1, newItem_audio);
3478             ui->tableWidget->setItem(numRows, j + columnIndex::T_AUDIOLANG_1, newItem_lang);
3479             ui->tableWidget->setItem(numRows, j + columnIndex::T_AUDIOTITLE_1, newItem_title);
3480             ui->tableWidget->setItem(numRows, j + columnIndex::T_AUDIOCHECK_1, newItem_checkstate);
3481         }
3482 
3483         QString subtitleFormat("");
3484         QString subtitleLang("");
3485         QString subtitleTitle("");
3486         QString subtitleCheckstate;
3487         for (int j = 0; j < AMOUNT_SUBTITLES; j++) {
3488             subtitleFormat = QString::fromStdWString(MI.Get(Stream_Text, size_t(j), L"Format"));
3489             subtitleLang = QString::fromStdWString(MI.Get(Stream_Text, size_t(j), L"Language"));
3490             subtitleTitle = QString::fromStdWString(MI.Get(Stream_Text, size_t(j), L"Title"));
3491             subtitleCheckstate = "0";
3492 
3493             if (subtitleFormat != "") {
3494                 subtitleCheckstate = "1";
3495             }
3496             QTableWidgetItem *newItem_subtitle = new QTableWidgetItem(subtitleFormat);
3497             QTableWidgetItem *newItem_lang = new QTableWidgetItem(subtitleLang);
3498             QTableWidgetItem *newItem_title = new QTableWidgetItem(subtitleTitle);
3499             QTableWidgetItem *newItem_checkstate = new QTableWidgetItem(subtitleCheckstate);
3500             ui->tableWidget->setItem(numRows, j + columnIndex::T_SUBTITLE_1, newItem_subtitle);
3501             ui->tableWidget->setItem(numRows, j + columnIndex::T_SUBLANG_1, newItem_lang);
3502             ui->tableWidget->setItem(numRows, j + columnIndex::T_TITLESUB_1, newItem_title);
3503             ui->tableWidget->setItem(numRows, j + columnIndex::T_SUBCHECK_1, newItem_checkstate);
3504         }
3505         MI.Close();
3506         showOpeningFiles(50);
3507         QApplication::processEvents();
3508         ui->tableWidget->selectRow(ui->tableWidget->rowCount() - 1);
3509         QApplication::processEvents();
3510         showOpeningFiles(100);
3511         QApplication::processEvents();
3512 #if defined (Q_OS_UNIX)
3513         usleep(50000);
3514 #elif defined (Q_OS_WIN64)
3515         Sleep(50);
3516 #endif
3517         i++;
3518     }
3519     showOpeningFiles(false);
3520 }
3521 
on_tableWidget_itemSelectionChanged()3522 void Widget::on_tableWidget_itemSelectionChanged()  /*** Item selection changed ***/
3523 {
3524     ui->labelAnimation->hide();
3525     ui->label_Progress->hide();
3526     ui->label_Remaining->hide();
3527     ui->label_RemTime->hide();
3528     ui->progressBar->hide();
3529     ui->labelSplitPreview->clear();
3530     ui->horizontalSlider->blockSignals(true);
3531     ui->horizontalSlider->setValue(0);
3532     ui->horizontalSlider->blockSignals(false);
3533     ui->lineEditCurTime->clear();
3534     ui->lineEditStartTime->clear();
3535     ui->lineEditEndTime->clear();
3536 
3537     // **************************** Disable audio widgets ***********************************//
3538     QList <QCheckBox *> checkBoxAudio = ui->frameTab_2->findChildren<QCheckBox *>();
3539     QList <QLineEdit *> lineEditAudio = ui->frameTab_2->findChildren<QLineEdit *>();
3540     QList <QLabel*> labelsAudio = ui->frameTab_2->findChildren<QLabel*>();
3541     foreach (QCheckBox *checkBox, checkBoxAudio) {
3542         checkBox->setVisible(false);
3543     }
3544     foreach (QLineEdit *lineEdit, lineEditAudio) {
3545         lineEdit->setVisible(false);
3546     }
3547     foreach (QLabel *label, labelsAudio) {
3548         label->setVisible(false);
3549     }
3550     audioThumb->setVisible(true);
3551 
3552     // **************************** Disable subtitle widgets ***********************************//
3553     QList <QCheckBox *> checkBoxSubtitle = ui->frameTab_3->findChildren<QCheckBox *>();
3554     QList <QLineEdit *> lineEditSubtitle = ui->frameTab_3->findChildren<QLineEdit *>();
3555     QList <QLabel*> labelsSubtitle = ui->frameTab_3->findChildren<QLabel*>();
3556     foreach (QCheckBox *checkBox, checkBoxSubtitle) {
3557         checkBox->setVisible(false);
3558     }
3559     foreach (QLineEdit *lineEdit, lineEditSubtitle) {
3560         lineEdit->setVisible(false);
3561     }
3562     foreach (QLabel *label, labelsSubtitle) {
3563         label->setVisible(false);
3564     }
3565     subtitleThumb->setVisible(true);
3566 
3567     _row = ui->tableWidget->currentRow();
3568     if (_row != -1) {
3569         raiseThumb->hide();
3570         get_current_data();
3571 
3572     } else {
3573         // ********************************* Reset widgets ***************************************//
3574         raiseThumb->show();
3575         ui->labelThumb->clear();
3576         ui->textBrowser_1->clear();
3577         ui->textBrowser_2->clear();
3578         ui->labelThumb->setText(tr("Preview"));
3579         ui->label_source->setText("");
3580         ui->label_output->setText("");
3581         ui->horizontalSlider->setMaximum(0);
3582 
3583         // **************************** Reset metadata widgets ***********************************//
3584         QList<QLineEdit *> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit *>();
3585         foreach (QLineEdit *lineEdit, linesEditMetadata) {
3586             lineEdit->clear();
3587             lineEdit->setEnabled(false);
3588         }
3589 
3590         // **************************** Reset audio widgets ***********************************//
3591         foreach (QLineEdit *lineEdit, lineEditAudio) {
3592             lineEdit->clear();
3593         }
3594         foreach (QCheckBox *checkBox, checkBoxAudio) {
3595             checkBox->setChecked(false);
3596         }
3597 
3598         // **************************** Reset subtitle widgets ***********************************//
3599         foreach (QLineEdit *lineEdit, lineEditSubtitle) {
3600             lineEdit->clear();
3601         }
3602         foreach (QCheckBox *checkBox, checkBoxSubtitle) {
3603             checkBox->setChecked(false);
3604         }
3605 
3606         // **************************** Reset video variables ***********************************//
3607         _dur = 0.0;
3608         _input_file = "";
3609         _stream_size = "";
3610         _width = "";
3611         _height = "";
3612         _fmt = "";
3613         _fps = "";
3614         _fr_count = 0;
3615         _startTime = 0.0;
3616         _endTime = 0.0;
3617 
3618         _hdr[CUR_COLOR_RANGE] = "";    // color range
3619         _hdr[CUR_COLOR_PRIMARY] = "";  // color primary
3620         _hdr[CUR_COLOR_MATRIX] = "";   // color matrix
3621         _hdr[CUR_TRANSFER] = "";       // transfer
3622         _hdr[CUR_MAX_LUM] = "";        // max lum
3623         _hdr[CUR_MIN_LUM] = "";        // min lum
3624         _hdr[CUR_MAX_CLL] = "";        // max cll
3625         _hdr[CUR_MAX_FALL] = "";       // max fall
3626         _hdr[CUR_MASTER_DISPLAY] = ""; // master display
3627         _hdr[CUR_CHROMA_COORD] = "";   // chr coord
3628         _hdr[CUR_WHITE_COORD] = "";    // white coord
3629 
3630         // **************************** Reset metadata variables ***********************************//
3631         _videoMetadata[VIDEO_TITLE] = "";
3632         _videoMetadata[VIDEO_AUTHOR] = "";
3633         _videoMetadata[VIDEO_YEAR] = "";
3634         _videoMetadata[VIDEO_PERFORMER] = "";
3635         _videoMetadata[VIDEO_DESCRIPTION] = "";
3636         _videoMetadata[VIDEO_MOVIENAME] = "";
3637 
3638         // **************************** Reset audio variables ***********************************//
3639         for (int i = 0; i < AMOUNT_AUDIO_STREAMS; i++) {
3640             _audioStreamCheckState[i] = 0;
3641             _audioLang[i] = "";
3642             _audioTitle[i] = "";
3643         }
3644 
3645         // **************************** Reset subtitle variables ***********************************//
3646         for (int i = 0; i < AMOUNT_SUBTITLES; i++) {
3647             _subtitleCheckState[i] = 0;
3648             _subtitleLang[i] = "";
3649             _subtitleTitle[i] = "";
3650         }
3651     }
3652 }
3653 
resizeTableRows(int rows_height)3654 void Widget::resizeTableRows(int rows_height)
3655 {
3656     QHeaderView *verticalHeader = ui->tableWidget->verticalHeader();
3657     verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
3658     verticalHeader->setDefaultSectionSize(rows_height);
3659     if (rows_height == 25) {
3660         ui->tableWidget->setIconSize(QSize(16, 16));
3661     } else {
3662         int rows_width = static_cast<int>(round(1.777f*rows_height));
3663         ui->tableWidget->setIconSize(QSize(rows_width, rows_height));
3664     }
3665     int numRows = ui->tableWidget->rowCount();
3666     if (numRows > 0) {
3667         int row = ui->tableWidget->currentRow();
3668         ui->tableWidget->clearSelection();
3669         if (numRows > 1) {
3670             for (int i = 0; i < numRows; i++) {
3671                 ui->tableWidget->selectRow(i);
3672             }
3673         }
3674         ui->tableWidget->selectRow(row);
3675     }
3676 }
3677 
resetView()3678 void Widget::resetView()
3679 {
3680     const QString defaultSettings(":/resources/data/default_settings.ini");
3681     QSettings *settings = new QSettings(defaultSettings, QSettings::IniFormat, this);
3682     if (settings->value("Version").toInt() == SETTINGS_VERSION) {
3683         // Restore Main Window
3684         settings->beginGroup("MainWindow");
3685         window->restoreState(settings->value("MainWindow/state").toByteArray());
3686         settings->endGroup();
3687     }
3688     delete settings;
3689 
3690     QList<int> dockSizesX = {};
3691     QList<int> dockSizesY = {};
3692     float coeffX[DOCKS_COUNT] = {0.25f, 0.04f, 0.48f, 0.48f, 0.25f, 0.25f, 0.25f, 0.25f};
3693     float coeffY[DOCKS_COUNT] = {0.9f, 0.1f, 0.1f, 0.1f, 0.9f, 0.9f, 0.9f, 0.9f};
3694     for (int ind = 0; ind < DOCKS_COUNT; ind++) {
3695         int dockWidth = static_cast<int>(coeffX[ind] * this->width());
3696         int dockHeight = static_cast<int>(coeffY[ind] * this->height());
3697         dockSizesX.append(dockWidth);
3698         dockSizesY.append(dockHeight);
3699     }
3700     setDocksParameters(dockSizesX, dockSizesY);
3701 }
3702 
provideContextMenu(const QPoint & position)3703 void Widget::provideContextMenu(const QPoint &position)     /*** Call table items menu  ***/
3704 {
3705     QTableWidgetItem *item = ui->tableWidget->itemAt(0, position.y());
3706     if (item != nullptr) {
3707         itemMenu->exec(ui->tableWidget->mapToGlobal(QPoint(position.x(), position.y() + 35)));
3708     }
3709 }
3710 
dragEnterEvent(QDragEnterEvent * event)3711 void Widget::dragEnterEvent(QDragEnterEvent* event)     /*** Drag enter event ***/
3712 {
3713     event->acceptProposedAction();
3714 }
3715 
dragMoveEvent(QDragMoveEvent * event)3716 void Widget::dragMoveEvent(QDragMoveEvent* event)     /*** Drag move event ***/
3717 {
3718     event->acceptProposedAction();
3719 }
3720 
dragLeaveEvent(QDragLeaveEvent * event)3721 void Widget::dragLeaveEvent(QDragLeaveEvent* event)     /*** Drag leave event ***/
3722 {
3723     event->accept();
3724 }
3725 
dropEvent(QDropEvent * event)3726 void Widget::dropEvent(QDropEvent* event)     /*** Drag & Drop ***/
3727 {
3728     const QMimeData *mimeData = event->mimeData();
3729     if (mimeData->hasUrls())
3730     {
3731         QStringList formats;
3732         QStringList pathList;
3733         QList<QUrl> urlList = mimeData->urls();
3734         for (int i = 0; i < urlList.size() && i < 32; ++i)
3735         {
3736             pathList.append(urlList.at(i).toLocalFile());
3737             formats.append(QMimeDatabase().mimeTypeForFile(pathList.at(i)).name());
3738         }
3739         if (!formats.filter("audio/").empty() || !formats.filter("video/").empty())
3740         {
3741             openFiles(pathList);
3742             event->acceptProposedAction();
3743             return;
3744         }
3745     }
3746     event->ignore();
3747 }
3748 
timeConverter(float & time)3749 QString Widget::timeConverter(float &time)     /*** Time converter to hh:mm:ss ***/
3750 {
3751     int h = static_cast<int>(trunc(time / 3600));
3752     int m = static_cast<int>(trunc((time - float(h * 3600)) / 60));
3753     int s = static_cast<int>(round(time - float(h * 3600) - float(m * 60)));
3754     QString hrs = QString::number(h);
3755     QString min = QString::number(m);
3756     QString sec = QString::number(s);
3757     std::ostringstream sstr;
3758     sstr << std::setw(2) << std::setfill('0') << hrs.toStdString() << ":"
3759          << std::setw(2) << std::setfill('0') << min.toStdString() << ":"
3760          << std::setw(2) << std::setfill('0') << sec.toStdString();
3761     std::string time_str = sstr.str();
3762 
3763     return QString::fromStdString(time_str);
3764 }
3765 
on_comboBoxMode_currentIndexChanged(int index)3766 void Widget::on_comboBoxMode_currentIndexChanged(int index)
3767 {
3768     if (index == 0) {
3769         _batch_mode = false;
3770     } else {
3771         _batch_mode = true;
3772     }
3773 }
3774 
on_horizontalSlider_resize_valueChanged(int value)3775 void Widget::on_horizontalSlider_resize_valueChanged(int value)
3776 {
3777     _rowSize = value;
3778     resizeTableRows(value);
3779 }
3780 
3781 /************************************************
3782 ** Preview Window
3783 ************************************************/
3784 
setThumbnail(QString curFilename,double time,QString quality,int destination)3785 QString Widget::setThumbnail(QString curFilename, double time, QString quality, int destination)     /*** Thumbnail ***/
3786 {
3787     QString qualityParam = "-vf scale=144:-1 -compression_level 10 -pix_fmt rgb24";
3788     if (quality == "low")
3789     {
3790         qualityParam = "-vf scale=144:-1,format=pal8,dctdnoiz=4.5";
3791     }
3792     const QString time_qstr = QString::number(time, 'f', 3);
3793     const QString tmb_name = curFilename.replace(".", "_").replace(" ", "_") + time_qstr;
3794     QString tmb_file = _thumb_path + QString("/") + tmb_name + QString(".png");
3795     QFile tmb(tmb_file);
3796     if (!tmb.exists()) {
3797         QStringList cmd;
3798         cmd << "-hide_banner" << "-ss" << time_qstr << "-i" << _input_file
3799             << qualityParam.split(" ") << "-vframes" << "1" << "-y" << tmb_file;
3800         processThumbCreation->start("ffmpeg", cmd);
3801         processThumbCreation->waitForFinished();
3802     }
3803     if (!tmb.exists()) {
3804         tmb_file = ":/resources/images/no_preview.png";
3805     }
3806     QPixmap pix(tmb_file);
3807     QPixmap pix_scaled;
3808     if (destination == 1) {
3809         pix_scaled = pix.scaled(ui->frame_preview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
3810         ui->labelThumb->setPixmap(pix_scaled);
3811     } else {
3812         pix_scaled = pix.scaled(ui->labelSplitPreview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
3813         ui->labelSplitPreview->setPixmap(pix_scaled);
3814     }
3815     return tmb_file;
3816 }
3817 
repeatHandler_Type_2()3818 void Widget::repeatHandler_Type_2()  /*** Repeat handler ***/
3819 {
3820     std::cout << "Call by timer... " << std::endl;
3821     if (_row != -1) {
3822         setThumbnail(_curFilename, _curTime, "high", 2);
3823     }
3824 }
3825 
3826 /************************************************
3827 ** Source Window
3828 ************************************************/
3829 
on_buttonHotInputFile_clicked()3830 void Widget::on_buttonHotInputFile_clicked()
3831 {
3832     on_actionAdd_clicked();
3833 }
3834 
3835 /************************************************
3836 ** Output Window
3837 ************************************************/
3838 
get_output_filename()3839 void Widget::get_output_filename()  /*** Get output data ***/
3840 {
3841     ui->textBrowser_2->clear();
3842     ui->textBrowser_2->setText(_cur_param[curParamIndex::OUTPUT_PARAM]);
3843     QString file_without_ext("");
3844     QString extension("");
3845     QString suffix("");
3846     QString prefix("");
3847     int _CODEC = _cur_param[curParamIndex::CODEC].toInt();
3848     int _CONTAINER = _cur_param[curParamIndex::CONTAINER].toInt();
3849     extension = updateFieldContainer(_CODEC, _CONTAINER).toLower();
3850 
3851     if (_suffixType == 0) {
3852         QString row_qstr = QString::number(_row);
3853         std::ostringstream sstr;
3854         sstr << std::setw(4) << std::setfill('0') << row_qstr.toStdString();
3855         std::string counter = sstr.str();
3856         suffix = _suffixName + QString::fromStdString(counter);
3857     } else {
3858         QTime ct = QTime::currentTime();
3859         QDate cd = QDate::currentDate();
3860         QString ct_qstr = ct.toString();
3861         QString cd_qstr = cd.toString("MM.dd.yyyy");
3862         suffix = QString("_") + ct_qstr.remove(":") + QString("_") + cd_qstr.remove(".");
3863     }
3864 
3865     if (_prefxType == 0) {
3866         std::wstring file_name_wstr = _curFilename.toStdWString();
3867         std::wstring::size_type separator = file_name_wstr.rfind('.');
3868         if (separator != std::wstring::npos) {
3869             file_without_ext = QString::fromStdWString(file_name_wstr.substr(0, separator));
3870         } else {
3871             file_without_ext = _curFilename;
3872         }
3873         prefix = file_without_ext;
3874     } else {
3875         prefix = _prefixName;
3876     }
3877 
3878     QString _output_file_name = prefix + suffix + QString(".") + extension;
3879     ui->label_output->setText(_output_file_name);
3880     if (_output_folder == "") {
3881         _output_file = _curPath + QString("/") + _output_file_name;
3882     } else {
3883         _output_file = _output_folder + QString("/") + _output_file_name;
3884     }
3885     if (_temp_folder == "") {
3886         _temp_file = _curPath + QString("/temp.mkv");
3887     } else {
3888         _temp_file = _temp_folder + QString("/temp.mkv");
3889     }
3890 }
3891 
on_buttonHotOutputFile_clicked()3892 void Widget::on_buttonHotOutputFile_clicked()
3893 {
3894     const QString output_folder_name = callFileDialog(tr("Select output folder"));
3895     if (output_folder_name.isEmpty()) return;
3896     _output_folder = output_folder_name;
3897     if (_row != -1) get_output_filename();
3898 }
3899 
callFileDialog(const QString title)3900 QString Widget::callFileDialog(const QString title)  /*** Call file dialog ***/
3901 {
3902     QFileDialog selectFolderWindow(nullptr);
3903     selectFolderWindow.setWindowTitle(title);
3904     selectFolderWindow.setMinimumWidth(600);
3905     selectFolderWindow.setWindowFlags(Qt::Dialog | Qt::SubWindow);
3906     if (_desktopEnv == "gnome") selectFolderWindow.setOption(QFileDialog::DontUseNativeDialog, true);
3907     selectFolderWindow.setFileMode(QFileDialog::DirectoryOnly);
3908     selectFolderWindow.setAcceptMode(QFileDialog::AcceptOpen);
3909     QString directory = QDir::homePath();
3910     if (_output_folder != "") directory = _output_folder;
3911     selectFolderWindow.setDirectory(directory);
3912     if (selectFolderWindow.exec() == QFileDialog::Accepted) {
3913         return selectFolderWindow.selectedFiles().at(0);
3914     }
3915     return QString("");
3916 }
3917 
3918 /************************************************
3919 ** Metadata Window
3920 ************************************************/
3921 
on_lineEditTitleVideo_editingFinished()3922 void Widget::on_lineEditTitleVideo_editingFinished()
3923 {
3924     if (_row != -1) {
3925         if (!ui->lineEditTitleVideo->isModified()) {
3926             return;
3927         }
3928         ui->lineEditTitleVideo->setModified(false);
3929         QString videoTitle = ui->lineEditTitleVideo->text();
3930         QTableWidgetItem *newItem_videoTitle = new QTableWidgetItem(videoTitle);
3931         ui->tableWidget->setItem(_row, columnIndex::T_VIDEOTITLE, newItem_videoTitle);
3932         _videoMetadata[VIDEO_TITLE] = videoTitle;
3933     }
3934 }
3935 
on_lineEditAuthorVideo_editingFinished()3936 void Widget::on_lineEditAuthorVideo_editingFinished()
3937 {
3938     if (_row != -1) {
3939         if (!ui->lineEditAuthorVideo->isModified()) {
3940             return;
3941         }
3942         ui->lineEditAuthorVideo->setModified(false);
3943         QString videoAuthor = ui->lineEditAuthorVideo->text();
3944         QTableWidgetItem *newItem_videoAuthor = new QTableWidgetItem(videoAuthor);
3945         ui->tableWidget->setItem(_row, columnIndex::T_VIDEOAUTHOR, newItem_videoAuthor);
3946         _videoMetadata[VIDEO_AUTHOR] = videoAuthor;
3947     }
3948 }
3949 
on_lineEditYearVideo_editingFinished()3950 void Widget::on_lineEditYearVideo_editingFinished()
3951 {
3952     if (_row != -1) {
3953         if (!ui->lineEditYearVideo->isModified()) {
3954             return;
3955         }
3956         ui->lineEditYearVideo->setModified(false);
3957         QString videoYear = ui->lineEditYearVideo->text();
3958         QTableWidgetItem *newItem_videoYear = new QTableWidgetItem(videoYear);
3959         ui->tableWidget->setItem(_row, columnIndex::T_VIDEOYEAR, newItem_videoYear);
3960         _videoMetadata[VIDEO_YEAR] = videoYear;
3961     }
3962 }
3963 
on_lineEditPerfVideo_editingFinished()3964 void Widget::on_lineEditPerfVideo_editingFinished()
3965 {
3966     if (_row != -1) {
3967         if (!ui->lineEditPerfVideo->isModified()) {
3968             return;
3969         }
3970         ui->lineEditPerfVideo->setModified(false);
3971         QString videoPerf = ui->lineEditPerfVideo->text();
3972         QTableWidgetItem *newItem_videoPerf = new QTableWidgetItem(videoPerf);
3973         ui->tableWidget->setItem(_row, columnIndex::T_VIDEOPERF, newItem_videoPerf);
3974         _videoMetadata[VIDEO_PERFORMER] = videoPerf;
3975     }
3976 }
3977 
on_lineEditMovieNameVideo_editingFinished()3978 void Widget::on_lineEditMovieNameVideo_editingFinished()
3979 {
3980     if (_row != -1) {
3981         if (!ui->lineEditMovieNameVideo->isModified()) {
3982             return;
3983         }
3984         ui->lineEditMovieNameVideo->setModified(false);
3985         QString videoMovieName = ui->lineEditMovieNameVideo->text();
3986         QTableWidgetItem *newItem_videoMovieName = new QTableWidgetItem(videoMovieName);
3987         ui->tableWidget->setItem(_row, columnIndex::T_VIDEOMOVIENAME, newItem_videoMovieName);
3988         _videoMetadata[VIDEO_MOVIENAME] = videoMovieName;
3989     }
3990 }
3991 
on_lineEditDescriptionVideo_editingFinished()3992 void Widget::on_lineEditDescriptionVideo_editingFinished()
3993 {
3994     if (_row != -1) {
3995         if (!ui->lineEditDescriptionVideo->isModified()) {
3996             return;
3997         }
3998         ui->lineEditDescriptionVideo->setModified(false);
3999         QString videoDescription = ui->lineEditDescriptionVideo->text();
4000         QTableWidgetItem *newItem_videoDescription = new QTableWidgetItem(videoDescription);
4001         ui->tableWidget->setItem(_row, columnIndex::T_VIDEODESCR, newItem_videoDescription);
4002         _videoMetadata[VIDEO_DESCRIPTION] = videoDescription;
4003     }
4004 }
4005 
on_actionClearMetadata_clicked()4006 void Widget::on_actionClearMetadata_clicked()
4007 {
4008     if (_row != -1) {
4009         QList<QLineEdit*> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit*>();
4010         foreach (QLineEdit *lineEdit, linesEditMetadata) {
4011             lineEdit->clear();
4012             lineEdit->insert("");
4013             lineEdit->setFocus();
4014             lineEdit->setModified(true);
4015         }
4016         ui->frame_middle->setFocus();
4017     }
4018 }
4019 
on_actionUndoMetadata_clicked()4020 void Widget::on_actionUndoMetadata_clicked()
4021 {
4022     if (_row != -1) {
4023         QList<QLineEdit*> linesEditMetadata = ui->frameTab_1->findChildren<QLineEdit*>();
4024         foreach (QLineEdit *lineEdit, linesEditMetadata) {
4025             lineEdit->undo();
4026             if (lineEdit->text() != "") {
4027                 lineEdit->setFocus();
4028                 lineEdit->setCursorPosition(0);
4029                 lineEdit->setModified(true);
4030             }
4031         }
4032         ui->frame_middle->setFocus();
4033     }
4034 }
4035 
4036 /************************************************
4037 ** Streams Window
4038 ************************************************/
4039 
on_actionClearAudioTitles_clicked()4040 void Widget::on_actionClearAudioTitles_clicked()
4041 {
4042     if (_row != -1) {
4043         for (int stream = 0; stream < AMOUNT_AUDIO_STREAMS; stream++) {
4044             QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
4045                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
4046             lineEditTitleAudio->clear();
4047             lineEditTitleAudio->insert("");
4048             lineEditTitleAudio->setFocus();
4049             lineEditTitleAudio->setModified(true);
4050         }
4051         ui->frame_middle->setFocus();
4052     }
4053 }
4054 
on_actionClearSubtitleTitles_clicked()4055 void Widget::on_actionClearSubtitleTitles_clicked()
4056 {
4057     if (_row != -1) {
4058         for (int stream = 0; stream < AMOUNT_SUBTITLES; stream++) {
4059             QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
4060                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
4061             lineEditTitleSubtitle->clear();
4062             lineEditTitleSubtitle->insert("");
4063             lineEditTitleSubtitle->setFocus();
4064             lineEditTitleSubtitle->setModified(true);
4065         }
4066         ui->frame_middle->setFocus();
4067     }
4068 }
4069 
on_actionUndoTitles_clicked()4070 void Widget::on_actionUndoTitles_clicked()
4071 {
4072     if (_row != -1) {
4073         for (int stream = 0; stream < AMOUNT_AUDIO_STREAMS; stream++) {
4074             QLineEdit *lineEditTitleAudio = ui->frameTab_2->findChild<QLineEdit *>("lineEditTitleAudio_"
4075                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
4076             lineEditTitleAudio->undo();
4077             if (lineEditTitleAudio->text() != "") {
4078                 lineEditTitleAudio->setFocus();
4079                 lineEditTitleAudio->setCursorPosition(0);
4080                 lineEditTitleAudio->setModified(true);
4081             }
4082         }
4083         for (int stream = 0; stream < AMOUNT_SUBTITLES; stream++) {
4084             QLineEdit *lineEditTitleSubtitle = ui->frameTab_3->findChild<QLineEdit *>("lineEditTitleSubtitle_"
4085                 + QString::number(stream + 1), Qt::FindDirectChildrenOnly);
4086             lineEditTitleSubtitle->undo();
4087             if (lineEditTitleSubtitle->text() != "") {
4088                 lineEditTitleSubtitle->setFocus();
4089                 lineEditTitleSubtitle->setCursorPosition(0);
4090                 lineEditTitleSubtitle->setModified(true);
4091             }
4092         }
4093         ui->frame_middle->setFocus();
4094     }
4095 }
4096 
4097 /************************************************
4098 ** Split Window
4099 ************************************************/
4100 
on_horizontalSlider_valueChanged(int value)4101 void Widget::on_horizontalSlider_valueChanged(int value)
4102 {
4103     if (_row != -1) {
4104         double fps_double = _fps.toDouble();
4105         if (fps_double != 0.0) {
4106             _curTime = round(1000.0 * (static_cast<double>(value) / fps_double)) / 1000.0;
4107         } else {
4108             _curTime = 0.0;
4109         }
4110         ui->lineEditCurTime->setText(timeConverter(_curTime));
4111         timerCallSetThumbnail->stop();
4112         timerCallSetThumbnail->start();
4113     }
4114 }
4115 
on_buttonFramePrevious_clicked()4116 void Widget::on_buttonFramePrevious_clicked()
4117 {
4118     int value = ui->horizontalSlider->value();
4119     if (value > 0) {
4120         ui->horizontalSlider->setValue(value - 1);
4121     }
4122 }
4123 
on_buttonFrameNext_clicked()4124 void Widget::on_buttonFrameNext_clicked()
4125 {
4126     int value = ui->horizontalSlider->value();
4127     if (value < _fr_count) {
4128         ui->horizontalSlider->setValue(value + 1);
4129     }
4130 }
4131 
on_buttonSetStartTime_clicked()4132 void Widget::on_buttonSetStartTime_clicked()
4133 {
4134     if (_row != -1) {
4135         _startTime = _curTime;
4136         if (_startTime > _endTime && _endTime != 0.0)
4137         {
4138             _startTime = _endTime;
4139         }
4140         ui->lineEditStartTime->setText(timeConverter(_startTime));
4141         QTableWidgetItem *newItem_startTime = new QTableWidgetItem(QString::number(_startTime, 'f', 3));
4142         ui->tableWidget->setItem(_row, columnIndex::T_STARTTIME, newItem_startTime);
4143     }
4144 }
4145 
on_buttonSetEndTime_clicked()4146 void Widget::on_buttonSetEndTime_clicked()
4147 {
4148     if (_row != -1) {
4149         _endTime = _curTime;
4150         if (_endTime < _startTime)
4151         {
4152             _endTime =_startTime;
4153         }
4154         ui->lineEditEndTime->setText(timeConverter(_endTime));
4155         QTableWidgetItem *newItem_endTime = new QTableWidgetItem(QString::number(_endTime, 'f', 3));
4156         ui->tableWidget->setItem(_row, columnIndex::T_ENDTIME, newItem_endTime);
4157     }
4158 }
4159 
on_actionResetLabels_clicked()4160 void Widget::on_actionResetLabels_clicked()
4161 {
4162     if (_row != -1) {
4163         ui->labelSplitPreview->clear();
4164         ui->horizontalSlider->blockSignals(true);
4165         ui->horizontalSlider->setValue(0);
4166         ui->horizontalSlider->blockSignals(false);
4167 
4168         _curTime = 0.0;
4169         ui->lineEditCurTime->setText(timeConverter(_curTime));
4170 
4171         _startTime = 0.0;
4172         ui->lineEditStartTime->setText(timeConverter(_startTime));
4173         QTableWidgetItem *newItem_startTime = new QTableWidgetItem(QString::number(_startTime, 'f', 3));
4174         ui->tableWidget->setItem(_row, columnIndex::T_STARTTIME, newItem_startTime);
4175 
4176         _endTime = 0.0;
4177         ui->lineEditEndTime->setText(timeConverter(_endTime));
4178         QTableWidgetItem *newItem_endTime = new QTableWidgetItem(QString::number(_endTime, 'f', 3));
4179         ui->tableWidget->setItem(_row, columnIndex::T_ENDTIME, newItem_endTime);
4180     }
4181 }
4182 
timeConverter(double & time)4183 QString Widget::timeConverter(double &time)     /*** Time converter to hh:mm:ss.msc ***/
4184 {
4185     int h = static_cast<int>(trunc(time / 3600));
4186     int m = static_cast<int>(trunc((time - double(h * 3600)) / 60));
4187     int s = static_cast<int>(trunc(time - double(h * 3600) - double(m * 60)));
4188     int ms = static_cast<int>(round(1000 * (time - double(h * 3600) - double(m * 60) - double(s))));
4189 
4190     QString hrs = QString::number(h);
4191     QString min = QString::number(m);
4192     QString sec = QString::number(s);
4193     QString msec = QString::number(ms);
4194 
4195     std::ostringstream sstr;
4196     sstr << std::setw(2) << std::setfill('0') << hrs.toStdString() << ":"
4197          << std::setw(2) << std::setfill('0') << min.toStdString() << ":"
4198          << std::setw(2) << std::setfill('0') << sec.toStdString() << "."
4199          << std::setw(3) << msec.toStdString();
4200     std::string time_str = sstr.str();
4201 
4202     return QString::fromStdString(time_str);
4203 }
4204 
4205 /************************************************
4206 ** Preset Window
4207 ************************************************/
4208 
set_defaults()4209 void Widget::set_defaults() /*** Set default presets ***/
4210 {
4211     std::cout<< "Set defaults..." << std::endl;
4212     QFile _prs_file(":/resources/data/default_presets.ini");
4213     if (_prs_file.open(QIODevice::ReadOnly)) {
4214         QDataStream in(&_prs_file);
4215         in.setVersion(QDataStream::Qt_4_0);
4216         int ver;
4217         in >> ver;
4218         if (ver == PRESETS_VERSION) {
4219             in >> _cur_param >> _pos_top >> _pos_cld >> _preset_table;
4220         }
4221         _prs_file.close();
4222     }
4223 }
4224 
on_buttonApplyPreset_clicked()4225 void Widget::on_buttonApplyPreset_clicked()  /*** Apply preset ***/
4226 {
4227     int index = ui->treeWidget->currentIndex().row();
4228     if (index < 0) {
4229         _message = tr("Select preset first!\n");
4230         call_task_complete(_message, false);
4231         return;
4232     }
4233     QTreeWidgetItem *item = ui->treeWidget->currentItem();
4234     QTreeWidgetItem *parentItem = item->parent();
4235     if (parentItem != nullptr) {
4236         // Item is child...
4237         for (int k = 0; k < PARAMETERS_COUNT; k++) {
4238             _cur_param[k] = item->text(k+7);
4239         }
4240 
4241     } else {
4242         // Item is parent...
4243         _message = tr("Select preset first!\n");
4244         call_task_complete(_message, false);
4245         return;
4246     }
4247     _pos_top = ui->treeWidget->indexOfTopLevelItem(parentItem);
4248     _pos_cld = parentItem->indexOfChild(item);
4249     std::cout << "Pos_top: " << _pos_top << std::endl;  // Current section pos
4250     std::cout << "Pos_cld: " << _pos_cld << std::endl;  // Current preset pos
4251     if (_row != -1) {
4252         get_output_filename();
4253     }
4254 }
4255 
on_actionRemove_preset_clicked()4256 void Widget::on_actionRemove_preset_clicked()  /*** Remove preset ***/
4257 {
4258     int index = ui->treeWidget->currentIndex().row();
4259     if (index < 0) {
4260         return;
4261     }
4262     QTreeWidgetItem *item = ui->treeWidget->currentItem();
4263     QTreeWidgetItem *parentItem = item->parent();
4264     if (parentItem != nullptr) {
4265         // Item is child...
4266         _message = tr("Delete?");
4267         bool confirm = call_dialog(_message);
4268         if (confirm == true)
4269         {
4270             int index_top = ui->treeWidget->indexOfTopLevelItem(parentItem);
4271             int index_child = parentItem->indexOfChild(item);
4272             updateCurPresetPos(index_top, index_child);
4273 
4274             QTreeWidgetItem *takenItem = parentItem->takeChild(index_child);
4275             Q_ASSERT(takenItem == item);
4276             delete takenItem;
4277             updatePresetTable();
4278         }
4279 
4280     } else {
4281         // Item is parent...
4282         int count_child = item->childCount();
4283         if (count_child == 0) {
4284             int index_top = ui->treeWidget->indexOfTopLevelItem(item);
4285             int index_child = -1;
4286             updateCurPresetPos(index_top, index_child);
4287 
4288             QTreeWidgetItem *takenItem = ui->treeWidget->takeTopLevelItem(index_top);
4289             Q_ASSERT(takenItem==item);
4290             delete takenItem;
4291             updatePresetTable();
4292 
4293         } else {
4294             _message = tr("Delete presets first!\n");
4295             call_task_complete(_message, false);
4296         }
4297     }
4298 }
4299 
on_actionEdit_preset_clicked()4300 void Widget::on_actionEdit_preset_clicked()  /*** Edit preset ***/
4301 {
4302     int index = ui->treeWidget->currentIndex().row();
4303     if (index < 0) {
4304         _message = tr("Select preset first!\n");
4305         call_task_complete(_message, false);
4306         return;
4307     }
4308     QTreeWidgetItem *item = ui->treeWidget->currentItem();
4309     QTreeWidgetItem *parentItem = item->parent();
4310     if (parentItem != nullptr) {
4311         // Item is child...
4312         for (int k = 0; k < PARAMETERS_COUNT; k++) {
4313             _new_param[k] = item->text(k+7);
4314         };
4315         Preset presetWindow(this);
4316         presetWindow.setParameters(&_presetWindowGeometry, &_new_param);
4317         presetWindow.setModal(true);
4318         if (presetWindow.exec() == QDialog::Accepted) {
4319             for (int k = 0; k < PARAMETERS_COUNT; k++) {
4320                 item->setText(k+7, _new_param[k]);
4321             }
4322             updateInfoFields(_new_param[1], _new_param[2], _new_param[3], _new_param[4],
4323                              _new_param[11], _new_param[12], _new_param[21], item, true);
4324             int index_top = ui->treeWidget->indexOfTopLevelItem(parentItem);
4325             int index_child = parentItem->indexOfChild(item);
4326             if (_pos_top == index_top && _pos_cld == index_child) {
4327                 for (int k = 0; k < PARAMETERS_COUNT; k++) {
4328                     _cur_param[k] = item->text(k+7);
4329                 }
4330                 if (_row != -1) {
4331                     get_output_filename();
4332                 }
4333             }
4334             updatePresetTable();
4335         }
4336     } else {
4337         // Item is parent...
4338         _message = tr("Select preset first!\n");
4339         call_task_complete(_message, false);
4340     }
4341 }
4342 
add_section()4343 void Widget::add_section()  /*** Add section ***/
4344 {
4345     QFont parentFont;
4346     parentFont.setBold(true);
4347     QTreeWidgetItem *root = new QTreeWidgetItem();
4348     root->setText(0, "New section");
4349     root->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
4350     root->setFont(0, parentFont);
4351     setPresetIcon(root, true);
4352     ui->treeWidget->addTopLevelItem(root);
4353     ui->treeWidget->setCurrentItem(root);
4354     root->setFirstColumnSpanned(true);
4355     updatePresetTable();
4356 }
4357 
add_preset()4358 void Widget::add_preset()  /*** Add preset ***/
4359 {
4360     int index = ui->treeWidget->currentIndex().row();
4361     if (index < 0) {
4362         _message = tr("First add a section!\n");
4363         call_task_complete(_message, false);
4364         return;
4365     }
4366 
4367     QVector<QString> cur_param;
4368     QFile _prs_file(":/resources/data/default_presets.ini");
4369     if (_prs_file.open(QIODevice::ReadOnly)) {
4370         QDataStream in(&_prs_file);
4371         in.setVersion(QDataStream::Qt_4_0);
4372         int ver;
4373         in >> ver;
4374         if (ver == PRESETS_VERSION) {
4375             in >> cur_param;
4376             QTreeWidgetItem *item = ui->treeWidget->currentItem();
4377             QTreeWidgetItem *parentItem = item->parent();
4378             QTreeWidgetItem *child = new QTreeWidgetItem();
4379             for (int k = 0; k < PARAMETERS_COUNT; k++) {
4380                 child->setText(k + 7, cur_param[k]);
4381             }
4382             updateInfoFields(cur_param[1], cur_param[2], cur_param[3], cur_param[4],
4383                              cur_param[11], cur_param[12], cur_param[21], child, true);
4384             setItemStyle(child);
4385             if (parentItem != nullptr) {
4386                 // Item is child...
4387                 parentItem->addChild(child);
4388 
4389                 int index_top = ui->treeWidget->indexOfTopLevelItem(parentItem);
4390                 int index_child = parentItem->indexOfChild(child);
4391                 updateCurPresetPos(index_top, index_child);
4392             } else {
4393                 // Item is parent...
4394                 item->addChild(child);
4395                 ui->treeWidget->expandItem(item);
4396 
4397                 int index_top = ui->treeWidget->indexOfTopLevelItem(item);
4398                 int index_child = item->indexOfChild(child);
4399                 updateCurPresetPos(index_top, index_child);
4400             }
4401             updatePresetTable();
4402         }
4403         _prs_file.close();
4404     }
4405 }
4406 
renameSectionPreset()4407 void Widget::renameSectionPreset()
4408 {
4409     QTreeWidgetItem *item = ui->treeWidget->currentItem();
4410     QTreeWidgetItem *parentItem = item->parent();
4411     if (parentItem != nullptr) {
4412         item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
4413         ui->treeWidget->editItem(item, 0);
4414         item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
4415     } else {
4416         ui->treeWidget->editItem(item, 0);
4417     }
4418 }
4419 
setItemStyle(QTreeWidgetItem * item)4420 void Widget::setItemStyle(QTreeWidgetItem *item)
4421 {
4422     QFont font = qApp->font();
4423     font.setItalic(true);
4424     QColor foregroundChildColor;
4425     switch (_theme)
4426     {
4427         case 0:
4428         case 1:
4429         case 2:
4430             foregroundChildColor.setRgb(qRgb(50, 100, 157));
4431             break;
4432         case 3:
4433             foregroundChildColor.setRgb(qRgb(30, 50, 150));
4434             break;
4435     }
4436     item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
4437     item->setTextAlignment(0, Qt::AlignLeft | Qt::AlignVCenter);
4438     item->setForeground(0, foregroundChildColor);
4439     item->setFont(0, font);
4440     for (int column = 1; column < 7; column++) {
4441         item->setTextAlignment(column, Qt::AlignCenter);
4442         item->setForeground(column, foregroundChildColor);
4443         item->setFont(column, font);
4444     }
4445 }
4446 
updateCurPresetPos(int & index_top,int & index_child)4447 void Widget::updateCurPresetPos(int &index_top, int &index_child)
4448 {
4449     std::cout << "Pos top: " << _pos_top << " Pos child: " << _pos_cld
4450               << " >>>>>> Index top: " << index_top << " Index child: " << index_child << std::endl;
4451     //if (index_child == _pos_cld) {
4452     _pos_top = -1;
4453     _pos_cld = -1;
4454     _cur_param[curParamIndex::OUTPUT_PARAM] = tr("Preset not selected");
4455     if (_row != -1) {
4456         get_output_filename();
4457     }
4458     //}
4459 }
4460 
updateInfoFields(QString & codec_qstr,QString & mode_qstr,QString & container_qstr,QString & bqr_qstr,QString & pass_qstr,QString & preset_qstr,QString & acodec_qstr,QTreeWidgetItem * item,bool defaultNameFlag)4461 void Widget::updateInfoFields(QString &codec_qstr, QString &mode_qstr, QString &container_qstr,
4462                               QString &bqr_qstr, QString &pass_qstr, QString &preset_qstr,
4463                               QString &acodec_qstr, QTreeWidgetItem *item, bool defaultNameFlag)
4464 {
4465     int codec = codec_qstr.toInt();
4466     int mode = mode_qstr.toInt();
4467     int preset = preset_qstr.toInt();
4468     int pass = pass_qstr.toInt();
4469     int acodec = acodec_qstr.toInt();
4470     int container = container_qstr.toInt();
4471     if (defaultNameFlag) {
4472         item->setText(0, updateFieldCodec(codec));
4473         QString newPresetName = item->text(0);
4474         item->setText(30 + 7, newPresetName);
4475     }
4476     item->setText(1, updateFieldMode(codec, mode));
4477     item->setText(2, bqr_qstr);
4478     item->setText(3, updateFieldPreset(codec, preset));
4479     item->setText(4, updateFieldPass(codec, pass));
4480     item->setText(5, updateFieldAcodec(codec, acodec));
4481     item->setText(6, updateFieldContainer(codec, container));
4482 }
4483 
updatePresetTable()4484 void Widget::updatePresetTable()
4485 {
4486     int TOP_LEVEL_ITEMS_COUNT = ui->treeWidget->topLevelItemCount();
4487     int CHILD_COUNT = 0;
4488     for (int i = 0; i < TOP_LEVEL_ITEMS_COUNT; i++) {
4489         CHILD_COUNT += ui->treeWidget->topLevelItem(i)->childCount();
4490     }
4491     int ROWS_COUNT = TOP_LEVEL_ITEMS_COUNT + CHILD_COUNT;  // Count of all rows...
4492     /****************************************************/
4493     for (int i = 0; i < PARAMETERS_COUNT+1; i++) {
4494       _preset_table[i].resize(ROWS_COUNT);
4495     }
4496     /****************************************************/
4497     int row = 0;
4498     for (int top = 0; top < TOP_LEVEL_ITEMS_COUNT; top++) {
4499         _preset_table[0][row] = ui->treeWidget->topLevelItem(top)->text(0);
4500         _preset_table[PARAMETERS_COUNT][row] = "TopLewelItem";
4501 
4502         CHILD_COUNT = ui->treeWidget->topLevelItem(top)->childCount();
4503         for (int child = 0; child < CHILD_COUNT; child++) {
4504             row++;
4505             for (int column = 0; column < PARAMETERS_COUNT; column++) {
4506                 _preset_table[column][row] = ui->treeWidget->topLevelItem(top)->child(child)->text(column+7);
4507             }
4508             _preset_table[PARAMETERS_COUNT][row] = "ChildItem";
4509         }
4510         row++;
4511     }
4512     /****************************************************/
4513     std::cout << _preset_table[0].size() << " x " << _preset_table.size() << std::endl; // Table size
4514 }
4515 
updateFieldCodec(int & codec)4516 QString Widget::updateFieldCodec(int &codec)
4517 {
4518     QString arr_codec[NUMBER_PRESETS] = {
4519         tr("H.265/HEVC 4:2:0 12 bit"),
4520         tr("H.265/HEVC 4:2:0 10 bit"),
4521         tr("H.265/HEVC 4:2:0 8 bit"),
4522         tr("H.264/AVC 4:2:0 8 bit"),
4523         tr("VP9 4:2:0 10 bit"),
4524         tr("VP9 4:2:0 8 bit"),
4525         tr("Intel QSV H.265/HEVC 4:2:0 10 bit"),
4526         tr("Intel QSV H.265/HEVC 4:2:0 8 bit"),
4527         tr("Intel QSV H.264/AVC 4:2:0 8 bit"),
4528         tr("Intel QSV VP9 4:2:0 10 bit"),
4529         tr("Intel QSV VP9 4:2:0 8 bit"),
4530         tr("Intel QSV MPEG-2 4:2:0 8 bit"),
4531         tr("NVENC H.265/HEVC 4:2:0 10 bit"),
4532         tr("NVENC H.265/HEVC 4:2:0 8 bit"),
4533         tr("NVENC H.264/AVC 4:2:0 8 bit"),
4534         tr("ProRes Proxy"),
4535         "ProRes LT",
4536         tr("ProRes Standard"),
4537         "ProRes HQ",
4538         "ProRes 4444",
4539         "ProRes 4444XQ",
4540         "DNxHR LB",
4541         "DNxHR SQ",
4542         "DNxHR HQ",
4543         "DNxHR HQX",
4544         "DNxHR 444",
4545         "XDCAM HD422",
4546         "XAVC 4:2:2",
4547         tr("From source")
4548     };
4549     return arr_codec[codec];
4550 }
4551 
updateFieldMode(int & codec,int & mode)4552 QString Widget::updateFieldMode(int &codec, int &mode)
4553 {
4554     QString arr_mode[NUMBER_PRESETS][5] = {
4555         {"CBR",      "ABR", "VBR", "CRF", "CQP"},
4556         {"CBR",      "ABR", "VBR", "CRF", "CQP"},
4557         {"CBR",      "ABR", "VBR", "CRF", "CQP"},
4558         {"CBR",      "ABR", "VBR", "CRF", "CQP"},
4559         {"ABR",      "CRF", "",    "",    ""},
4560         {"ABR",      "CRF", "",    "",    ""},
4561         {"VBR",      "",    "",    "",    ""},
4562         {"VBR",      "",    "",    "",    ""},
4563         {"VBR",      "",    "",    "",    ""},
4564         {"ABR",      "CRF", "",    "",    ""},
4565         {"ABR",      "CRF", "",    "",    ""},
4566         {"VBR",      "",    "",    "",    ""},
4567         {"VBR",      "",    "",    "",    ""},
4568         {"VBR",      "",    "",    "",    ""},
4569         {"VBR",      "",    "",    "",    ""},
4570         {tr("Auto"), "",    "",    "",    ""},
4571         {tr("Auto"), "",    "",    "",    ""},
4572         {tr("Auto"), "",    "",    "",    ""},
4573         {tr("Auto"), "",    "",    "",    ""},
4574         {tr("Auto"), "",    "",    "",    ""},
4575         {tr("Auto"), "",    "",    "",    ""},
4576         {tr("Auto"), "",    "",    "",    ""},
4577         {tr("Auto"), "",    "",    "",    ""},
4578         {tr("Auto"), "",    "",    "",    ""},
4579         {tr("Auto"), "",    "",    "",    ""},
4580         {tr("Auto"), "",    "",    "",    ""},
4581         {"VBR",      "",    "",    "",    ""},
4582         {"CBR",      "",    "",    "",    ""},
4583         {tr("Auto"), "",    "",    "",    ""}
4584     };
4585     return arr_mode[codec][mode];
4586 }
4587 
updateFieldPreset(int & codec,int & preset)4588 QString Widget::updateFieldPreset(int &codec, int &preset)
4589 {
4590     QString arr_preset[NUMBER_PRESETS][10] = {
4591         {tr("None"), tr("Ultrafast"), tr("Superfast"), tr("Veryfast"), tr("Faster"), tr("Fast"), tr("Medium"), tr("Slow"),     tr("Slower"), tr("Veryslow")},
4592         {tr("None"), tr("Ultrafast"), tr("Superfast"), tr("Veryfast"), tr("Faster"), tr("Fast"), tr("Medium"), tr("Slow"),     tr("Slower"), tr("Veryslow")},
4593         {tr("None"), tr("Ultrafast"), tr("Superfast"), tr("Veryfast"), tr("Faster"), tr("Fast"), tr("Medium"), tr("Slow"),     tr("Slower"), tr("Veryslow")},
4594         {tr("None"), tr("Ultrafast"), tr("Superfast"), tr("Veryfast"), tr("Faster"), tr("Fast"), tr("Medium"), tr("Slow"),     tr("Slower"), tr("Veryslow")},
4595         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4596         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4597         {tr("None"), tr("Veryfast"),  tr("Faster"),    tr("Fast"),     tr("Medium"), tr("Slow"), tr("Slower"), tr("Veryslow"), "",           ""},
4598         {tr("None"), tr("Veryfast"),  tr("Faster"),    tr("Fast"),     tr("Medium"), tr("Slow"), tr("Slower"), tr("Veryslow"), "",           ""},
4599         {tr("None"), tr("Veryfast"),  tr("Faster"),    tr("Fast"),     tr("Medium"), tr("Slow"), tr("Slower"), tr("Veryslow"), "",           ""},
4600         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4601         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4602         {tr("None"), tr("Veryfast"),  tr("Faster"),    tr("Fast"),     tr("Medium"), tr("Slow"), tr("Slower"), tr("Veryslow"), "",           ""},
4603         {tr("None"), tr("Slow"),      "",              "",             "",           "",         "",           "",             "",           ""},
4604         {tr("None"), tr("Slow"),      "",              "",             "",           "",         "",           "",             "",           ""},
4605         {tr("None"), tr("Slow"),      "",              "",             "",           "",         "",           "",             "",           ""},
4606         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4607         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4608         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4609         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4610         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4611         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4612         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4613         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4614         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4615         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4616         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4617         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""},
4618         {tr("None"), tr("Ultrafast"), tr("Superfast"), tr("Veryfast"), tr("Faster"), tr("Fast"), tr("Medium"), tr("Slow"),     tr("Slower"), tr("Veryslow")},
4619         {tr("None"), "",              "",              "",             "",           "",         "",           "",             "",           ""}
4620     };
4621     return arr_preset[codec][preset];
4622 }
4623 
updateFieldPass(int & codec,int & pass)4624 QString Widget::updateFieldPass(int &codec, int &pass)
4625 {
4626     QString arr_pass[NUMBER_PRESETS][2] = {
4627         {tr("1 Pass"), tr("2 Pass")},
4628         {tr("1 Pass"), tr("2 Pass")},
4629         {tr("1 Pass"), tr("2 Pass")},
4630         {tr("1 Pass"), tr("2 Pass")},
4631         {tr("1 Pass"), tr("2 Pass")},
4632         {tr("1 Pass"), tr("2 Pass")},
4633         {tr("Auto"),   ""},
4634         {tr("Auto"),   ""},
4635         {tr("Auto"),   ""},
4636         {tr("Auto"),   ""},
4637         {tr("Auto"),   ""},
4638         {tr("Auto"),   ""},
4639         {tr("2 Pass"), ""},
4640         {tr("2 Pass"), ""},
4641         {tr("2 Pass"), ""},
4642         {tr("Auto"),   ""},
4643         {tr("Auto"),   ""},
4644         {tr("Auto"),   ""},
4645         {tr("Auto"),   ""},
4646         {tr("Auto"),   ""},
4647         {tr("Auto"),   ""},
4648         {tr("Auto"),   ""},
4649         {tr("Auto"),   ""},
4650         {tr("Auto"),   ""},
4651         {tr("Auto"),   ""},
4652         {tr("Auto"),   ""},
4653         {tr("Auto"),   ""},
4654         {tr("Auto"),   ""},
4655         {tr("Auto"),   ""}
4656     };
4657     return arr_pass[codec][pass];
4658 }
4659 
updateFieldAcodec(int & codec,int & acodec)4660 QString Widget::updateFieldAcodec(int &codec, int &acodec)
4661 {
4662     QString arr_acodec[NUMBER_PRESETS][6] = {
4663         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4664         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4665         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4666         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4667         {"Opus",       "Vorbis",     tr("Source"), "",           "",     ""},
4668         {"Opus",       "Vorbis",     tr("Source"), "",           "",     ""},
4669         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4670         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4671         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4672         {"Opus",       "Vorbis",     tr("Source"), "",           "",     ""},
4673         {"Opus",       "Vorbis",     tr("Source"), "",           "",     ""},
4674         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4675         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4676         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4677         {"AAC",        "AC3",        "DTS",        tr("Source"), "",     ""},
4678         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4679         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4680         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4681         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4682         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4683         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4684         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4685         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4686         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4687         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4688         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4689         {"PCM 16 bit", "",           "",           "",           "",     ""},
4690         {"PCM 16 bit", "PCM 24 bit", "PCM 32 bit", "",           "",     ""},
4691         {"AAC",        "AC3",        "DTS",        "Vorbis",     "Opus", tr("Source")}
4692     };
4693     return arr_acodec[codec][acodec];
4694 }
4695 
updateFieldContainer(int & codec,int & container)4696 QString Widget::updateFieldContainer(int &codec, int &container)
4697 {
4698     QString arr_container[NUMBER_PRESETS][5] = {
4699         {"MKV",  "MOV", "MP4", "",     ""},
4700         {"MKV",  "MOV", "MP4", "",     ""},
4701         {"MKV",  "MOV", "MP4", "M2TS", "TS"},
4702         {"MKV",  "MOV", "MP4", "M2TS", "TS"},
4703         {"WebM", "MKV", "",    "",     ""},
4704         {"WebM", "MKV", "",    "",     ""},
4705         {"MKV",  "MOV", "MP4", "",     ""},
4706         {"MKV",  "MOV", "MP4", "",     ""},
4707         {"MKV",  "MOV", "MP4", "",     ""},
4708         {"WebM", "MKV", "",    "",     ""},
4709         {"WebM", "MKV", "",    "",     ""},
4710         {"MKV",  "MPG", "AVI", "M2TS", "TS"},
4711         {"MKV",  "MOV", "MP4", "",     ""},
4712         {"MKV",  "MOV", "MP4", "M2TS", "TS"},
4713         {"MKV",  "MOV", "MP4", "M2TS", "TS"},
4714         {"MOV",  "",    "",    "",     ""},
4715         {"MOV",  "",    "",    "",     ""},
4716         {"MOV",  "",    "",    "",     ""},
4717         {"MOV",  "",    "",    "",     ""},
4718         {"MOV",  "",    "",    "",     ""},
4719         {"MOV",  "",    "",    "",     ""},
4720         {"MOV",  "",    "",    "",     ""},
4721         {"MOV",  "",    "",    "",     ""},
4722         {"MOV",  "",    "",    "",     ""},
4723         {"MOV",  "",    "",    "",     ""},
4724         {"MOV",  "",    "",    "",     ""},
4725         {"MXF",  "",    "",    "",     ""},
4726         {"MXF",  "",    "",    "",     ""},
4727         {"MKV",  "MOV", "MP4", "M2TS", "TS"}
4728     };
4729     return arr_container[codec][container];
4730 }
4731 
setPresetIcon(QTreeWidgetItem * item,bool collapsed)4732 void Widget::setPresetIcon(QTreeWidgetItem *item, bool collapsed)
4733 {
4734     QIcon sectionIcon;
4735     QString path;
4736     switch (_theme)
4737     {
4738         case 0:
4739         case 1:
4740         case 2:
4741             if (collapsed) {
4742                 path = QString::fromUtf8(":/resources/icons/16x16/cil-folder.png");
4743             } else {
4744                 path = QString::fromUtf8(":/resources/icons/16x16/cil-folder-open.png");}
4745             break;
4746         case 3:
4747             if (collapsed) {
4748                 path = QString::fromUtf8(":/resources/icons/16x16/cil-folder_light.png");
4749             } else {
4750                 path = QString::fromUtf8(":/resources/icons/16x16/cil-folder-open_light.png");}
4751             break;
4752     }
4753     sectionIcon.addFile(path, QSize(), QIcon::Normal, QIcon::Off);
4754     item->setIcon(0, sectionIcon);
4755 }
4756 
on_treeWidget_itemCollapsed(QTreeWidgetItem * item)4757 void Widget::on_treeWidget_itemCollapsed(QTreeWidgetItem *item)
4758 {
4759     if (item != nullptr) {
4760         setPresetIcon(item, true);
4761     }
4762 }
4763 
on_treeWidget_itemExpanded(QTreeWidgetItem * item)4764 void Widget::on_treeWidget_itemExpanded(QTreeWidgetItem *item)
4765 {
4766     if (item != nullptr) {
4767         setPresetIcon(item, false);
4768     }
4769 }
4770 
on_treeWidget_itemChanged(QTreeWidgetItem * item,int column)4771 void Widget::on_treeWidget_itemChanged(QTreeWidgetItem *item, int column)
4772 {
4773     if (item->isSelected() && column == 0) {
4774         QTreeWidgetItem *parentItem = item->parent();
4775         if (parentItem != nullptr) {
4776             QString newPresetName = item->text(0);
4777             item->setText(30 + 7, newPresetName);
4778         }
4779         updatePresetTable();
4780     }
4781 }
4782 
on_treeWidget_itemDoubleClicked(QTreeWidgetItem * item,int column)4783 void Widget::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
4784 {
4785     QTreeWidgetItem *parentItem = item->parent();
4786     if (parentItem != nullptr) {
4787         on_buttonApplyPreset_clicked();
4788         std::cout << "Double clicked column: " << column << std::endl;
4789     }
4790 }
4791 
providePresetContextMenu(const QPoint & position)4792 void Widget::providePresetContextMenu(const QPoint &position)     /*** Call tree items menu  ***/
4793 {
4794     QTreeWidgetItem *item = ui->treeWidget->itemAt(position);
4795     if (item != nullptr) {
4796         QTreeWidgetItem *parentItem = item->parent();
4797         if (parentItem != nullptr) {
4798             presetMenu->exec(ui->treeWidget->mapToGlobal(QPoint(position.x(), position.y() + 35)));
4799         } else {
4800             sectionMenu->exec(ui->treeWidget->mapToGlobal(QPoint(position.x(), position.y() + 35)));
4801         }
4802     }
4803 }
4804 
4805 /************************************************
4806 ** Dialogs Windows
4807 ************************************************/
4808 
call_dialog(const QString & _message)4809 bool Widget::call_dialog(const QString &_message)  /*** Call dialog ***/
4810 {
4811     Dialog dialog(this);
4812     dialog.setMessage(_message);
4813     dialog.setModal(true);
4814     if (dialog.exec() == QDialog::Accepted) {
4815         return true;
4816     }
4817     return false;
4818 }
4819 
call_task_complete(const QString & _message,const bool & _timer_mode)4820 void Widget::call_task_complete(const QString &_message, const bool &_timer_mode)  /*** Call task complete ***/
4821 {
4822     if (this->isHidden()) {
4823         if (_hideInTrayFlag && !_timer_mode) {
4824             trayIcon->showMessage(_message, tr("Task"), QSystemTrayIcon::Information, 151000);
4825         }
4826         else if (_timer_mode) {
4827             this->show();
4828             Taskcomplete taskcomplete(this);
4829             taskcomplete.setMessage(_message, _timer_mode);
4830             taskcomplete.setModal(true);
4831             taskcomplete.exec();
4832         }
4833     } else {
4834         Taskcomplete taskcomplete(this);
4835         taskcomplete.setMessage(_message, _timer_mode);
4836         taskcomplete.setModal(true);
4837         taskcomplete.exec();
4838     }
4839 }
4840