Debian Codegraph @

src/dvbcut.cpp

raw
1 /* dvbcut
2 Copyright (c) 2005 Sven Over <[email protected]>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 /* $Id$ */
20
21 #include <unistd.h>
22
23 #include <cstring>
24 #include <cerrno>
25 #include <cmath>
26 #include <cstdlib>
27 #include <climits>
28 #include <memory>
29 #include <algorithm>
30
31 #include <qlabel.h>
32 #include <qpixmap.h>
33 #include <qimage.h>
34 #include <qcolor.h>
35 #include <qfiledialog.h>
36 #include <qmessagebox.h>
37 #include <qslider.h>
38 #include <qapplication.h>
39 #include <qstring.h>
40 #include <qlineedit.h>
41 #include <qprocess.h>
42 #include <qpushbutton.h>
43 #include <qaction.h>
44 #include <qtextbrowser.h>
45 #include <qfile.h>
46 #include <qdom.h>
47 #include <qcursor.h>
48 #include <qcombobox.h>
49 #include <qmenubar.h>
50 #include <qsettings.h>
51 #include <qregexp.h>
52 #include <qstatusbar.h>
53 #include <QProxyStyle>
54 #include <QTextCodec>
55 #include <QTextStream>
56 #include <QWheelEvent>
57
58 #include "port.h"
59 #include "dvbcut.h"
60 #include "mpgfile.h"
61 #include "avframe.h"
62 #include "eventlistitem.h"
63 #include "mplayererrorbase.h"
64 #include "lavfmuxer.h"
65 #include "mpegmuxer.h"
66 #include "progresswindow.h"
67 #include "imageprovider.h"
68 #include "differenceimageprovider.h"
69 #include "busyindicator.h"
70 #include "progressstatusbar.h"
71 #include "exportdialog.h"
72 #include "settings.h"
73 #include "exception.h"
74
75 #define DVBCUT_LOADFILTER \
76 QT_TRANSLATE_NOOP("dvbcut", "Recognized files (*.dvbcut *.m2t *.mpg *.rec* *.ts *.tts* *.trp *.vdr);;" \
77 "dvbcut project files (*.dvbcut);;" \
78 "MPEG files (*.m2t *.mpg *.rec* *.ts *.tts* *.trp *.vdr);;" \
79 "All files (*)")
80 #define DVBCUT_IDXFILTER \
81 QT_TRANSLATE_NOOP("dvbcut", "dvbcut index files (*.idx);;All files (*)")
82 #define DVBCUT_PRJFILTER \
83 QT_TRANSLATE_NOOP("dvbcut", "dvbcut project files (*.dvbcut);;All files (*)")
84
85 bool dvbcut::cache_friendly = true;
86
87 // **************************************************************************
88 // *** busy cursor helpers
89
90 class dvbcutbusy : public busyindicator
91 {
92 protected:
93 dvbcut *d;
94 int bsy;
95 public:
96 dvbcutbusy(dvbcut *_d) : busyindicator(), d(_d), bsy(0)
97 {}
98 ~dvbcutbusy()
99 {
100 while (bsy>0)
101 setbusy(false);
102 while (bsy<0)
103 setbusy(true);
104 }
105 virtual void setbusy(bool busy=true)
106 {
107 if (busy)
108 ++bsy;
109 else {
110 if (bsy<=0)
111 return;
112 --bsy;
113 }
114 d->setbusy(busy);
115 }
116 };
117
118 void dvbcut::setbusy(bool b)
119 {
120 if (b) {
121 if (busy==0)
122 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
123 ++busy;
124 } else if (busy>0) {
125 --busy;
126 if (busy==0)
127 QApplication::restoreOverrideCursor();
128 }
129 }
130
131 class SliderStyleAbsolute : public QProxyStyle {
132 public:
133 virtual int styleHint ( StyleHint hint, const QStyleOption * option = 0, const QWidget * widget = 0, QStyleHintReturn * returnData = 0 ) const{
134 if (hint == QStyle::SH_Slider_AbsoluteSetButtons){
135 return Qt::LeftButton;
136 }else{
137 return QProxyStyle::styleHint(hint, option, widget, returnData);
138 }
139 }
140 };
141
142 static QString get_resource(QString file)
143 {
144 QFileInfo appDir(qApp->applicationDirPath());
145
146 // first search in the directory containing dvbcut
147 QString resFile = appDir.absoluteFilePath() + file;
148
149 #ifndef __WIN32__
150 // Unix/Linux: search in the associated share subdirectory
151 if (!QFile::exists(resFile)) {
152 resFile = appDir.absolutePath() + "/share/dvbcut" + file;
153 }
154 #endif
155
156 return resFile;
157 }
158
159 // **************************************************************************
160 // *** dvbcut::dvbcut (private constructor)
161
162 dvbcut::dvbcut()
163 :QMainWindow(),
164 audiotrackpopup(0), recentfilespopup(0), editconvertpopup(0), audiotrackmenu(0),
165 buf(8 << 20, 128 << 20),
166 mpg(0), pictures(0),
167 curpic(~0), showimage(true), fine(false),
168 jogsliding(false), jogmiddlepic(0),
169 mplayer_process(0), imgp(0), busy(0),
170 viewscalefactor(1.0),
171 nogui(false)
172 {
173 ui = new Ui::dvbcutbase();
174 ui->setupUi(this);
175 #ifndef HAVE_LIB_AO
176 ui->playAudio1Action->setEnabled(false);
177 ui->playAudio2Action->setEnabled(false);
178 ui->playToolbar->removeAction(ui->playAudio1Action);
179 ui->playToolbar->removeAction(ui->playAudio2Action);
180 ui->playMenu->removeAction(ui->playAudio1Action);
181 ui->playMenu->removeAction(ui->playAudio2Action);
182 #endif // ! HAVE_LIB_AO
183
184 audiotrackpopup=new QMenu(tr("Audio track"), this);
185 ui->playMenu->addSeparator();
186 audiotrackmenu=ui->playMenu->addMenu(audiotrackpopup);
187 connect( audiotrackpopup, SIGNAL( triggered(QAction*) ), this, SLOT( audiotrackchosen(QAction*) ) );
188
189 recentfilespopup=new QMenu(tr("Open &recent..."), this);
190 ui->fileMenu->insertMenu(ui->fileSaveAction, recentfilespopup);
191 connect( recentfilespopup, SIGNAL( triggered(QAction*) ), this, SLOT( loadrecentfile(QAction*) ) );
192 connect( recentfilespopup, SIGNAL( aboutToShow() ), this, SLOT( abouttoshowrecentfiles() ) );
193
194 editconvertpopup=new QMenu(tr("Convert bookmarks"), this);
195 ui->editMenu->insertMenu(ui->editBookmarkAction, editconvertpopup);
196 connect( editconvertpopup, SIGNAL( triggered(QAction*) ), this, SLOT( editConvert(QAction*) ) );
197 connect( editconvertpopup, SIGNAL( aboutToShow() ), this, SLOT( abouttoshoweditconvert() ) );
198
199 ui->fileOpenAction->setIcon(QIcon::fromTheme("document-open", this->style()->standardIcon(QStyle::SP_DialogOpenButton)));
200 ui->fileSaveAction->setIcon(QIcon::fromTheme("document-save", this->style()->standardIcon(QStyle::SP_DialogSaveButton)));
201 ui->fileSaveAsAction->setIcon(QIcon::fromTheme("document-save-as", this->style()->standardIcon(QStyle::SP_DriveFDIcon)));
202 ui->snapshotSaveAction->setIcon(QIcon::fromTheme("camera-photo", this->style()->standardIcon(QStyle::SP_DesktopIcon)));
203 ui->playPlayAction->setIcon(QIcon::fromTheme("media-playback-start", this->style()->standardIcon(QStyle::SP_MediaPlay)));
204 ui->playStopAction->setIcon(QIcon::fromTheme("media-playback-pause", this->style()->standardIcon(QStyle::SP_MediaPause)));
205 ui->playAudio1Action->setIcon(QIcon::fromTheme("media-seek-backward", this->style()->standardIcon(QStyle::SP_MediaSeekBackward)));
206 ui->playAudio2Action->setIcon(QIcon::fromTheme("media-seek-forward", this->style()->standardIcon(QStyle::SP_MediaSeekForward)));
207
208 setviewscalefactor(settings().viewscalefactor);
209
210 // install event handler
211 ui->linslider->installEventFilter(this);
212 ui->linslider->setStyle(new SliderStyleAbsolute);
213
214 // set caption
215 setWindowTitle(QString(VERSION_STRING));
216 setWindowIcon(QIcon(get_resource("/icons/dvbcut.svg")));
217 }
218
219 // **************************************************************************
220 // *** dvbcut::~dvbcut (destructor)
221
222 dvbcut::~dvbcut()
223 {
224 if (mplayer_process) {
225 mplayer_process->terminate();
226 delete mplayer_process;
227 }
228
229 if (audiotrackpopup)
230 delete audiotrackpopup;
231 if (recentfilespopup)
232 delete recentfilespopup;
233 if (editconvertpopup)
234 delete editconvertpopup;
235
236 if (imgp)
237 delete imgp;
238 if (mpg)
239 delete mpg;
240 if(ui)
241 delete ui;
242 }
243
244 // **************************************************************************
245 // *** slots (actions)
246
247 void dvbcut::fileNew()
248 {
249 dvbcut *d = new dvbcut;
250 d->show();
251 }
252
253 void dvbcut::fileOpen()
254 {
255 open();
256 }
257
258 void dvbcut::fileSaveAs()
259 {
260 if (prjfilen.empty() && !mpgfilen.empty() && !mpgfilen.front().empty()) {
261 std::string prefix = mpgfilen.front();
262 int lastdot = prefix.rfind(".");
263 int lastslash = prefix.rfind("/");
264 if (lastdot >= 0 && lastdot > lastslash)
265 prefix = prefix.substr(0, lastdot);
266 prjfilen = prefix + ".dvbcut";
267 int nr = 0;
268 while (QFileInfo(QString::fromStdString(prjfilen)).exists())
269 prjfilen = prefix + "_" + QString::number(++nr).toStdString() + ".dvbcut";
270 }
271
272 QString s=QFileDialog::getSaveFileName(
273 this,
274 tr("Choose the name of the project file"),
275 QString::fromStdString(prjfilen),
276 tr(DVBCUT_PRJFILTER) );
277
278 if (s.isNull())
279 return;
280
281 if (QFileInfo(s).exists() && question(
282 tr("File exists - dvbcut"),
283 tr("%1\nalready exists. Overwrite?").arg(s)) !=
284 QMessageBox::Yes)
285 return;
286
287 prjfilen = s.toStdString();
288 if (!prjfilen.empty())
289 fileSave();
290 }
291
292 void dvbcut::fileSave()
293 {
294 if (prjfilen.empty()) {
295 fileSaveAs();
296 return;
297 }
298
299 std::list<std::string> dummy_list;
300 dummy_list.push_back(prjfilen);
301 addtorecentfiles(dummy_list);
302
303 QFile outfile(QString::fromStdString(prjfilen));
304 if (!outfile.open(QIODevice::WriteOnly)) {
305 critical(tr("Failed to write project file - dvbcut"),
306 //: Placeholder will be replaced with filename
307 tr("%1:\nCould not open file").arg(QString::fromStdString(prjfilen)));
308 return;
309 }
310
311 QDomDocument doc("dvbcut");
312 QDomElement root = doc.createElement("dvbcut");
313 #if 0
314 root.setAttribute("mpgfile",mpgfilen.front());
315 if (!idxfilen.empty())
316 root.setAttribute("idxfile",idxfilen);
317 #endif
318 doc.appendChild(root);
319
320 std::list<std::string>::const_iterator it = mpgfilen.begin();
321 while (it != mpgfilen.end()) {
322 QDomElement elem = doc.createElement("mpgfile");
323 elem.setAttribute("path", QString::fromStdString(*it));
324 root.appendChild(elem);
325 ++it;
326 }
327
328 if (!idxfilen.empty()) {
329 QDomElement elem = doc.createElement("idxfile");
330 elem.setAttribute("path", QString::fromStdString(idxfilen));
331 root.appendChild(elem);
332 }
333
334 int index;
335 for (index = 0; index < ui->eventlist->count(); index++)
336 {
337 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
338 if (eli) {
339 QString elemname;
340 EventListItem::eventtype evt=eli->geteventtype();
341
342 if (evt==EventListItem::start)
343 elemname="start";
344 else if (evt==EventListItem::stop)
345 elemname="stop";
346 else if (evt==EventListItem::chapter)
347 elemname="chapter";
348 else if (evt==EventListItem::bookmark)
349 elemname="bookmark";
350 else
351 continue;
352
353 QDomElement elem=doc.createElement(elemname);
354 elem.setAttribute("picture",eli->getpicture());
355 root.appendChild(elem);
356 }
357 }
358
359 QTextStream stream(&outfile);
360 stream.setCodec(QTextCodec::codecForName("ISO-8859-1"));
361 stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
362 stream << doc.toString().toStdString().c_str();
363 outfile.close();
364 }
365
366 void dvbcut::snapshotSave()
367 {
368 std::vector<int> piclist;
369 piclist.push_back(curpic);
370
371 snapshotSave(piclist);
372 }
373
374 void dvbcut::chapterSnapshotsSave()
375 {
376 int found=0;
377 std::vector<int> piclist;
378 int index;
379 for (index = 0; index < ui->eventlist->count(); index++)
380 {
381 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
382 if (eli) {
383 if (eli->geteventtype()==EventListItem::chapter) {
384 piclist.push_back(eli->getpicture());
385 found++;
386 }
387 }
388 }
389
390 if (found) {
391 snapshotSave(piclist, settings().snapshot_range, settings().snapshot_samples);
392 } else
393 statusBar()->showMessage(QString("*** No chapters to save! ***"));
394 }
395
396 void dvbcut::snapshotSave(std::vector<int> piclist, int range, int samples)
397 {
398 QString prefix;
399 QString type=settings().snapshot_type;
400 QString delim=settings().snapshot_delimiter;
401 QString ext=settings().snapshot_extension;
402 int first = settings().snapshot_first;
403 int width = settings().snapshot_width;
404 int quality = settings().snapshot_quality;
405
406 // get unique filename
407 if (picfilen.isEmpty()) {
408 if(settings().snapshot_prefix.isEmpty()) {
409 if (!prjfilen.empty())
410 prefix = QString::fromStdString(prjfilen);
411 else if (!mpgfilen.empty() && !mpgfilen.front().empty())
412 prefix = QString::fromStdString(mpgfilen.front());
413 } else
414 prefix = settings().snapshot_prefix;
415
416 if (!prefix.isEmpty()) {
417 int lastdot = prefix.lastIndexOf('.');
418 int lastslash = prefix.lastIndexOf('/');
419 if (lastdot >= 0 && lastdot > lastslash)
420 prefix = prefix.left(lastdot);
421 int nr = first;
422 picfilen = prefix + delim + QString::number(nr).rightJustified( width, '0' ) + "." + ext;
423 while (QFileInfo(picfilen).exists())
424 picfilen = prefix + delim + QString::number(++nr).rightJustified( width, '0' )+ "." + ext;
425 }
426 }
427
428 QString s = QFileDialog::getSaveFileName(
429 this,
430 tr("Choose the name of the picture file"),
431 picfilen,
432 //: Placeholder will be replaced with file extension
433 tr("Images (*.%1)").arg(ext) );
434
435 if (s.isEmpty())
436 return;
437
438 if (QFileInfo(s).exists() && question(
439 tr("File exists - dvbcut"),
440 //: Placeholder will be replaced with filename
441 tr("%1\nalready exists. Overwrite?").arg(s)) !=
442 QMessageBox::Yes)
443 return;
444
445 QImage p;
446 int pic, i, nr;
447 bool ok=false;
448 for (std::vector<int>::iterator it = piclist.begin(); it != piclist.end(); ++it) {
449
450 if(samples>1 && range>0)
451 pic = chooseBestPicture(*it, range, samples);
452 else
453 pic = *it+range;
454
455 // save selected picture to file
456 if (imgp)
457 p = imgp->getimage(pic,fine);
458 else
459 p = imageprovider(*mpg, new dvbcutbusy(this), false, viewscalefactor).getimage(pic,fine);
460 if(p.save(s,type.toLatin1(),quality))
461 statusBar()->showMessage("Saved snapshot: " + s);
462 else
463 statusBar()->showMessage("*** Unable to save snapshot: " + s + "! ***");
464
465 // try to "increment" the choosen filename for next snapshot (or use old name as default)
466 // No usage of "delim", so it's possible to choose any prefix in front of the number field!
467 i = s.lastIndexOf(QRegExp("\\d{"+QString::number(width)+","+QString::number(width)+"}\\."+ext+"$"));
468 if (i>0) {
469 nr = s.mid(i,width).toInt(&ok,10);
470 if (ok)
471 picfilen = s.left(i) + QString::number(++nr).rightJustified(width, '0')+ "." + ext;
472 else
473 picfilen = s;
474 }
475 else
476 picfilen = s;
477
478 s = picfilen;
479 }
480
481 }
482
483 int dvbcut::chooseBestPicture(int startpic, int range, int samples)
484 {
485 QImage p;
486 QRgb col;
487 int idx, x, y, w, h, pic, norm, colors;
488 int r, g, b, nr=11, ng=16, nb=5; // "borrowed" the weights from calc. of qGray = (11*r+16*g+5*b)/32
489 double entropy;
490 std::vector<double> histogram;
491
492 samples = samples>0 ? samples: 1;
493 samples = samples>abs(range) ? abs(range)+1: samples;
494
495 int bestpic = startpic+range, bestnr=0;
496 double bestval = 0.;
497 int dp = range/(samples-1);
498 int ncol = nr*ng*nb;
499
500 // choose the best picture among equidistant samples in the range (not for single snapshots!)
501 for (int n=0; n<samples && samples>1 && range>0; n++) {
502 pic = startpic+n*dp;
503
504 if (imgp)
505 p = imgp->getimage(pic,fine);
506 else
507 p = imageprovider(*mpg, new dvbcutbusy(this), false, viewscalefactor).getimage(pic,fine);
508
509 // get a measure for complexity of picture (at least good enough to discard single colored frames!)
510
511 // index color space and fill histogram
512 w = p.width();
513 h = p.height();
514 histogram.assign(ncol,0.);
515 for(x=0; x<w; x++)
516 for(y=0; y<h; y++) {
517 col=p.pixel(x,y);
518 r=nr*qRed(col)/256;
519 g=ng*qGreen(col)/256;
520 b=nb*qBlue(col)/256;
521 idx=r+nr*g+nr*ng*b;
522 histogram[idx]++;
523 }
524
525 // calc. probability to fall in a given color class
526 colors = 0;
527 norm = w*h;
528 for(unsigned int i=0; i<histogram.size(); i++)
529 if(histogram[i]>0) {
530 colors++;
531 histogram[i] /= norm;
532 }
533
534 // calc. the information entropy (complexity) of the picture
535 entropy = 0.;
536 for(x=0; x<w; x++)
537 for(y=0; y<h; y++) {
538 col=p.pixel(x,y);
539 r=nr*qRed(col)/256;
540 g=ng*qGreen(col)/256;
541 b=nb*qBlue(col)/256;
542 idx=r+nr*g+nr*ng*b;
543 entropy-=histogram[idx]*log(histogram[idx]);
544 }
545 entropy /= log(2.);
546
547 //fprintf(stderr,"frame %7d, sample %4d (%7d): %10d %10.2f\n",startpic,n,pic,colors,entropy);
548
549 // largest "information content"?
550 if(entropy>bestval) {
551 bestval=entropy;
552 bestpic=pic;
553 bestnr=n;
554 }
555 }
556 if (0) fprintf(stderr,"choosing sample / frame: %4d / %7d\n!", bestnr, bestpic);
557
558 return bestpic;
559 }
560
561 void dvbcut::fileExport()
562 {
563 if (expfilen.empty()) {
564 std::string newexpfilen;
565
566 if (!prjfilen.empty())
567 newexpfilen=prjfilen;
568 else if (!mpgfilen.empty() && !mpgfilen.front().empty())
569 newexpfilen=mpgfilen.front();
570
571 if (!newexpfilen.empty()) {
572 int lastdot(newexpfilen.rfind("."));
573 int lastslash(newexpfilen.rfind("/"));
574 if (lastdot>=0 && lastslash<lastdot)
575 newexpfilen=newexpfilen.substr(0,lastdot);
576 expfilen=newexpfilen+".mpg";
577 int nr=0;
578 while (QFileInfo(QString::fromStdString(expfilen)).exists())
579 expfilen = newexpfilen + "_" + QString::number(++nr).toStdString() + ".mpg";
580 }
581 }
582
583 std::unique_ptr<exportdialog> expd(new exportdialog(QString::fromStdString(expfilen),this));
584 expd->ui->muxercombo->addItem(tr("MPEG program stream/DVD (DVBCUT multiplexer)"));
585 expd->ui->muxercombo->addItem(tr("MPEG program stream (DVBCUT multiplexer)"));
586 expd->ui->muxercombo->addItem(tr("MPEG program stream/DVD (libavformat)"));
587 expd->ui->muxercombo->addItem(tr("MPEG transport stream (libavformat)"));
588 #ifndef __WIN32__
589 // add possible user configured pipe commands
590 int pipe_items_start=expd->ui->muxercombo->count();
591 for (unsigned int i = 0; i < settings().pipe_command.size(); ++i)
592 expd->ui->muxercombo->addItem(settings().pipe_label[i]);
593 #endif
594
595 if (settings().export_format < 0
596 || settings().export_format >= expd->ui->muxercombo->count())
597 settings().export_format = 0;
598 expd->ui->muxercombo->setCurrentIndex(settings().export_format);
599
600 for(int a=0;a<mpg->getaudiostreams();++a) {
601 expd->ui->audiolist->addItem(mpg->getstreaminfo(audiostream(a)).c_str());
602 }
603 expd->ui->audiolist->selectAll();
604
605 int expfmt = 0;
606 if (!nogui) {
607 expd->show();
608 if (!expd->exec())
609 return;
610
611 settings().export_format = expd->ui->muxercombo->currentIndex();
612 expfmt = expd->ui->muxercombo->currentIndex();
613
614 expfilen = expd->ui->filenameline->text().toStdString();
615 if (expfilen.empty())
616 return;
617 expd->hide();
618 } else if (exportformat > 0 && exportformat < expd->ui->muxercombo->count())
619 expfmt = exportformat;
620
621 // create usable chapter lists
622 std::string chapterstring, chaptercolumn;
623 if (!chapterlist.empty()) {
624 int nchar=0;
625 char chapter[16];
626 pts_t lastch=-1;
627 for(std::list<pts_t>::const_iterator it=chapterlist.begin();
628 it!=chapterlist.end();++it)
629 if (*it != lastch) {
630 lastch=*it;
631 // formatting the chapter string
632 if (nchar>0) {
633 nchar++;
634 chapterstring+=",";
635 chaptercolumn+="\n";
636 }
637 nchar+=sprintf(chapter,"%02d:%02d:%02d.%03d",
638 int(lastch/(3600*90000)),
639 int(lastch/(60*90000))%60,
640 int(lastch/90000)%60,
641 int(lastch/90)%1000 );
642 // append chapter marks to lists for plain text / dvdauthor xml-file
643 chapterstring+=chapter;
644 chaptercolumn+=chapter;
645 }
646 }
647
648 int child_pid = -1;
649 int pipe_fds[2];
650
651 #ifndef __WIN32__
652 // check for piped output
653 std::string expcmd;
654 size_t pos;
655 int ip=expfmt-pipe_items_start;
656 if(ip>=0) {
657 expfmt=settings().pipe_format[ip];
658 if (settings().pipe_command[ip].indexOf('|') == -1)
659 expcmd = "|" + settings().pipe_command[ip].toStdString();
660 else
661 expcmd = settings().pipe_command[ip].toStdString();
662
663 if ((pos=expcmd.find("%OUTPUT%"))!=std::string::npos)
664 expcmd.replace(pos,8,expfilen);
665 } else
666 expcmd = expfilen;
667
668 // chapter tag can also be used with input field pipes!
669 if ((pos=expcmd.find("%CHAPTERS%"))!=std::string::npos)
670 expcmd.replace(pos,10,chapterstring);
671
672 if ((pos=expcmd.find('|'))!=std::string::npos) {
673 pos++;
674 size_t end=expcmd.find(' ',pos);
675 //if (!QFileInfo(expcmd.substr(pos,end-pos)).exists() ||
676 // !QFileInfo(expcmd.substr(pos,end-pos)).isExecutable()) {
677 // better test if command is found in $PATH, so one don't needs to give the full path name
678 std::string which="which "+expcmd.substr(pos,end-pos)+" >/dev/null";
679 int irc = system(which.c_str());
680 if(irc!=0) {
681 critical(tr("Command not found - dvbcut"),
682 //: Placeholder will be replaced with pipe command
683 tr("Problems with piped output to:\n%1").arg(QString::fromStdString(expcmd.substr(pos,end-pos))));
684 return;
685 }
686
687 if (::pipe(pipe_fds) < 0)
688 return;
689 child_pid = fork();
690 if (child_pid == 0) {
691 ::close(pipe_fds[1]);
692 if (pipe_fds[0] != STDIN_FILENO) {
693 dup2(pipe_fds[0], STDIN_FILENO);
694 }
695 //fprintf(stderr, "Executing %s\n", expcmd.c_str()+pos);
696 for (int fd=0; fd<256; ++fd)
697 if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
698 ::close(fd);
699 execl("/bin/sh", "sh", "-c", expcmd.c_str()+pos, (char *)0);
700 _exit(127);
701 }
702 ::close(pipe_fds[0]);
703 if (child_pid < 0) {
704 ::close(pipe_fds[1]);
705 return;
706 }
707 } else
708 #endif
709 if (QFileInfo(QString::fromStdString(expfilen)).exists() && question(
710 tr("File exists - dvbcut"),
711 tr("%1\nalready exists. Overwrite?").arg(QString::fromStdString(expfilen))) !=
712 QMessageBox::Yes)
713 return;
714
715 progresswindow *prgwin = 0;
716 logoutput *log;
717 if (nogui) {
718 log = new logoutput;
719 }
720 else {
721 prgwin = new progresswindow(this);
722 prgwin->setWindowTitle(QString("export - " + QString::fromStdString(expfilen)));
723 log = prgwin;
724 }
725
726 // lavfmuxer mux(fmt,*mpg,outfilename);
727
728 std::unique_ptr<muxer> mux;
729 uint32_t audiostreammask(0);
730
731 for(int a=0;a<mpg->getaudiostreams();++a)
732 if (expd->ui->audiolist->item(a)->isSelected())
733 audiostreammask|=1u<<a;
734
735 std::string out_file = (child_pid < 0) ? expfilen :
736 std::string("pipe:") + QString::number(pipe_fds[1]).toStdString();
737
738 switch(expfmt) {
739 case 1:
740 mux = std::unique_ptr<muxer>(new mpegmuxer(audiostreammask,*mpg,out_file.c_str(),false,0));
741 break;
742 case 2:
743 mux = std::unique_ptr<muxer>(new lavfmuxer("dvd",audiostreammask,*mpg,out_file.c_str()));
744 break;
745 case 3:
746 mux = std::unique_ptr<muxer>(new lavfmuxer("mpegts",audiostreammask,*mpg,out_file.c_str()));
747 break;
748 case 0:
749 default:
750 mux = std::unique_ptr<muxer>(new mpegmuxer(audiostreammask,*mpg,out_file.c_str()));
751 break;
752 }
753
754 if (!mux->ready()) {
755 #ifndef __WIN32__
756 if (child_pid > 0) {
757 ::close(pipe_fds[1]);
758 int wstatus;
759 while (waitpid(child_pid, &wstatus, 0)==-1 && errno==EINTR);
760 }
761 #endif
762 log->printerror(tr("Unable to set up muxer!"));
763 if (nogui)
764 delete log;
765 else {
766 prgwin->finish();
767 delete prgwin;
768 }
769 return;
770 }
771
772 // starting export, switch source to sequential mode
773 buf.setsequential(cache_friendly);
774
775 int startpic, stoppic, savedpic=0;
776 pts_t startpts=(*mpg)[0].getpts(), stoppts, savedtime=0;
777
778 for(unsigned int num=0; num<quick_picture_lookup.size(); num++) {
779 startpic=quick_picture_lookup[num].startpicture;
780 startpts=quick_picture_lookup[num].startpts;
781 stoppic=quick_picture_lookup[num].stoppicture;
782 stoppts=quick_picture_lookup[num].stoppts;
783
784 //: Example: 1. Exporting 600 pictures: 00:05:45.240/00 .. 00:06:09.240/00
785 log->printheading(tr("%1. Exporting %n pictures: %2 .. %3", "", stoppic-startpic)
786 .arg(num+1).arg(ptsstring(startpts).c_str(),ptsstring(stoppts).c_str()));
787 mpg->savempg(*mux,startpic,stoppic,savedpic,quick_picture_lookup.back().outpicture,log);
788
789 savedpic=quick_picture_lookup[num].outpicture;
790 savedtime=quick_picture_lookup[num].outpts;
791 }
792
793 mux.reset();
794
795 //: Example: Saved 3627 pictures (00:02:25.80)
796 log->printheading(tr("Saved %n pictures (%1:%2:%3.%4)", "", savedpic)
797 .arg(int(savedtime/(3600*90000)), 2, 10, QChar('0'))
798 .arg(int(savedtime/(60*90000))%60, 2, 10, QChar('0'))
799 .arg(int(savedtime/90000)%60, 2, 10, QChar('0'))
800 .arg(int(savedtime/90)%1000, 2, 10, QChar('0')));
801
802 #ifndef __WIN32__
803 if (child_pid > 0) {
804 ::close(pipe_fds[1]);
805 int wstatus;
806 while (waitpid(child_pid, &wstatus, 0)==-1 && errno==EINTR);
807 }
808
809 // do some post processing if requested
810 if (ip>=0 && !settings().pipe_post[ip].isEmpty()) {
811 expcmd = settings().pipe_post[ip].toStdString();
812
813 if ((pos=expcmd.find("%OUTPUT%"))!=std::string::npos)
814 expcmd.replace(pos,8,expfilen);
815 if ((pos=expcmd.find("%CHAPTERS%"))!=std::string::npos)
816 expcmd.replace(pos,10,chapterstring);
817
818 pos=expcmd.find(' ');
819 std::string which="which "+expcmd.substr(0,pos)+" >/dev/null";
820
821 log->print("");
822 log->printheading(tr("Performing post processing"));
823 int irc = system(which.c_str());
824
825 if(irc!=0) {
826 critical(tr("Command not found - dvbcut"),
827 //: Placeholder will be replaced with pipe command
828 tr("Problems with post processing command:\n%1").arg(QString::fromStdString(expcmd.substr(0,pos))));
829 log->print(tr("Command not found!"));
830 } else {
831 int irc = system(expcmd.c_str());
832 if(irc!=0) {
833 critical(tr("Post processing error - dvbcut"),
834 //: %1 will be replaced with exit code, %2 with pipe command
835 tr("Post processing command:\n%2\n returned non-zero exit code: %1").arg(irc).arg(QString::fromStdString(expcmd)));
836 log->print(tr("Command reported some problems... please check!"));
837 }
838 //else
839 // log->print("Everything seems to be OK...");
840 }
841 }
842 #endif
843
844 // print plain list of chapter marks
845 log->print("");
846 log->printheading(tr("Chapter list"));
847 log->print(chaptercolumn.c_str());
848
849 // simple dvdauthor xml file with chapter marks
850 std::string filename,destname;
851 if (expfilen.rfind("/")<expfilen.length())
852 filename=expfilen.substr(expfilen.rfind("/")+1);
853 else
854 filename=expfilen;
855 destname=filename.substr(0,filename.rfind("."));
856 log->print("");
857 log->printheading(tr("Simple XML-file for dvdauthor with chapter marks"));
858 log->print("<dvdauthor dest=\"" + QString::fromStdString(destname) + "\">");
859 log->print(" <vmgm />");
860 log->print(" <titleset>");
861 log->print(" <titles>");
862 log->print(" <pgc>");
863 log->print(" <vob file=\"" + QString::fromStdString(filename) + "\" chapters=\"" + QString::fromStdString(chapterstring) + "\" />");
864 log->print(" </pgc>");
865 log->print(" </titles>");
866 log->print(" </titleset>");
867 log->print("</dvdauthor>");
868
869 if (nogui)
870 delete log;
871 else {
872 prgwin->finish();
873 delete prgwin;
874 }
875
876 // done exporting, switch back to random mode
877 buf.setsequential(false);
878 }
879
880 void dvbcut::fileClose()
881 {
882 close();
883 }
884
885 void dvbcut::addEventListItem(int pic, EventListItem::eventtype type)
886 {
887 //check if requested EventListItem is already in list to avoid doubles!
888 int index;
889 for (index = 0; index < ui->eventlist->count(); index++)
890 {
891 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
892 if (eli) {
893 if (pic==eli->getpicture() && type==eli->geteventtype())
894 return;
895 }
896 }
897
898 QPixmap p;
899 if (imgp && imgp->rtti() == IMAGEPROVIDER_STANDARD)
900 p = QPixmap::fromImage(imgp->getimage(pic));
901 else
902 p = QPixmap::fromImage(imageprovider(*mpg, new dvbcutbusy(this), false, 4).getimage(pic));
903
904 new EventListItem(ui->eventlist, p, type, pic, (*mpg)[pic].getpicturetype(),
905 (*mpg)[pic].getpts() - firstpts);
906 }
907
908 void dvbcut::editBookmark()
909 {
910 addEventListItem(curpic, EventListItem::bookmark);
911 }
912
913
914 void dvbcut::editChapter()
915 {
916 addEventListItem(curpic, EventListItem::chapter);
917 update_quick_picture_lookup_table();
918 }
919
920
921 void dvbcut::editStop()
922 {
923 addEventListItem(curpic, EventListItem::stop);
924 update_quick_picture_lookup_table();
925 }
926
927
928 void dvbcut::editStart()
929 {
930 addEventListItem(curpic, EventListItem::start);
931 update_quick_picture_lookup_table();
932 }
933
934 void dvbcut::editAutoChapters()
935 {
936 int inpic, chapters = 0;
937 quick_picture_lookup_t::iterator it;
938 QImage p1, p2;
939
940 // the first chapter at 0sec is ALWAYS set by default from update_quick_picture_lookup_table()
941 int chapter_start;
942 if(settings().chapter_interval>0) {
943 chapter_start = settings().chapter_interval; // fixed length of intervals
944 } else {
945 chapter_start = quick_picture_lookup.back().outpicture/(1-settings().chapter_interval); // given number of chapters
946 chapter_start = chapter_start > settings().chapter_minimum ? chapter_start : settings().chapter_minimum;
947 }
948 // don't make a new chapter if it would be shorter than the specified minimal length
949 int chapter_max = quick_picture_lookup.back().outpicture - settings().chapter_minimum;
950
951 for(int outpic = chapter_start; outpic < chapter_max; outpic+=chapter_start)
952 if (!quick_picture_lookup.empty()) {
953 // find the entry in the quick_picture_lookup table that corresponds to given output picture
954 it = std::upper_bound(quick_picture_lookup.begin(),quick_picture_lookup.end(),outpic,quick_picture_lookup_s::cmp_outpicture());
955 inpic = outpic - it->outpicture + it->stoppicture;
956
957 if(inpic+settings().chapter_tolerance>it->stoppicture) {
958 if(it == quick_picture_lookup.end()) break;
959 // take begin of next START/STOP range as chapter picture if to near at end of current range
960 it++;
961 inpic=it->startpicture;
962 } else if(settings().chapter_tolerance>0) {
963 // look for the next scene change inside specified frame tolerance (VERY SLOW!!!)
964 if (!imgp)
965 imgp = new imageprovider(*mpg, new dvbcutbusy(this), false, viewscalefactor, settings().chapter_tolerance);
966 p2 = imgp->getimage(inpic,fine);
967 for(int pic=inpic+1; pic<inpic+settings().chapter_tolerance && pic<pictures; pic++) {
968 // get next picture
969 p1 = p2;
970 p2 = imgp->getimage(pic,fine);
971 if (p2.size()!=p1.size())
972 p2=p2.scaled(p1.size());
973
974 // calculate color distance between two consecutive frames
975 double dist=0.;
976 if (p2.depth()==32 && p1.depth()==32)
977 for (int y=0;y<p1.height();++y) {
978 QRgb *col1=(QRgb*)p1.scanLine(y);
979 QRgb *col2=(QRgb*)p2.scanLine(y);
980
981 for (int x=p1.width();x>0;--x) {
982 dist+=sqrt(pow(qRed(*col1)-qRed(*col2),2)+pow(qGreen(*col1)-qGreen(*col2),2)+pow(qBlue(*col1)-qBlue(*col2),2));
983 // that's a bit faster...
984 //dist+=(abs(qRed(*col1)-qRed(*col2))+abs(qGreen(*col1)-qGreen(*col2))+abs(qBlue(*col1)-qBlue(*col2)));
985 ++col1;
986 ++col2;
987 }
988 }
989 dist/=(p1.height()*p1.width());
990
991 // 50. seems to be a good measure for the color distance at scene changes (about sqrt(3)*50. if sum of abs values)!
992 //fprintf(stderr,"%d, DIST=%f\n",pic,dist);
993 if(dist>settings().chapter_threshold) {
994 inpic=pic;
995 statusBar()->showMessage(QString().asprintf("%d. Scene change @ %d, DIST=%f\n",chapters+1,inpic,dist));
996 break;
997 }
998 }
999 }
1000
1001 addEventListItem(inpic, EventListItem::chapter);
1002 chapters++;
1003 }
1004
1005 if (chapters)
1006 update_quick_picture_lookup_table();
1007
1008 }
1009
1010 void dvbcut::editSuggest()
1011 {
1012 int pic = 0, found=0;
1013 while ((pic = mpg->nextaspectdiscontinuity(pic)) >= 0) {
1014 addEventListItem(pic, EventListItem::bookmark);
1015 found++;
1016 }
1017 if (!found)
1018 statusBar()->showMessage(QString("*** No aspect ratio changes detected! ***"));
1019 }
1020
1021 void dvbcut::editImport()
1022 {
1023 int found=0;
1024 std::vector<int> bookmarks = mpg->getbookmarks();
1025 for (std::vector<int>::iterator b = bookmarks.begin(); b != bookmarks.end(); ++b) {
1026 addEventListItem(*b, EventListItem::bookmark);
1027 found++;
1028 }
1029 if (!found)
1030 statusBar()->showMessage(QString("*** No valid bookmarks available/found! ***"));
1031 }
1032
1033 void dvbcut::abouttoshoweditconvert()
1034 {
1035 editconvertpopup->clear();
1036 editconvertpopup->addAction(tr("START / STOP"))->setData(act_start_stop);
1037 editconvertpopup->addAction(tr("STOP / START"))->setData(act_stop_start);
1038 editconvertpopup->addAction(tr("4 : 3"))->setData(act_4_3);
1039 editconvertpopup->addAction(tr("16 : 9"))->setData(act_16_9);
1040 }
1041
1042 void dvbcut::editConvert(QAction *a)
1043 {
1044 int option = a->data().toInt();
1045 if (option < act_start_stop || option > act_16_9)
1046 return;
1047 editConvert((editconvertpop_actions)option);
1048 }
1049
1050 void dvbcut::editConvert(editconvertpop_actions option)
1051 {
1052 // convert Bookmarks to START/STOP markers
1053 int found=0;
1054 std::vector<int> cutlist;
1055 int index;
1056 for (index = 0; index < ui->eventlist->count(); index++)
1057 {
1058 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
1059 if (eli) {
1060 if (eli->geteventtype()==EventListItem::bookmark) {
1061 cutlist.push_back(eli->getpicture());
1062 delete eli;
1063 found++;
1064 }
1065 }
1066 }
1067 if (found) {
1068 addStartStopItems(cutlist, option);
1069
1070 if (found%2)
1071 statusBar()->showMessage(QString("*** No matching stop marker!!! ***"));
1072 }
1073 else
1074 statusBar()->showMessage(QString("*** No bookmarks to convert! ***"));
1075 }
1076
1077 void dvbcut::addStartStopItems(std::vector<int> cutlist, int option)
1078 {
1079 // take list of frame numbers and set alternating START/STOP markers
1080 bool alternate=true;
1081 EventListItem::eventtype type=EventListItem::start;
1082 if (option == act_stop_start)
1083 type=EventListItem::stop;
1084 else if (option == act_4_3 || option == act_16_9)
1085 alternate=false;
1086
1087 // make sure list is sorted...
1088 std::sort(cutlist.begin(),cutlist.end());
1089
1090 // ...AND there are no old START/STOP pairs!!!
1091 int index;
1092 for (index = 0; index < ui->eventlist->count(); index++)
1093 {
1094 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
1095 if (eli) {
1096 if (eli->geteventtype()==EventListItem::start || eli->geteventtype()==EventListItem::stop)
1097 delete eli;
1098 }
1099 }
1100
1101 for (std::vector<int>::iterator it = cutlist.begin(); it != cutlist.end(); ++it) {
1102 if(!alternate) {
1103 // set START/STOP according aspect ratio (2=4:3, 3=16:9)
1104 if (option == (*mpg)[*it].getaspectratio())
1105 type=EventListItem::start;
1106 else
1107 type=EventListItem::stop;
1108 }
1109
1110 addEventListItem(*it, type);
1111
1112 if(alternate) {
1113 // set START/STOP alternatingly
1114 if(type==EventListItem::start)
1115 type=EventListItem::stop;
1116 else
1117 type=EventListItem::start;
1118 }
1119 }
1120
1121 update_quick_picture_lookup_table();
1122 }
1123
1124 void dvbcut::viewDifference()
1125 {
1126 ui->viewNormalAction->setChecked(false);
1127 ui->viewUnscaledAction->setChecked(false);
1128 ui->viewDifferenceAction->setChecked(true);
1129
1130 if (imgp)
1131 delete imgp;
1132 imgp=new differenceimageprovider(*mpg,curpic, new dvbcutbusy(this), false, viewscalefactor);
1133 updateimagedisplay();
1134 }
1135
1136 inline int square(int x)
1137 {
1138 return x * x;
1139 }
1140
1141 unsigned long calc_distance(QImage baseimg, QImage im)
1142 {
1143 if (im.size() != baseimg.size())
1144 im = im.scaled(baseimg.size());
1145
1146 unsigned long distance = 0;
1147 if (im.depth() == 32 && baseimg.depth() == 32) {
1148 for (int y = 0; y < baseimg.height(); ++y) {
1149 QRgb *imd = (QRgb*) im.scanLine(y);
1150 QRgb *bimd = (QRgb*) baseimg.scanLine(y);
1151
1152 for (int x = im.width(); x > 0; --x) {
1153 int dist = square(qRed(*imd) - qRed(*bimd)) + square(qGreen(*imd) - qGreen(*bimd)) + square(qBlue(*imd) - qBlue(*bimd));
1154 if (dist > 1000)
1155 dist = 1000;
1156
1157 distance += dist;
1158 ++imd;
1159 ++bimd;
1160 }
1161 }
1162 }
1163
1164 return distance;
1165 }
1166
1167 int dvbcut::getPreviousStopEvent(int picture)
1168 {
1169 int previous = 0;
1170
1171 for (int i = 0; i < ui->eventlist->count(); i++) {
1172 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->item(i));
1173 if (eli->geteventtype() == EventListItem::stop && eli->getpicture() < picture)
1174 previous = eli->getpicture();
1175 }
1176
1177 if (previous)
1178 return previous;
1179 else
1180 critical(tr("Searching ..."), tr("Please set a stop marker for the picture to be searched.\nThen go where the picture is expected to appear the next time e.g. the end of the commercial break."));
1181
1182 return picture;
1183 }
1184
1185 void dvbcut::searchDuplicate()
1186 {
1187 ui->searchDuplicateAction->setEnabled(false);
1188
1189 progressstatusbar psb(statusBar());
1190 psb.print(tr("Searching ..."));
1191 psb.setprogress(0);
1192 imageprovider imgp(*mpg);
1193
1194 int search_start_pic = curpic;
1195 QImage last_stop_img = imgp.getimage(getPreviousStopEvent(search_start_pic));
1196
1197 unsigned long min = calc_distance(last_stop_img, imgp.getimage(search_start_pic, true));
1198 static const long n = settings().search_dups_range;
1199
1200 for (long i = 0; i < n; ++i) {
1201 unsigned long d = calc_distance(last_stop_img, imgp.getimage(search_start_pic + i, true));
1202 if (d < min) {
1203 min = d;
1204 gotoFrame(search_start_pic + i);
1205 }
1206
1207 psb.setprogress(i * 1000 / n);
1208 if (psb.cancelled()) {
1209 // FIXME
1210 break;
1211 }
1212 }
1213
1214 ui->searchDuplicateAction->setEnabled(true);
1215 }
1216
1217
1218 void dvbcut::viewUnscaled()
1219 {
1220 ui->viewNormalAction->setChecked(false);
1221 ui->viewUnscaledAction->setChecked(true);
1222 ui->viewDifferenceAction->setChecked(false);
1223
1224 if (!imgp || imgp->rtti()!=IMAGEPROVIDER_UNSCALED) {
1225 if (imgp)
1226 delete imgp;
1227 imgp=new imageprovider(*mpg,new dvbcutbusy(this),true,viewscalefactor);
1228 updateimagedisplay();
1229 }
1230 }
1231
1232
1233 void dvbcut::viewNormal()
1234 {
1235 ui->viewNormalAction->setChecked(true);
1236 ui->viewUnscaledAction->setChecked(false);
1237 ui->viewDifferenceAction->setChecked(false);
1238
1239 if (!imgp || imgp->rtti()!=IMAGEPROVIDER_STANDARD) {
1240 if (imgp)
1241 delete imgp;
1242 imgp=new imageprovider(*mpg,new dvbcutbusy(this),false,viewscalefactor);
1243 updateimagedisplay();
1244 }
1245 }
1246
1247 void dvbcut::zoomIn()
1248 {
1249 setviewscalefactor(viewscalefactor / 1.2);
1250 }
1251
1252 void dvbcut::zoomOut()
1253 {
1254 setviewscalefactor(viewscalefactor * 1.2);
1255 }
1256
1257 void dvbcut::viewFullSize()
1258 {
1259 setviewscalefactor(1.0);
1260 }
1261
1262 void dvbcut::viewHalfSize()
1263 {
1264 setviewscalefactor(2.0);
1265 }
1266
1267 void dvbcut::viewQuarterSize()
1268 {
1269 setviewscalefactor(4.0);
1270 }
1271
1272 void dvbcut::viewCustomSize()
1273 {
1274 setviewscalefactor(settings().viewscalefactor_custom);
1275 }
1276
1277 void dvbcut::playPlay()
1278 {
1279 if (mplayer_process)
1280 return;
1281
1282
1283 ui->eventlist->setEnabled(false);
1284 ui->linslider->setEnabled(false);
1285 ui->jogslider->setEnabled(false);
1286 ui->gobutton->setEnabled(false);
1287 ui->goinput->setEnabled(false);
1288 ui->gobutton2->setEnabled(false);
1289 ui->goinput2->setEnabled(false);
1290
1291 #ifdef HAVE_LIB_AO
1292
1293 ui->playAudio1Action->setEnabled(false);
1294 ui->playAudio2Action->setEnabled(false);
1295 #endif // HAVE_LIB_AO
1296
1297 ui->playPlayAction->setEnabled(false);
1298 ui->playStopAction->setEnabled(true);
1299 audiotrackmenu->setEnabled(false);
1300
1301 ui->fileOpenAction->setEnabled(false);
1302 ui->fileSaveAction->setEnabled(false);
1303 ui->fileSaveAsAction->setEnabled(false);
1304 ui->snapshotSaveAction->setEnabled(false);
1305 ui->chapterSnapshotsSaveAction->setEnabled(false);
1306 ui->fileExportAction->setEnabled(false);
1307
1308 showimage=false;
1309 ui->imagedisplay->setPixmap(QPixmap());
1310 ui->imagedisplay->grabKeyboard();
1311
1312 fine=true;
1313 ui->linslider->setValue(mpg->lastiframe(curpic));
1314 dvbcut_off_t offset=(*mpg)[curpic].getpos().packetposition();
1315 mplayer_curpts=(*mpg)[curpic].getpts();
1316
1317 QString process("mplayer");
1318 QStringList arguments;
1319
1320 arguments << "-noconsolecontrols";
1321 dvbcut_off_t partoffset;
1322 int partindex = buf.getfilenum(offset, partoffset);
1323 if (partindex == -1)
1324 return; // what else can we do?
1325
1326 #ifdef __WIN32__
1327 arguments << "-vo" << "directx:noaccel";
1328 #endif
1329 arguments << "-wid" << QString().asprintf("0x%x",int(ui->imagedisplay->winId()));
1330 arguments << "-sb" << QString::number(offset - partoffset);
1331 arguments << "-geometry" << QString().asprintf("%dx%d+0+0",int(ui->imagedisplay->width()),int(ui->imagedisplay->height()));
1332
1333 if (currentaudiotrack>=0 && currentaudiotrack<mpg->getaudiostreams()) {
1334 arguments << "-aid" << QString().asprintf("0x%x", int(mpg->mplayeraudioid(currentaudiotrack)));
1335 }
1336
1337 // for now, pass all filenames from the current one up to the last one
1338 std::list<std::string>::const_iterator it = mpgfilen.begin();
1339 for (int i = 0; it != mpgfilen.end(); ++i, ++it)
1340 if (i >= partindex)
1341 arguments << QString::fromStdString(*it);
1342
1343 mplayer_process=new QProcess(this);
1344 mplayer_process->setReadChannel(QProcess::StandardOutput);
1345 mplayer_process->setProcessChannelMode(QProcess::MergedChannels);
1346 connect(mplayer_process, SIGNAL(finished(int)), this, SLOT(mplayer_exited()));
1347 connect(mplayer_process, SIGNAL(readyReadStandardOutput()), this, SLOT(mplayer_readstdout()));
1348
1349 mplayer_success=false;
1350 mplayer_process->start(process, arguments);
1351 }
1352
1353 void dvbcut::playStop()
1354 {
1355 if (mplayer_process)
1356 mplayer_process->terminate();
1357 }
1358
1359 void dvbcut::playAudio1()
1360 {
1361 #ifdef HAVE_LIB_AO
1362 qApp->processEvents();
1363 try
1364 {
1365 mpg->playaudio(currentaudiotrack,curpic,-2000);
1366 }
1367 catch (const dvbcut_exception &ex)
1368 {
1369 ex.show();
1370 }
1371 #endif // HAVE_LIB_AO
1372 }
1373
1374 void dvbcut::playAudio2()
1375 {
1376 #ifdef HAVE_LIB_AO
1377 qApp->processEvents();
1378 try
1379 {
1380 mpg->playaudio(currentaudiotrack,curpic,2000);
1381 }
1382 catch (const dvbcut_exception &ex)
1383 {
1384 ex.show();
1385 }
1386 #endif // HAVE_LIB_AO
1387 }
1388
1389 // **************************************************************************
1390 // *** slots
1391
1392 void dvbcut::linslidervalue(int newpic)
1393 {
1394 ui->linslider->setTracking(false);
1395
1396 if (!mpg || newpic==curpic)
1397 {
1398 ui->linslider->setTracking(true);
1399 return;
1400 }
1401 if (!fine)
1402 newpic=mpg->lastiframe(newpic);
1403 if (!jogsliding)
1404 jogmiddlepic=newpic;
1405 if (newpic==curpic)
1406 {
1407 ui->linslider->setTracking(true);
1408 return;
1409 }
1410
1411 curpic=newpic;
1412 if (!jogsliding)
1413 jogmiddlepic=newpic;
1414
1415 update_time_display();
1416 updateimagedisplay();
1417
1418 ui->linslider->setTracking(true);
1419 }
1420
1421 void dvbcut::jogsliderreleased()
1422 {
1423 jogsliding=false;
1424 jogmiddlepic=curpic;
1425 ui->jogslider->setValue(0);
1426 }
1427
1428 void dvbcut::jogslidervalue(int v)
1429 {
1430 ui->jogslider->setTracking(false);
1431
1432 if (!mpg || (v==0 && curpic==jogmiddlepic))
1433 {
1434 ui->jogslider->setTracking(true);
1435 return;
1436 }
1437 jogsliding=true;
1438
1439 int relpic=0;
1440
1441 /*
1442 if (v>jog_offset)
1443 relpic=int(exp(alpha*(v-jog_offset))+.5);
1444 else if (v<-jog_offset)
1445 relpic=-int(exp(alpha*(-v-jog_offset))+.5);
1446 */
1447 /*
1448 alternative function
1449 (fits better to external tick interval setting, because jog_offset
1450 only affects scale at small numbers AND range of 1 frame is NOT smaller
1451 than range of 0 and 2 frames as in old function!)
1452 */
1453 if (v>0) {
1454 relpic=int(exp(alpha*v)-settings().jog_offset);
1455 if (relpic<0) relpic=0;
1456 }
1457 else if (v<0) {
1458 relpic=-int(exp(-alpha*v)-settings().jog_offset);
1459 if (relpic>0) relpic=0;
1460 }
1461
1462 int newpic=jogmiddlepic+relpic;
1463 if (newpic<0)
1464 newpic=0;
1465 else if (newpic>=pictures)
1466 newpic=pictures-1;
1467
1468 if (relpic>=settings().jog_threshold) {
1469 newpic=mpg->nextiframe(newpic);
1470 fine=false;
1471 } else if (relpic<=-settings().jog_threshold) {
1472 fine=false;
1473 } else
1474 fine=true;
1475
1476 if (curpic!=newpic)
1477 ui->linslider->setValue(newpic);
1478
1479 fine=false;
1480
1481 ui->jogslider->setTracking(true);
1482 }
1483
1484 void dvbcut::doubleclickedeventlist(QListWidgetItem *lbi)
1485 {
1486 EventListItem *item = dynamic_cast<EventListItem *>(lbi);
1487 if (!item)
1488 return;
1489
1490 fine=true;
1491 ui->linslider->setValue(item->getpicture());
1492 fine=false;
1493 }
1494
1495 void dvbcut::eventlistcontextmenu(const QPoint &point)
1496 {
1497 EventListItem *eli = dynamic_cast<EventListItem *>(ui->eventlist->itemAt(point));
1498 if (!eli)
1499 return;
1500
1501 enum popup_actions {
1502 act_go_to = 1,
1503 act_delete,
1504 act_delete_others,
1505 act_delete_all,
1506 act_delete_all_startstops,
1507 act_delete_all_chapters,
1508 act_delete_all_bookmarks,
1509 act_convert_to_start,
1510 act_convert_to_stop,
1511 act_convert_to_chapter,
1512 act_convert_to_bookmark,
1513 act_display_difference
1514 };
1515
1516 QMenu popup(ui->eventlist);
1517 popup.addAction(tr("Go to"))->setData(act_go_to);
1518 popup.addSeparator();
1519 popup.addAction(tr("Delete"))->setData(act_delete);
1520 popup.addAction(tr("Delete others"))->setData(act_delete_others);
1521 popup.addAction(tr("Delete all"))->setData(act_delete_all);
1522 popup.addAction(tr("Delete all start/stops"))->setData(act_delete_all_startstops);
1523 popup.addAction(tr("Delete all chapters"))->setData(act_delete_all_chapters);
1524 popup.addAction(tr("Delete all bookmarks"))->setData(act_delete_all_bookmarks);
1525 popup.addSeparator();
1526 popup.addAction(tr("Convert to start marker"))->setData(act_convert_to_start);
1527 popup.addAction(tr("Convert to stop marker"))->setData(act_convert_to_stop);
1528 popup.addAction(tr("Convert to chapter marker"))->setData(act_convert_to_chapter);
1529 popup.addAction(tr("Convert to bookmark"))->setData(act_convert_to_bookmark);
1530 popup.addSeparator();
1531 popup.addAction(tr("Display difference from this picture"))->setData(act_display_difference);
1532
1533 QListWidget *lb = ui->eventlist;
1534 EventListItem::eventtype cmptype=EventListItem::none, cmptype2=EventListItem::none;
1535 int index;
1536
1537 QAction *a = popup.exec(ui->eventlist->mapToGlobal(point));
1538 if (!a)
1539 return;
1540 switch (a->data().toInt()) {
1541 case act_go_to:
1542 fine=true;
1543 ui->linslider->setValue(eli->getpicture());
1544 fine=false;
1545 break;
1546
1547 case act_delete:
1548 {
1549 EventListItem::eventtype type=eli->geteventtype();
1550 delete eli;
1551 if (type!=EventListItem::bookmark) update_quick_picture_lookup_table();
1552 }
1553 break;
1554
1555 case act_delete_others:
1556 for (index = lb->count(); index > 0; index--) {
1557 EventListItem *t = dynamic_cast<EventListItem *>(lb->item(index-1));
1558 if (t != eli)
1559 delete t;
1560 }
1561 update_quick_picture_lookup_table();
1562 break;
1563
1564 case act_delete_all:
1565 lb->clear();
1566 update_quick_picture_lookup_table();
1567 break;
1568
1569 case act_delete_all_startstops:
1570 cmptype=EventListItem::start;
1571 cmptype2=EventListItem::stop;
1572 case act_delete_all_chapters:
1573 if (cmptype==EventListItem::none) cmptype=EventListItem::chapter;
1574 case act_delete_all_bookmarks:
1575 if (cmptype==EventListItem::none) cmptype=EventListItem::bookmark;
1576 for (index = lb->count(); index > 0; index--) {
1577 EventListItem *t = dynamic_cast<EventListItem *>(lb->item(index-1));
1578 if (t->geteventtype() == cmptype || t->geteventtype() == cmptype2)
1579 delete t;
1580 }
1581 if (cmptype!=EventListItem::bookmark) update_quick_picture_lookup_table();
1582 break;
1583
1584 case act_convert_to_start:
1585 eli->seteventtype(EventListItem::start);
1586 update_quick_picture_lookup_table();
1587 break;
1588
1589 case act_convert_to_stop:
1590 eli->seteventtype(EventListItem::stop);
1591 update_quick_picture_lookup_table();
1592 break;
1593
1594 case act_convert_to_chapter:
1595 eli->seteventtype(EventListItem::chapter);
1596 update_quick_picture_lookup_table();
1597 break;
1598
1599 case act_convert_to_bookmark:
1600 eli->seteventtype(EventListItem::bookmark);
1601 update_quick_picture_lookup_table();
1602 break;
1603
1604 case act_display_difference:
1605 if (imgp)
1606 delete imgp;
1607 imgp=new differenceimageprovider(*mpg,eli->getpicture(),new dvbcutbusy(this),false,viewscalefactor);
1608 updateimagedisplay();
1609 ui->viewNormalAction->setChecked(false);
1610 ui->viewUnscaledAction->setChecked(false);
1611 ui->viewDifferenceAction->setChecked(true);
1612 break;
1613 }
1614
1615 }
1616
1617 void dvbcut::clickedgo()
1618 {
1619 QString text=ui->goinput->text();
1620 text = text.trimmed();
1621 bool okay=false;
1622 int inpic;
1623 if (text.contains(':') || text.contains('.')) {
1624 okay=true;
1625 inpic=string2pts(text.toStdString())/getTimePerFrame();
1626 }
1627 else
1628 inpic=text.toInt(&okay,0);
1629 if (okay) {
1630 fine=true;
1631 ui->linslider->setValue(inpic);
1632 fine=false;
1633 }
1634 //goinput->clear();
1635 }
1636
1637 void dvbcut::clickedgo2()
1638 {
1639 QString text=ui->goinput2->text();
1640 text = text.trimmed();
1641 bool okay=false;
1642 int inpic, outpic;
1643 if (text.contains(':') || text.contains('.')) {
1644 okay=true;
1645 outpic=string2pts(text.toStdString())/getTimePerFrame();
1646 }
1647 else
1648 outpic=text.toInt(&okay,0);
1649 if (okay && !quick_picture_lookup.empty()) {
1650 // find the entry in the quick_picture_lookup table that corresponds to given output picture
1651 quick_picture_lookup_t::iterator it=
1652 std::upper_bound(quick_picture_lookup.begin(),quick_picture_lookup.end(),outpic,quick_picture_lookup_s::cmp_outpicture());
1653 inpic=outpic-it->outpicture+it->stoppicture;
1654 fine=true;
1655 ui->linslider->setValue(inpic);
1656 fine=false;
1657 }
1658 //goinput2->clear();
1659 }
1660
1661 void dvbcut::mplayer_exited()
1662 {
1663 if (mplayer_process) {
1664 if (!mplayer_success)// && !mplayer_process->normalExit())
1665 {
1666 mplayererrorbase *meb=new mplayererrorbase(this);
1667 meb->setText(mplayer_out);
1668 }
1669 mplayer_process->deleteLater();
1670 mplayer_process=0;
1671 }
1672
1673 ui->eventlist->setEnabled(true);
1674 ui->linslider->setEnabled(true);
1675 ui->jogslider->setEnabled(true);
1676 ui->gobutton->setEnabled(true);
1677 ui->goinput->setEnabled(true);
1678 ui->eventlist->setEnabled(true);
1679 ui->linslider->setEnabled(true);
1680 ui->jogslider->setEnabled(true);
1681 ui->gobutton->setEnabled(true);
1682 ui->goinput->setEnabled(true);
1683 ui->gobutton2->setEnabled(true);
1684 ui->goinput2->setEnabled(true);
1685
1686 #ifdef HAVE_LIB_AO
1687
1688 ui->playAudio1Action->setEnabled(true);
1689 ui->playAudio2Action->setEnabled(true);
1690 #endif // HAVE_LIB_AO
1691
1692 ui->playPlayAction->setEnabled(true);
1693 ui->playStopAction->setEnabled(false);
1694 audiotrackmenu->setEnabled(true);
1695
1696 ui->fileOpenAction->setEnabled(true);
1697 ui->fileSaveAction->setEnabled(true);
1698 ui->fileSaveAsAction->setEnabled(true);
1699 ui->snapshotSaveAction->setEnabled(true);
1700 ui->chapterSnapshotsSaveAction->setEnabled(true);
1701 ui->fileExportAction->setEnabled(true);
1702
1703 ui->imagedisplay->releaseKeyboard();
1704
1705 int cp=curpic;
1706 jogmiddlepic=curpic;
1707 curpic=-1;
1708 showimage=true;
1709 fine=true;
1710 linslidervalue(cp);
1711 ui->linslider->setValue(cp);
1712 fine=false;
1713 }
1714
1715 void dvbcut::mplayer_readstdout()
1716 {
1717 if (!mplayer_process)
1718 return;
1719
1720 QString line(mplayer_process->readAllStandardOutput());
1721 if (!line.length())
1722 return;
1723
1724 if (!mplayer_success)
1725 mplayer_out += line;
1726
1727 int pos=line.indexOf("V:");
1728 if (pos<0)
1729 return;
1730
1731 line.remove(0,pos+2);
1732 line=line.trimmed();
1733 for(pos=0;pos<(signed)line.length();++pos)
1734 if ((line[pos]<'0' || line[pos]>'9')&&line[pos]!='.')
1735 break;
1736 line.truncate(pos);
1737 if (line.length()==0)
1738 return;
1739
1740 bool okay;
1741 double d=line.toDouble(&okay);
1742 if (d==0 || !okay)
1743 return;
1744
1745 if (!mplayer_success) {
1746 mplayer_success=true;
1747 mplayer_out.truncate(0);
1748 }
1749 pts_t pts=mplayer_ptsreference(pts_t(d*90000.),mplayer_curpts);
1750
1751
1752 if (pts==mplayer_curpts)
1753 return;
1754
1755 int cp=curpic;
1756
1757 if (pts>mplayer_curpts) {
1758 while (cp+1<pictures && pts>mplayer_curpts)
1759 mplayer_curpts=(*mpg)[++cp].getpts();
1760 } else if (pts<mplayer_curpts-18000) {
1761 while (cp>1 && mplayer_curpts>pts)
1762 mplayer_curpts=(*mpg)[--cp].getpts();
1763 }
1764
1765 ui->linslider->setValue(cp);
1766 }
1767
1768 void dvbcut::updateimagedisplay()
1769 {
1770 if (showimage) {
1771 if (!imgp)
1772 imgp=new imageprovider(*mpg,new dvbcutbusy(this),false,viewscalefactor);
1773 QImage px=imgp->getimage(curpic,fine);
1774 ui->imagedisplay->setMinimumSize(px.size());
1775 ui->imagedisplay->setPixmap(QPixmap::fromImage(px));
1776 ui->imagedisplay->update();
1777 qApp->processEvents();
1778 }
1779 }
1780
1781 void dvbcut::audiotrackchosen(QAction* a)
1782 {
1783 int id = a->data().toInt();
1784 if (id<0 || id>mpg->getaudiostreams())
1785 return;
1786 currentaudiotrack=id;
1787 }
1788
1789 void dvbcut::abouttoshowrecentfiles()
1790 {
1791 recentfilespopup->clear();
1792 QString menuitem;
1793 for(unsigned int id=0; id<settings().recentfiles.size(); id++) {
1794 menuitem=QString(QString::fromStdString(settings().recentfiles[id].first.front()));
1795 if(settings().recentfiles[id].first.size()>1)
1796 menuitem += " ... (+" + QString::number(settings().recentfiles[id].first.size()-1) + ")";
1797 recentfilespopup->addAction(menuitem)->setData(id);
1798 }
1799 }
1800
1801 void dvbcut::loadrecentfile(QAction* a)
1802 {
1803 int id = a->data().toInt();
1804 if (id<0 || id>=(signed)settings().recentfiles.size())
1805 return;
1806 open(settings().recentfiles[(unsigned)id].first, settings().recentfiles[(unsigned)id].second);
1807 }
1808
1809 // **************************************************************************
1810 // *** public functions
1811
1812 void dvbcut::open(std::list<std::string> filenames, std::string idxfilename, std::string expfilename)
1813 {
1814 if (filenames.empty()) {
1815 QStringList fn = QFileDialog::getOpenFileNames(
1816 this,
1817 tr("Choose one or more MPEG files to open"),
1818 settings().lastdir,
1819 tr(DVBCUT_LOADFILTER));
1820 if (fn.empty()) {
1821 // fprintf(stderr,"open(): QFileDialog::getOpenFileNames() returned EMPTY filelist!!!\n");
1822 // fprintf(stderr," If you didn't saw a FileDialog, please check your 'lastdir' settings variable...");
1823 return;
1824 }
1825 for (QStringList::Iterator it = fn.begin(); it != fn.end(); ++it)
1826 filenames.push_back(it->toStdString());
1827
1828 // remember last directory if requested
1829 if (settings().lastdir_update) {
1830 QString dir = fn.front();
1831 int n = dir.lastIndexOf('/');
1832 if (n > 0)
1833 dir = dir.left(n);
1834 // adding a slash is NEEDED for top level directories (win or linux), and doesn't matter otherwise!
1835 dir = dir + "/";
1836 settings().lastdir = dir;
1837 }
1838 }
1839
1840 // hmmmm,... do we really need this? With fn.empty() we never reach this line...
1841 if (filenames.empty())
1842 return;
1843
1844 make_canonical(filenames);
1845
1846 std::string filename = filenames.front();
1847
1848 // a valid file name has been entered
1849 setWindowTitle(QString(VERSION_STRING " - " + QString::fromStdString(filename)));
1850
1851 // reset inbuffer
1852 buf.reset();
1853
1854 // if an MPEG file has already been opened, close it and reset the UI
1855 if (mpg) {
1856 delete mpg;
1857 mpg=0;
1858 }
1859
1860 curpic=~0;
1861 if (imgp) {
1862 delete imgp;
1863 imgp=0;
1864 }
1865 ui->eventlist->clear();
1866 ui->imagedisplay->setMinimumSize(QSize(0,0));
1867 ui->imagedisplay->setPixmap(QPixmap());
1868 ui->pictimelabel->clear();
1869 ui->pictimelabel2->clear();
1870 ui->picinfolabel->clear();
1871 ui->picinfolabel2->clear();
1872 ui->linslider->setValue(0);
1873 ui->jogslider->setValue(0);
1874
1875 ui->viewNormalAction->setChecked(true);
1876 ui->viewUnscaledAction->setChecked(false);
1877 ui->viewDifferenceAction->setChecked(false);
1878
1879 ui->fileOpenAction->setEnabled(false);
1880 ui->fileSaveAction->setEnabled(false);
1881 ui->fileSaveAsAction->setEnabled(false);
1882 ui->snapshotSaveAction->setEnabled(false);
1883 ui->chapterSnapshotsSaveAction->setEnabled(false);
1884 // enable closing even if no file was loaded (mr)
1885 //fileCloseAction->setEnabled(false);
1886 ui->fileExportAction->setEnabled(false);
1887 ui->playPlayAction->setEnabled(false);
1888 ui->playStopAction->setEnabled(false);
1889 audiotrackmenu->setEnabled(false);
1890 audiotrackpopup->clear();
1891 ui->editStartAction->setEnabled(false);
1892 ui->editStopAction->setEnabled(false);
1893 ui->editChapterAction->setEnabled(false);
1894 ui->editBookmarkAction->setEnabled(false);
1895 ui->editAutoChaptersAction->setEnabled(false);
1896 ui->editSuggestAction->setEnabled(false);
1897 ui->editImportAction->setEnabled(false);
1898 //editConvertAction->setEnabled(false);
1899
1900 #ifdef HAVE_LIB_AO
1901
1902 ui->playAudio1Action->setEnabled(false);
1903 ui->playAudio2Action->setEnabled(false);
1904 #endif // HAVE_LIB_AO
1905
1906 ui->viewNormalAction->setEnabled(false);
1907 ui->viewUnscaledAction->setEnabled(false);
1908 ui->viewDifferenceAction->setEnabled(false);
1909
1910 ui->eventlist->setEnabled(false);
1911 ui->imagedisplay->setEnabled(false);
1912 ui->pictimelabel->setEnabled(false);
1913 ui->pictimelabel2->setEnabled(false);
1914 ui->picinfolabel->setEnabled(false);
1915 ui->picinfolabel2->setEnabled(false);
1916 ui->goinput->setEnabled(false);
1917 ui->gobutton->setEnabled(false);
1918 ui->goinput2->setEnabled(false);
1919 ui->gobutton2->setEnabled(false);
1920 ui->linslider->setEnabled(false);
1921 ui->jogslider->setEnabled(false);
1922
1923 std::string prjfilename;
1924 QDomDocument domdoc;
1925 {
1926 QFile infile(QString::fromStdString(filename));
1927 if (infile.open(QIODevice::ReadOnly)) {
1928 char buff[512];
1929 QString line;
1930 qint64 readBytes = infile.readLine(buff,512);
1931 if(readBytes>0)
1932 line = QString::fromLatin1(buff, readBytes);
1933 if (line.startsWith(QString("<!DOCTYPE"))
1934 || line.startsWith(QString("<?xml"))) {
1935 infile.seek(0);
1936 QString errormsg;
1937 if (domdoc.setContent(&infile,false,&errormsg)) {
1938 QDomElement docelem = domdoc.documentElement();
1939 if (docelem.tagName() != "dvbcut") {
1940 critical(tr("Failed to read project file - dvbcut"),
1941 //: Placeholder will be replaced with filename
1942 tr("%1:\nNot a valid dvbcut project file").arg(QString::fromStdString(filename)));
1943 ui->fileOpenAction->setEnabled(true);
1944 return;
1945 }
1946 // parse elements, new-style first
1947 QDomNode n;
1948 filenames.clear();
1949 if (!nogui) {
1950 // in batch mode CLI-switches have priority!
1951 idxfilename.clear();
1952 expfilename.clear();
1953 }
1954 for (n = domdoc.documentElement().firstChild(); !n.isNull(); n = n.nextSibling()) {
1955 QDomElement e = n.toElement();
1956 if (e.isNull())
1957 continue;
1958 if (e.tagName() == "mpgfile") {
1959 QString qs = e.attribute("path");
1960 if (!qs.isEmpty())
1961 filenames.push_back(qs.toStdString());
1962 }
1963 else if (e.tagName() == "idxfile" && idxfilename.empty()) {
1964 QString qs = e.attribute("path");
1965 if (!qs.isEmpty())
1966 idxfilename = qs.toStdString();
1967 }
1968 else if (e.tagName() == "expfile" && expfilename.empty()) {
1969 QString qs = e.attribute("path");
1970 if (!qs.isEmpty())
1971 expfilename = qs.toStdString();
1972 qs = e.attribute("format");
1973 bool okay=false;
1974 if (!qs.isEmpty()) {
1975 int val = qs.toInt(&okay,0);
1976 if(okay) exportformat = val;
1977 }
1978 }
1979 }
1980 // try old-style project file format
1981 if (filenames.empty()) {
1982 QString qs = docelem.attribute("mpgfile");
1983 if (!qs.isEmpty())
1984 filenames.push_back(qs.toStdString());
1985 }
1986 if (idxfilename.empty()) {
1987 QString qs = docelem.attribute("idxfile");
1988 if (!qs.isEmpty())
1989 idxfilename = qs.toStdString();
1990 }
1991 if (expfilename.empty()) {
1992 QString qs = docelem.attribute("expfile");
1993 if (!qs.isEmpty())
1994 expfilename = qs.toStdString();
1995 }
1996 // sanity check
1997 if (filenames.empty()) {
1998 critical(tr("Failed to read project file - dvbcut"),
1999 //: Placeholder will be replaced with project filename
2000 tr("%1:\nNo MPEG filename given in project file").arg(QString::fromStdString(filename)));
2001 ui->fileOpenAction->setEnabled(true);
2002 return;
2003 }
2004 prjfilename = filename;
2005 }
2006 else {
2007 critical(tr("Failed to read project file - dvbcut"),
2008 QString::fromStdString(filename) + ":\n" + errormsg);
2009 ui->fileOpenAction->setEnabled(true);
2010 return;
2011 }
2012 }
2013 }
2014 }
2015
2016 // make filename the first MPEG file
2017 filename = filenames.front();
2018
2019 dvbcutbusy busy(this);
2020 busy.setbusy(true);
2021
2022 mpg = 0;
2023 std::string errormessage;
2024 std::list<std::string>::const_iterator it = filenames.begin();
2025 while (it != filenames.end() && buf.open(*it, &errormessage))
2026 ++it;
2027 buf.setsequential(cache_friendly);
2028 if (it == filenames.end()) {
2029 mpg = mpgfile::open(buf, &errormessage);
2030 }
2031 busy.setbusy(false);
2032
2033 if (!mpg) {
2034 critical(tr("Failed to open file - dvbcut"), errormessage);
2035 ui->fileOpenAction->setEnabled(true);
2036 return;
2037 }
2038
2039 if (idxfilename.empty()) {
2040 idxfilename = filename + ".idx";
2041 if (!nogui) {
2042 /*
2043 * BEWARE! UGLY HACK BELOW!
2044 *
2045 * In order to circumvent the QFileDialog's stupid URL parsing,
2046 * we need to first change to the directory and then pass the
2047 * filename as a relative file: URL. Otherwise, filenames that
2048 * contain ":" will not be handled correctly. --mr
2049 */
2050 QUrl u;
2051 u.setScheme("file");
2052 u.setPath(QString::fromStdString(idxfilename));
2053 if (chdir(QFileInfo(u.path()).absolutePath().toLatin1()) == -1)
2054 if (chdir("/") == -1)
2055 fprintf(stderr, "chdir(\"/\") failed\n");
2056 QString relname = QFileInfo(u.path()).fileName();
2057 QString s=QFileDialog::getSaveFileName(
2058 this,
2059 tr("Choose the name of the index file"),
2060 relname,
2061 tr(DVBCUT_IDXFILTER) );
2062 if (s.isEmpty()) {
2063 delete mpg;
2064 mpg=0;
2065 ui->fileOpenAction->setEnabled(true);
2066 return;
2067 }
2068 idxfilename = s.toStdString();
2069 // it's now a relative name that will be canonicalized again soon
2070 }
2071 }
2072
2073 make_canonical(idxfilename);
2074
2075 pictures=-1;
2076
2077 if (!idxfilename.empty()) {
2078 std::string errorstring;
2079 busy.setbusy(true);
2080 pictures=mpg->loadindex(idxfilename.c_str(),&errorstring);
2081 int serrno=errno;
2082 busy.setbusy(false);
2083 if (nogui && pictures > 0)
2084 fprintf(stderr,"Loaded index with %d pictures!\n",pictures);
2085 if (pictures==-1 && serrno!=ENOENT) {
2086 delete mpg;
2087 mpg=0;
2088 critical(tr("Failed to open file - dvbcut"),errorstring);
2089 ui->fileOpenAction->setEnabled(true);
2090 return;
2091 }
2092 if (pictures==-2) {
2093 delete mpg;
2094 mpg=0;
2095 critical(tr("Invalid index file - dvbcut"), errorstring);
2096 ui->fileOpenAction->setEnabled(true);
2097 return;
2098 }
2099 if (pictures<=-3) {
2100 delete mpg;
2101 mpg=0;
2102 //: The index file belongs to another MPEG file
2103 critical(tr("Index file mismatch - dvbcut"), errorstring);
2104 ui->fileOpenAction->setEnabled(true);
2105 return;
2106 }
2107 }
2108
2109 if (pictures<0) {
2110 progressstatusbar psb(statusBar());
2111 psb.setprogress(500);
2112 //: Text shown in the main window status bar when generating index. For example: "Indexing 'path/to/file.mpg'..."
2113 psb.print(tr("Indexing '%1'...").arg(QString::fromStdString(filename)));
2114 std::string errorstring;
2115 busy.setbusy(true);
2116 pictures=mpg->generateindex(idxfilename.empty()?0:idxfilename.c_str(),&errorstring,&psb);
2117 busy.setbusy(false);
2118 if (nogui && pictures > 0)
2119 fprintf(stderr,"Generated index with %d pictures!\n",pictures);
2120
2121 if (psb.cancelled()) {
2122 delete mpg;
2123 mpg=0;
2124 ui->fileOpenAction->setEnabled(true);
2125 return;
2126 }
2127
2128 if (pictures<0) {
2129 delete mpg;
2130 mpg=0;
2131 critical(tr("Error creating index - dvbcut"),
2132 //: %1 will be replaced with filename, %2 with error description
2133 tr("Cannot create index for\n%1:\n%2").arg(QString::fromStdString(filename), QString::fromStdString(errorstring)));
2134 ui->fileOpenAction->setEnabled(true);
2135 return;
2136 } else if (!errorstring.empty()) {
2137 critical(tr("Error saving index file - dvbcut"), QString::fromStdString(errorstring));
2138 }
2139 }
2140
2141 if (pictures<1) {
2142 delete mpg;
2143 mpg=0;
2144 critical(tr("Invalid MPEG file - dvbcut"),
2145 //: Placeholder will be replaced with filename
2146 tr("The chosen file\n%1\ndoes not contain any video").arg(QString::fromStdString(filename)));
2147 ui->fileOpenAction->setEnabled(true);
2148 return;
2149 }
2150
2151 // file loaded, switch to random mode
2152 buf.setsequential(false);
2153
2154 mpgfilen=filenames;
2155 idxfilen=idxfilename;
2156 prjfilen=prjfilename;
2157 expfilen=expfilename;
2158 picfilen=QString();
2159 if (prjfilen.empty())
2160 addtorecentfiles(mpgfilen,idxfilen);
2161 else {
2162 std::list<std::string> dummy_list;
2163 dummy_list.push_back(prjfilen);
2164 addtorecentfiles(dummy_list);
2165 }
2166
2167 firstpts=(*mpg)[0].getpts();
2168 timeperframe=(*mpg)[1].getpts()-(*mpg)[0].getpts();
2169
2170 double fps=27.e6/double(mpgfile::frameratescr[(*mpg)[0].getframerate()]);
2171 ui->linslider->setMaximum(pictures-1);
2172 ui->linslider->setSingleStep(int(300*fps));
2173 ui->linslider->setPageStep(int(900*fps));
2174 if (settings().lin_interval > 0)
2175 ui->linslider->setTickInterval(int(settings().lin_interval*fps));
2176
2177 //alpha=log(jog_maximum)/double(100000-jog_offset);
2178 // with alternative function
2179 alpha=log(settings().jog_maximum)/100000.;
2180 if (settings().jog_interval > 0 && settings().jog_interval <= 100000)
2181 ui->jogslider->setTickInterval(int(100000/settings().jog_interval));
2182
2183 curpic=~0;
2184 showimage=true;
2185 fine=false;
2186 jogsliding=false;
2187 jogmiddlepic=0;
2188 imgp=new imageprovider(*mpg,new dvbcutbusy(this),false,viewscalefactor);
2189
2190 linslidervalue(0);
2191 ui->linslider->setValue(0);
2192 ui->jogslider->setValue(0);
2193
2194 ui->eventlist->setMinimumWidth(200);
2195
2196 if (!domdoc.isNull()) {
2197 QDomElement e;
2198 for (QDomNode n=domdoc.documentElement().firstChild();!n.isNull();n=n.nextSibling())
2199 if (!(e=n.toElement()).isNull()) {
2200 EventListItem::eventtype evt;
2201 if (e.tagName()=="start")
2202 evt=EventListItem::start;
2203 else if (e.tagName()=="stop")
2204 evt=EventListItem::stop;
2205 else if (e.tagName()=="chapter")
2206 evt=EventListItem::chapter;
2207 else if (e.tagName()=="bookmark")
2208 evt=EventListItem::bookmark;
2209 else
2210 continue;
2211 bool okay=false;
2212 int picnum;
2213 QString str=e.attribute("picture","-1");
2214 if (str.contains(':') || str.contains('.')) {
2215 okay=true;
2216 picnum=string2pts(str.toStdString())/getTimePerFrame();
2217 }
2218 else
2219 picnum=str.toInt(&okay,0);
2220 if (okay && picnum>=0 && picnum<pictures) {
2221 new EventListItem(ui->eventlist,QPixmap::fromImage(imgp->getimage(picnum)),evt,picnum,(*mpg)[picnum].getpicturetype(),(*mpg)[picnum].getpts()-firstpts);
2222 }
2223 }
2224 }
2225
2226 update_quick_picture_lookup_table();
2227
2228 ui->fileOpenAction->setEnabled(true);
2229 ui->fileSaveAction->setEnabled(true);
2230 ui->fileSaveAsAction->setEnabled(true);
2231 ui->snapshotSaveAction->setEnabled(true);
2232 ui->chapterSnapshotsSaveAction->setEnabled(true);
2233 ui->fileCloseAction->setEnabled(true);
2234 ui->fileExportAction->setEnabled(true);
2235 ui->playPlayAction->setEnabled(true);
2236 audiotrackmenu->setEnabled(true);
2237 ui->playStopAction->setEnabled(false);
2238 ui->editStartAction->setEnabled(true);
2239 ui->editStopAction->setEnabled(true);
2240 ui->editChapterAction->setEnabled(true);
2241 ui->editBookmarkAction->setEnabled(true);
2242 ui->editAutoChaptersAction->setEnabled(true);
2243 ui->editSuggestAction->setEnabled(true);
2244 ui->editImportAction->setEnabled(true);
2245 //editConvertAction->setEnabled(true);
2246 ui->viewNormalAction->setEnabled(true);
2247 ui->viewUnscaledAction->setEnabled(true);
2248 ui->viewDifferenceAction->setEnabled(true);
2249
2250 #ifdef HAVE_LIB_AO
2251
2252 if (mpg->getaudiostreams()) {
2253 ui->playAudio1Action->setEnabled(true);
2254 ui->playAudio2Action->setEnabled(true);
2255 }
2256 #endif // HAVE_LIB_AO
2257
2258 ui->eventlist->setEnabled(true);
2259 ui->imagedisplay->setEnabled(true);
2260 ui->pictimelabel->setEnabled(true);
2261 ui->pictimelabel2->setEnabled(true);
2262 ui->picinfolabel->setEnabled(true);
2263 ui->picinfolabel2->setEnabled(true);
2264 ui->goinput->setEnabled(true);
2265 ui->gobutton->setEnabled(true);
2266 ui->goinput2->setEnabled(true);
2267 ui->gobutton2->setEnabled(true);
2268 ui->linslider->setEnabled(true);
2269 ui->jogslider->setEnabled(true);
2270
2271 QActionGroup *audiotrackmenugroup = new QActionGroup(this);
2272 for(int a=0;a<mpg->getaudiostreams();++a) {
2273 QAction* action = audiotrackpopup->addAction(QString::fromStdString(mpg->getstreaminfo(audiostream(a))));
2274 action->setData(a);
2275 action->setCheckable(true);
2276 audiotrackmenugroup->addAction(action);
2277 }
2278 if (mpg->getaudiostreams()>0) {
2279 audiotrackpopup->actions().at(0)->setChecked(true);
2280 currentaudiotrack=0;
2281 } else
2282 currentaudiotrack=-1;
2283 }
2284
2285 // **************************************************************************
2286 // *** protected functions
2287
2288 void dvbcut::addtorecentfiles(const std::list<std::string> &filenames, const std::string &idxfilename)
2289 {
2290
2291 for(std::vector<std::pair<std::list<std::string>,std::string> >::iterator it=settings().recentfiles.begin();
2292 it!=settings().recentfiles.end();)
2293 // checking the size and the first/last filename should be enough... but maybe I'm to lazy! ;-)
2294 if (it->first.size()==filenames.size() && it->first.front()==filenames.front() && it->first.back()==filenames.back())
2295 it=settings().recentfiles.erase(it);
2296 else
2297 ++it;
2298
2299 settings().recentfiles.insert(settings().recentfiles.begin(),std::pair<std::list<std::string>,std::string>(filenames,idxfilename));
2300
2301 while (settings().recentfiles.size()>settings().recentfiles_max)
2302 settings().recentfiles.pop_back();
2303 }
2304
2305 void dvbcut::setviewscalefactor(double factor)
2306 {
2307 if (factor<=0.0)
2308 factor=1.0;
2309 ui->viewFullSizeAction->setChecked(factor==1.0);
2310 ui->viewHalfSizeAction->setChecked(factor==2.0);
2311 ui->viewQuarterSizeAction->setChecked(factor==4.0);
2312 ui->viewCustomSizeAction->setChecked(factor==settings().viewscalefactor_custom);
2313
2314 settings().viewscalefactor = factor;
2315
2316 if (factor!=viewscalefactor) {
2317 viewscalefactor=factor;
2318 if (imgp) {
2319 imgp->setviewscalefactor(factor);
2320 updateimagedisplay();
2321 }
2322 }
2323 }
2324
2325 bool dvbcut::eventFilter(QObject *watched, QEvent *e) {
2326 bool myEvent = true;
2327 int delta = 0;
2328 int incr = WHEEL_INCR_NORMAL;
2329 Qt::KeyboardModifiers mods;
2330
2331 if (e->type() == QEvent::Wheel && watched != ui->jogslider) {
2332 QWheelEvent *we = (QWheelEvent*)e;
2333 // Note: delta is a multiple of 120 (see Qt documentation)
2334 delta = we->angleDelta().y();
2335 mods = we->modifiers();
2336 if(mods & Qt::AltModifier) {
2337 incr = WHEEL_INCR_ALT;
2338 } else if(mods & Qt::ControlModifier) {
2339 incr = WHEEL_INCR_CTRL;
2340 } else if(mods & Qt::ShiftModifier) {
2341 incr = WHEEL_INCR_SHIFT;
2342 } else if(mods & Qt::MetaModifier) {
2343 // TODO: do we want/need another step-size?
2344 // incr = WHEEL_INCR_META;
2345 }
2346
2347 }
2348 else if (e->type() == QEvent::KeyPress) {
2349 QKeyEvent *ke = (QKeyEvent*)e;
2350 delta = ke->count() * settings().wheel_delta;
2351 if (ke->key() == Qt::Key_Right)
2352 delta = -delta;
2353 else if (ke->key() != Qt::Key_Left)
2354 myEvent = false;
2355 mods = ke->modifiers();
2356 if(mods & Qt::AltModifier) {
2357 incr = WHEEL_INCR_ALT;
2358 } else if(mods & Qt::ControlModifier) {
2359 incr = WHEEL_INCR_CTRL;
2360 } else if(mods & Qt::ShiftModifier) {
2361 incr = WHEEL_INCR_SHIFT;
2362 } else if(mods & Qt::MetaModifier) {
2363 // TODO: do we want/need another step-size?
2364 // incr = WHEEL_INCR_META;
2365 }
2366 }
2367 else
2368 myEvent = false;
2369
2370 if (myEvent) {
2371 // process scroll event myself
2372 incr = settings().wheel_increments[incr];
2373 if (incr != 0) {
2374 bool save = fine;
2375 // use fine positioning if incr is small
2376 fine = (incr < 0 ? -incr : incr) < settings().wheel_threshold;
2377 // Note: delta is a multiple of 120 (see Qt documentation)
2378 int newpos = curpic - (delta * incr) / settings().wheel_delta;
2379 if (newpos < 0)
2380 newpos = 0;
2381 else if (newpos >= pictures)
2382 newpos = pictures - 1;
2383 ui->linslider->setValue(newpos);
2384 fine = save;
2385 }
2386 return true;
2387 }
2388
2389 // propagate to base class
2390 return QMainWindow::eventFilter(watched, e);
2391 }
2392
2393 /*virtual*/
2394 void dvbcut::wheelEvent(QWheelEvent* event)
2395 {
2396 eventFilter(NULL, event);
2397 }
2398
2399 int
2400 dvbcut::question(const QString & caption, const QString & text)
2401 {
2402 if (nogui) {
2403 //: Question during batch processing - print the prompt and tell the user that you assume the answer is No.
2404 fprintf(stderr, "%s", tr("%1\n%2\n(assuming No)\n").arg(caption, text).toLatin1().data());
2405 return QMessageBox::No;
2406 }
2407 return QMessageBox::question(this, caption, text, QMessageBox::Yes,
2408 QMessageBox::No | QMessageBox::Default | QMessageBox::Escape);
2409 }
2410
2411 int
2412 dvbcut::critical(const QString & caption, const std::string & text) {
2413 return critical(caption, QString::fromStdString(text));
2414 }
2415
2416 int
2417 dvbcut::critical(const QString & caption, const QString & text)
2418 {
2419 if (nogui) {
2420 //: Error during batch processing - print text and tell the user you're aborting the batch
2421 fprintf(stderr, "%s", tr("%1\n%2\n(aborting)\n").arg(caption, text).toLatin1().data());
2422 return QMessageBox::Abort;
2423 }
2424 return QMessageBox::critical(this, caption, text,
2425 QMessageBox::Abort, QMessageBox::NoButton);
2426 }
2427
2428 void
2429 dvbcut::make_canonical(std::string &filename) {
2430 if (filename[0] != '/') {
2431 char *rp = realpath(filename.c_str(), NULL);
2432 if (rp)
2433 filename = rp;
2434 free(rp);
2435 }
2436 }
2437
2438 void
2439 dvbcut::make_canonical(std::list<std::string> &filenames) {
2440 std::list<std::string>::const_iterator it = filenames.begin();
2441 std::list<std::string> newlist;
2442
2443 while (it != filenames.end()) {
2444 std::string tmp = *it;
2445 make_canonical(tmp);
2446 newlist.push_back(tmp);
2447 ++it;
2448 }
2449 filenames = newlist;
2450 }
2451
2452 inline static QString
2453 timestr(pts_t pts) {
2454 return QString().asprintf("%02d:%02d:%02d.%03d",
2455 int(pts/(3600*90000)),
2456 int(pts/(60*90000))%60,
2457 int(pts/90000)%60,
2458 int(pts/90)%1000);
2459 }
2460
2461 void dvbcut::update_time_display()
2462 {
2463 const index::picture &idx=(*mpg)[curpic];
2464 const pts_t pts=idx.getpts()-firstpts;
2465 const char *AR[]={"forbidden","1:1","4:3","16:9","2.21:1","reserved"};
2466 const char *FR[]={"forbidden","23.976","24","25","29.97","30","50","59.94","60","reserved"};
2467
2468 int outpic=0;
2469 pts_t outpts=0;
2470 QChar mark = ' ';
2471
2472 // find the entry in the quick_picture_lookup table that corresponds to curpic
2473 quick_picture_lookup_t::iterator it=
2474 std::upper_bound(quick_picture_lookup.begin(),quick_picture_lookup.end(),curpic,quick_picture_lookup_s::cmp_picture());
2475
2476 if (it!=quick_picture_lookup.begin())
2477 {
2478 // curpic is not before the first entry of the table
2479 --it;
2480 if (curpic < it->stoppicture)
2481 {
2482 // curpic is between (START and STOP[ pics of the current entry
2483 outpic=curpic-it->stoppicture+it->outpicture;
2484 outpts=pts-it->stoppts+it->outpts;
2485 mark = '*';
2486 }
2487 else
2488 {
2489 // curpic is after the STOP-1 pic of the current entry
2490 outpic=it->outpicture;
2491 outpts=it->outpts;
2492 }
2493 }
2494
2495 QString curtime =
2496 QString(QChar(IDX_PICTYPE[idx.getpicturetype()]))
2497 + " " + timestr(pts);
2498 QString outtime =
2499 QString(mark) + " " + timestr(outpts);
2500 ui->pictimelabel->setText(curtime);
2501 ui->pictimelabel2->setText(outtime);
2502 ui->goinput->setText(QString::number(curpic));
2503 ui->goinput2->setText(QString::number(outpic));
2504
2505 int res=idx.getresolution(); // are found video resolutions stored in index?
2506 if (res) {
2507 // new index with resolution bits set and lookup table at the end
2508 ui->picinfolabel->setText(QString::number(mpg->getwidth(res)) + "x"
2509 + QString::number(mpg->getheight(res)));
2510 } else {
2511 // in case of an old index file type (or if we don't want to change the index format/encoding?)
2512 // ==> get info directly from each image (which could be somewhat slower?!?)
2513 QImage p = imageprovider(*mpg, new dvbcutbusy(this), true).getimage(curpic,false);
2514 ui->picinfolabel->setText(QString::number(p.width()) + "x"
2515 + QString::number(p.height()));
2516 }
2517 ui->picinfolabel2->setText(QString(FR[idx.getframerate()]) + "fps, "
2518 + QString(AR[idx.getaspectratio()]));
2519
2520 }
2521
2522 void dvbcut::update_quick_picture_lookup_table() {
2523 // that's the (only) place where the event list should be scanned for
2524 // the exported pictures ranges, i.e. for START/STOP/CHAPTER markers!
2525 quick_picture_lookup.clear();
2526 chapterlist.clear();
2527
2528 chapterlist.push_back(0);
2529
2530 int startpic, stoppic, outpics=0, lastchapter=-2;
2531 pts_t startpts, stoppts, outpts=0;
2532 bool realzero=false;
2533
2534 if(!nogui) {
2535 // overwrite CLI options
2536 start_bof = settings().start_bof;
2537 stop_eof = settings().stop_eof;
2538 }
2539
2540 if (start_bof) {
2541 startpic=0;
2542 startpts=(*mpg)[0].getpts()-firstpts;
2543 }
2544 else {
2545 startpic=-1;
2546 startpts=0;
2547 }
2548
2549 int index;
2550 for (index = 0; index < ui->eventlist->count(); index++)
2551 {
2552 EventListItem *item = dynamic_cast<EventListItem *>(ui->eventlist->item(index));
2553 if (item) {
2554 const EventListItem &eli=*static_cast<const EventListItem*>(item);
2555 switch (eli.geteventtype()) {
2556 case EventListItem::start:
2557 if (startpic<0 || (start_bof && startpic==0 && !realzero)) {
2558 startpic=eli.getpicture();
2559 startpts=eli.getpts();
2560 if (startpic==0)
2561 realzero=true;
2562 // did we have a chapter in the eventlist directly before?
2563 if(lastchapter==startpic)
2564 chapterlist.push_back(outpts);
2565 }
2566 break;
2567 case EventListItem::stop:
2568 if (startpic>=0) {
2569 stoppic=eli.getpicture();
2570 stoppts=eli.getpts();
2571 outpics+=stoppic-startpic;
2572 outpts+=stoppts-startpts;
2573
2574 quick_picture_lookup.push_back(quick_picture_lookup_s(startpic,startpts,stoppic,stoppts,outpics,outpts));
2575
2576 startpic=-1;
2577 }
2578 break;
2579 case EventListItem::chapter:
2580 lastchapter=eli.getpicture();
2581 if (startpic>=0)
2582 chapterlist.push_back(eli.getpts()-startpts+outpts);
2583 break;
2584 default:
2585 break;
2586 }
2587 }
2588 }
2589
2590 // last item in list was a (real or virtual) START
2591 if (stop_eof && startpic>=0) {
2592 // create a new export range by adding a virtual STOP marker at EOF
2593 stoppic=pictures-1;
2594 stoppts=(*mpg)[stoppic].getpts()-firstpts;
2595 outpics+=stoppic-startpic;
2596 outpts+=stoppts-startpts;
2597
2598 quick_picture_lookup.push_back(quick_picture_lookup_s(startpic,startpts,stoppic,stoppts,outpics,outpts));
2599 }
2600
2601 update_time_display();
2602 }
2603
2604 void dvbcut::helpAboutAction_activated()
2605 {
2606 QMessageBox::about(this, tr("dvbcut"),
2607 tr("<head></head><body><span style=\"font-family: Helvetica,Arial,sans-serif;\">"
2608 "<p>Version %1</p>"
2609 "<a href=\"https://github.com/bernhardu/dvbcut-deb\">Git source repository.</a></p>"
2610 "<p>This program is free software; you can redistribute it and/or "
2611 "modify it under the terms of the GNU General Public License as "
2612 "published by the Free Software Foundation; either version 2 of "
2613 "the License, or (at your option) any later version. This "
2614 "program is distributed in the hope that it will be useful, "
2615 "but WITHOUT ANY WARRANTY; without even the implied warranty of "
2616 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU "
2617 "General Public License for more details.</p>"
2618 "<p>You should have received a copy of the GNU General Public License along "
2619 "with this program; if not, see "
2620 "<a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a>.</p>"
2621 "</span></body></html>").arg(VERSION_STRING));
2622 }
2623
2624 #include <QHBoxLayout>
2625 #include <QVBoxLayout>
2626 #include <qdialog.h>
2627 #include <qtextbrowser.h>
2628 #include <qpushbutton.h>
2629
2630 class helpDialog : public QDialog {
2631 public:
2632 helpDialog(QWidget *parent, QString file)
2633 : QDialog(parent)
2634 {
2635 prev = new QPushButton(tr("Prev"));
2636 next = new QPushButton(tr("Next"));
2637 home = new QPushButton(tr("Home"));
2638 close = new QPushButton(tr("Close"));
2639 viewer = new QTextBrowser();
2640
2641 hbox = new QHBoxLayout();
2642 hbox->addWidget(prev);
2643 hbox->addWidget(next);
2644 hbox->addWidget(home);
2645 hbox->addWidget(close);
2646
2647 QWidget *hboxw = new QWidget();
2648 hboxw->setLayout(hbox);
2649
2650 vbox = new QVBoxLayout();
2651 vbox->addWidget(viewer);
2652 vbox->addWidget(hboxw);
2653 setLayout(vbox);
2654 resize(640, 480);
2655
2656 close->setDefault(true);
2657 connect(prev, SIGNAL(clicked()), viewer, SLOT(backward()));
2658 connect(viewer, SIGNAL(backwardAvailable(bool)), prev, SLOT(setEnabled(bool)));
2659 connect(next, SIGNAL(clicked()), viewer, SLOT(forward()));
2660 connect(viewer, SIGNAL(forwardAvailable(bool)), next, SLOT(setEnabled(bool)));
2661 connect(home, SIGNAL(clicked()), viewer, SLOT(home()));
2662 connect(close, SIGNAL(clicked()), this, SLOT(accept()));
2663 viewer->setSource(file);
2664 setWindowTitle(tr("dvbcut help"));
2665 show();
2666 }
2667 virtual ~helpDialog() {
2668 delete prev;
2669 delete next;
2670 delete home;
2671 delete close;
2672 delete hbox;
2673 delete viewer;
2674 delete vbox;
2675 }
2676 private:
2677 QVBoxLayout *vbox;
2678 QHBoxLayout *hbox;
2679 QTextBrowser *viewer;
2680 QPushButton *prev, *next, *home, *close;
2681 };
2682
2683 static QString get_help_file(QString locale)
2684 {
2685 QString file = QString("/dvbcut_%1.html").arg(locale);
2686
2687 return get_resource(file);
2688 }
2689
2690 void dvbcut::helpContentAction_activated()
2691 {
2692 QString locale = QLocale::system().name();
2693
2694 QString helpFile = get_help_file(locale);
2695
2696 if (!QFile::exists(helpFile))
2697 helpFile = get_help_file(locale.left(2));
2698
2699 if (!QFile::exists(helpFile))
2700 helpFile = get_help_file("en");
2701
2702 if (QFile::exists(helpFile)) {
2703 helpDialog dlg(this, helpFile);
2704 dlg.exec();
2705 }
2706 else {
2707 QMessageBox::information(this, tr("dvbcut"),
2708 tr("Help file %1 not available").arg(helpFile));
2709 }
2710 }
2711
2712 void dvbcut::gotoFrame(int frameno)
2713 {
2714 bool save = fine;
2715 fine = true;
2716 ui->linslider->setValue(frameno);
2717 fine = save;
2718 }