MythTV master
mythtranscode.cpp
Go to the documentation of this file.
1// C++ headers
2#include <cerrno>
3#include <fcntl.h> // for open flags
4#include <fstream>
5#include <iostream>
6#include <thread>
7
8// Qt headers
9#include <QtGlobal>
10#include <QCoreApplication>
11#include <QDir>
12#include <utility>
13
14// MythTV headers
15#include "libmyth/mythcontext.h"
20#include "libmythbase/mythdb.h"
24#include "libmythbase/mythversion.h"
26#include "libmythtv/jobqueue.h"
29
30// MythTranscode
31#include "mpeg2fix.h"
33#include "transcode.h"
34
35static void CompleteJob(int jobID, ProgramInfo *pginfo, bool useCutlist,
36 frm_dir_map_t *deleteMap, int &exitCode,
37 int resultCode, bool forceDelete);
38
39static int glbl_jobID = -1;
40static QString recorderOptions = "";
41
42static void UpdatePositionMap(frm_pos_map_t &posMap, frm_pos_map_t &durMap, const QString& mapfile,
43 ProgramInfo *pginfo)
44{
45 if (pginfo && mapfile.isEmpty())
46 {
49 pginfo->SavePositionMap(posMap, MARK_GOP_BYFRAME);
50 pginfo->SavePositionMap(durMap, MARK_DURATION_MS);
51 }
52 else if (!mapfile.isEmpty())
53 {
55 FILE *mapfh = fopen(mapfile.toLocal8Bit().constData(), "w");
56 if (!mapfh)
57 {
58 LOG(VB_GENERAL, LOG_ERR, QString("Could not open map file '%1'")
59 .arg(mapfile) + ENO);
60 return;
61 }
62 frm_pos_map_t::const_iterator it;
63 fprintf (mapfh, "Type: %d\n", keyType);
64 for (it = posMap.cbegin(); it != posMap.cend(); ++it)
65 {
66 QString str = QString("%1 %2\n").arg(it.key()).arg(*it);
67 fprintf(mapfh, "%s", qPrintable(str));
68 }
69 fclose(mapfh);
70 }
71}
72
73static int BuildKeyframeIndex(MPEG2fixup *m2f, const QString &infile,
74 frm_pos_map_t &posMap, frm_pos_map_t &durMap, int jobID)
75{
76 if (!m2f)
77 return 0;
78
80 {
81 if (jobID >= 0)
83 QObject::tr("Generating Keyframe Index"));
84 int err = m2f->BuildKeyframeIndex(infile, posMap, durMap);
85 if (err)
86 return err;
87 if (jobID >= 0)
89 QObject::tr("Transcode Completed"));
90 }
91 return 0;
92}
93
94static void UpdateJobQueue(float percent_done)
95{
97 QString("%1% ").arg(percent_done, 0, 'f', 1) +
98 QObject::tr("Completed"));
99}
100
101static int CheckJobQueue()
102{
104 {
105 LOG(VB_GENERAL, LOG_NOTICE, "Transcoding stopped by JobQueue");
106 return 1;
107 }
108 return 0;
109}
110
111static int QueueTranscodeJob(ProgramInfo *pginfo, const QString& profile,
112 const QString& hostname, bool usecutlist)
113{
114 if (!profile.isEmpty())
115 {
116 RecordingInfo recinfo(*pginfo);
118 }
119
121 pginfo->GetRecordingStartTime(),
122 hostname, "", "",
123 usecutlist ? JOB_USE_CUTLIST : 0))
124 {
125 LOG(VB_GENERAL, LOG_NOTICE,
126 QString("Queued transcode job for chanid %1 @ %2")
127 .arg(pginfo->GetChanID())
129 return GENERIC_EXIT_OK;
130 }
131
132 LOG(VB_GENERAL, LOG_ERR, QString("Error queuing job for chanid %1 @ %2")
133 .arg(pginfo->GetChanID())
136}
137
138int main(int argc, char *argv[])
139{
140 uint chanid = 0;
141 QDateTime starttime;
142 QString infile;
143 QString outfile;
144 QString profilename = QString("autodetect");
145 QString fifodir = nullptr;
146 int jobID = -1;
147 int jobType = JOB_NONE;
148 int otype = REPLEX_MPEG2;
149 bool useCutlist = false;
150 bool keyframesonly = false;
151 bool build_index = false;
152 bool fifosync = false;
153 bool mpeg2 = false;
154 bool fifo_info = false;
155 bool cleanCut = false;
156 frm_dir_map_t deleteMap;
157 frm_pos_map_t posMap;
158 frm_pos_map_t durMap;
159 int AudioTrackNo = -1;
160
161 bool found_starttime = false;
162 bool found_chanid = false;
163 bool found_infile = false;
164 int update_index = 1;
165 bool isVideo = false;
166 bool passthru = false;
167
169 if (!cmdline.Parse(argc, argv))
170 {
173 }
174
175 if (cmdline.toBool("showhelp"))
176 {
178 return GENERIC_EXIT_OK;
179 }
180
181 if (cmdline.toBool("showversion"))
182 {
184 return GENERIC_EXIT_OK;
185 }
186
187 QCoreApplication a(argc, argv);
188 QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHTRANSCODE);
189
190 if (cmdline.toBool("outputfile"))
191 {
192 outfile = cmdline.toString("outputfile");
193 update_index = 0;
194 }
195
196 bool showprogress = cmdline.toBool("showprogress");
197
198 QString mask("general");
199 bool quiet = (outfile == "-") || showprogress;
200 int retval = cmdline.ConfigureLogging(mask, quiet);
201 if (retval != GENERIC_EXIT_OK)
202 return retval;
203
204 if (cmdline.toBool("starttime"))
205 {
206 starttime = cmdline.toDateTime("starttime");
207 found_starttime = true;
208 }
209 if (cmdline.toBool("chanid"))
210 {
211 chanid = cmdline.toUInt("chanid");
212 found_chanid = true;
213 }
214 if (cmdline.toBool("jobid"))
215 jobID = cmdline.toInt("jobid");
216 if (cmdline.toBool("inputfile"))
217 {
218 infile = cmdline.toString("inputfile");
219 found_infile = true;
220 }
221 if (cmdline.toBool("video"))
222 isVideo = true;
223 if (cmdline.toBool("profile"))
224 profilename = cmdline.toString("profile");
225
226 if (cmdline.toBool("usecutlist"))
227 {
228 useCutlist = true;
229 if (!cmdline.toString("usecutlist").isEmpty())
230 {
231 if (!cmdline.toBool("inputfile"))
232 {
233 LOG(VB_GENERAL, LOG_CRIT, "External cutlists are only allowed "
234 "when using the --infile option.");
236 }
237
238 uint64_t last = 0;
239 QStringList cutlist = cmdline.toStringList("usecutlist", " ");
240 for (const auto & cut : std::as_const(cutlist))
241 {
242 QStringList startend = cut.split("-", Qt::SkipEmptyParts);
243 if (startend.size() == 2)
244 {
245 uint64_t start = startend.first().toULongLong();
246 uint64_t end = startend.last().toULongLong();
247
248 if (cmdline.toBool("inversecut"))
249 {
250 LOG(VB_GENERAL, LOG_DEBUG,
251 QString("Cutting section %1-%2.")
252 .arg(last).arg(start));
253 deleteMap[start] = MARK_CUT_END;
254 deleteMap[end] = MARK_CUT_START;
255 last = end;
256 }
257 else
258 {
259 LOG(VB_GENERAL, LOG_DEBUG,
260 QString("Cutting section %1-%2.")
261 .arg(start).arg(end));
262 deleteMap[start] = MARK_CUT_START;
263 deleteMap[end] = MARK_CUT_END;
264 }
265 }
266 }
267
268 if (cmdline.toBool("inversecut"))
269 {
270 if (deleteMap.contains(0) && (deleteMap[0] == MARK_CUT_END))
271 deleteMap.remove(0);
272 else
273 deleteMap[0] = MARK_CUT_START;
274 deleteMap[999999999] = MARK_CUT_END;
275 LOG(VB_GENERAL, LOG_DEBUG,
276 QString("Cutting section %1-999999999.")
277 .arg(last));
278 }
279
280 // sanitize cutlist
281 if (deleteMap.count() >= 2)
282 {
283 frm_dir_map_t::iterator cur = deleteMap.begin();
284 frm_dir_map_t::iterator prev;
285 prev = cur++;
286 while (cur != deleteMap.end())
287 {
288 if (prev.value() == cur.value())
289 {
290 // two of the same type next to each other
291 QString err("Cut %1points found at %3 and %4, with no "
292 "%2 point in between.");
293 if (prev.value() == MARK_CUT_END)
294 err = err.arg("end", "start");
295 else
296 err = err.arg("start", "end");
297 LOG(VB_GENERAL, LOG_CRIT, "Invalid cutlist defined!");
298 LOG(VB_GENERAL, LOG_CRIT, err.arg(prev.key())
299 .arg(cur.key()));
301 }
302 if ( (prev.value() == MARK_CUT_START) &&
303 ((cur.key() - prev.key()) < 2) )
304 {
305 LOG(VB_GENERAL, LOG_WARNING, QString("Discarding "
306 "insufficiently long cut: %1-%2")
307 .arg(prev.key()).arg(cur.key()));
308 prev = deleteMap.erase(prev);
309 cur = deleteMap.erase(cur);
310
311 if (cur == deleteMap.end())
312 continue;
313 }
314 prev = cur++;
315 }
316 }
317 }
318 else if (cmdline.toBool("inversecut"))
319 {
320 std::cerr << "Cutlist inversion requires an external cutlist be\n"
321 << "provided using the --honorcutlist option.\n";
323 }
324 }
325
326 if (cmdline.toBool("cleancut"))
327 cleanCut = true;
328
329 if (cmdline.toBool("allkeys"))
330 keyframesonly = true;
331 if (cmdline.toBool("reindex"))
332 build_index = true;
333 if (cmdline.toBool("fifodir"))
334 fifodir = cmdline.toString("fifodir");
335 if (cmdline.toBool("fifoinfo"))
336 fifo_info = true;
337 if (cmdline.toBool("fifosync"))
338 fifosync = true;
339 if (cmdline.toBool("recopt"))
340 recorderOptions = cmdline.toString("recopt");
341 if (cmdline.toBool("mpeg2"))
342 mpeg2 = true;
343 if (cmdline.toBool("ostream"))
344 {
345 if (cmdline.toString("ostream") == "dvd") {
346 otype = REPLEX_DVD;
347 } else if (cmdline.toString("ostream") == "ps") {
348 otype = REPLEX_MPEG2;
349 } else if (cmdline.toString("ostream") == "ts") {
350 otype = REPLEX_TS_SD;
351 } else {
352 std::cerr << "Invalid 'ostream' type: "
353 << cmdline.toString("ostream").toLocal8Bit().constData()
354 << '\n';
356 }
357 }
358 if (cmdline.toBool("audiotrack"))
359 AudioTrackNo = cmdline.toInt("audiotrack");
360 if (cmdline.toBool("passthru"))
361 passthru = true;
362 // Set if we want to delete the original file once conversion succeeded.
363 bool deleteOriginal = cmdline.toBool("delete");
364
365 // Load the context
366 MythContext context {MYTH_BINARY_VERSION};
367 if (!context.Init(false))
368 {
369 LOG(VB_GENERAL, LOG_ERR, "Failed to init MythContext, exiting.");
371 }
372
373 MythTranslation::load("mythfrontend");
374
376
377 if (jobID != -1)
378 {
379 if (JobQueue::GetJobInfoFromID(jobID, jobType, chanid, starttime))
380 {
381 found_starttime = true;
382 found_chanid = true;
383 }
384 else
385 {
386 std::cerr << "mythtranscode: ERROR: Unable to find DB info for "
387 << "JobQueue ID# " << jobID << '\n';
389 }
390 }
391
392 if (((!found_infile && !(found_chanid && found_starttime)) ||
393 (found_infile && (found_chanid || found_starttime))))
394 {
395 std::cerr << "Must specify -i OR -c AND -s options!\n";
397 }
398 if (isVideo && !found_infile)
399 {
400 std::cerr << "Must specify --infile to use --video\n";
402 }
403 if (jobID >= 0 && (found_infile || build_index))
404 {
405 std::cerr << "Can't specify -j with --buildindex, --video or --infile\n";
407 }
408 if ((jobID >= 0) && build_index)
409 {
410 std::cerr << "Can't specify both -j and --buildindex\n";
412 }
413 if (keyframesonly && !fifodir.isEmpty())
414 {
415 std::cerr << "Cannot specify both --fifodir and --allkeys\n";
417 }
418 if (fifosync && fifodir.isEmpty())
419 {
420 std::cerr << "Must specify --fifodir to use --fifosync\n";
422 }
423 if (fifo_info && !fifodir.isEmpty())
424 {
425 std::cerr << "Cannot specify both --fifodir and --fifoinfo\n";
427 }
428 if (cleanCut && fifodir.isEmpty() && !fifo_info)
429 {
430 std::cerr << "Clean cutting works only in fifodir mode\n";
432 }
433 if (cleanCut && !useCutlist)
434 {
435 std::cerr << "--cleancut is pointless without --honorcutlist\n";
437 }
438
439 if (fifo_info)
440 {
441 // Setup a dummy fifodir path, so that the "fifodir" code path
442 // is taken. The path wont actually be used.
443 fifodir = "DummyFifoPath";
444 }
445
447 {
448 LOG(VB_GENERAL, LOG_ERR, "couldn't open db");
450 }
451
452 ProgramInfo *pginfo = nullptr;
453 if (isVideo)
454 {
455 // We want the absolute file path for the filemarkup table
456 QFileInfo inf(infile);
457 infile = inf.absoluteFilePath();
458 pginfo = new ProgramInfo(infile);
459 }
460 else if (!found_infile)
461 {
462 pginfo = new ProgramInfo(chanid, starttime);
463
464 if (!pginfo->GetChanID())
465 {
466 LOG(VB_GENERAL, LOG_ERR,
467 QString("Couldn't find recording for chanid %1 @ %2")
468 .arg(chanid).arg(starttime.toString(Qt::ISODate)));
469 delete pginfo;
471 }
472
473 infile = pginfo->GetPlaybackURL(false, true);
474 }
475 else
476 {
477 pginfo = new ProgramInfo(infile);
478 if (!pginfo->GetChanID())
479 {
480 LOG(VB_GENERAL, LOG_ERR,
481 QString("Couldn't find a recording for filename '%1'")
482 .arg(infile));
483 delete pginfo;
485 }
486 }
487
488 if (!pginfo)
489 {
490 LOG(VB_GENERAL, LOG_ERR, "No program info found!");
492 }
493
494 if (cmdline.toBool("queue"))
495 {
496 QString hostname = cmdline.toString("queue");
497 return QueueTranscodeJob(pginfo, profilename, hostname, useCutlist);
498 }
499
500 if (infile.startsWith("myth://") && (outfile.isEmpty() || outfile != "-") &&
501 fifodir.isEmpty() && !cmdline.toBool("avf"))
502 {
503 LOG(VB_GENERAL, LOG_ERR,
504 QString("Attempted to transcode %1. Mythtranscode is currently "
505 "unable to transcode remote files.") .arg(infile));
506 delete pginfo;
508 }
509
510 if (outfile.isEmpty() && !build_index && fifodir.isEmpty())
511 outfile = infile + ".tmp";
512
513 if (jobID >= 0)
514 JobQueue::ChangeJobStatus(jobID, JOB_RUNNING);
515
516 auto *transcode = new Transcode(pginfo);
517
518 if (!build_index)
519 {
520 if (fifodir.isEmpty())
521 {
522 LOG(VB_GENERAL, LOG_NOTICE, QString("Transcoding from %1 to %2")
523 .arg(infile, outfile));
524 }
525 else
526 {
527 LOG(VB_GENERAL, LOG_NOTICE, QString("Transcoding from %1 to FIFO")
528 .arg(infile));
529 }
530 }
531
532 if (cmdline.toBool("avf"))
533 {
534 transcode->SetAVFMode();
535
536 if (cmdline.toBool("container"))
537 transcode->SetCMDContainer(cmdline.toString("container"));
538 if (cmdline.toBool("acodec"))
539 transcode->SetCMDAudioCodec(cmdline.toString("acodec"));
540 if (cmdline.toBool("vcodec"))
541 transcode->SetCMDVideoCodec(cmdline.toString("vcodec"));
542 }
543
544 if (cmdline.toBool("avf"))
545 {
546 if (cmdline.toBool("width"))
547 transcode->SetCMDWidth(cmdline.toInt("width"));
548 if (cmdline.toBool("height"))
549 transcode->SetCMDHeight(cmdline.toInt("height"));
550 if (cmdline.toBool("bitrate"))
551 transcode->SetCMDBitrate(cmdline.toInt("bitrate") * 1000);
552 if (cmdline.toBool("audiobitrate"))
553 transcode->SetCMDAudioBitrate(cmdline.toInt("audiobitrate") * 1000);
554 }
555
556 if (!cmdline.toBool("avf") && fifodir.isEmpty())
557 {
558 mpeg2 = true;
559 }
560
561 if (showprogress)
562 transcode->ShowProgress(true);
563 if (!recorderOptions.isEmpty())
564 transcode->SetRecorderOptions(recorderOptions);
565 int result = 0;
566 if ((!mpeg2 && !build_index))
567 {
568 result = transcode->TranscodeFile(infile, outfile,
569 profilename, useCutlist,
570 (fifosync || keyframesonly), jobID,
571 fifodir, fifo_info, cleanCut, deleteMap,
572 AudioTrackNo, passthru);
573
574 if ((result == REENCODE_OK) && (jobID >= 0))
575 {
576 JobQueue::ChangeJobArgs(jobID, "RENAME_TO_NUV");
577 RecordingInfo recInfo(pginfo->GetRecordingID());
578 RecordingFile *recFile = recInfo.GetRecordingFile();
579 recFile->m_containerFormat = formatNUV;
580 recFile->Save();
581 }
582 }
583
584 if (fifo_info)
585 {
586 delete transcode;
587 return GENERIC_EXIT_OK;
588 }
589
590 int exitcode = GENERIC_EXIT_OK;
591 if (mpeg2 || build_index)
592 {
593 void (*update_func)(float) = nullptr;
594 int (*check_func)() = nullptr;
595 if (useCutlist)
596 {
597 LOG(VB_GENERAL, LOG_INFO, "Honoring the cutlist while transcoding");
598 if (deleteMap.isEmpty())
599 pginfo->QueryCutList(deleteMap);
600 }
601 if (jobID >= 0)
602 {
604 update_func = &UpdateJobQueue;
605 check_func = &CheckJobQueue;
606 }
607
608 auto *m2f = new MPEG2fixup(infile, outfile,
609 &deleteMap, nullptr, false, false, 20,
610 showprogress, otype, update_func,
611 check_func);
612
613 if (cmdline.toBool("allaudio"))
614 {
615 m2f->SetAllAudio(true);
616 }
617
618 if (build_index)
619 {
620 int err = BuildKeyframeIndex(m2f, infile, posMap, durMap, jobID);
621 if (err)
622 {
623 delete m2f;
624 m2f = nullptr;
625 return err;
626 }
627 if (update_index)
628 UpdatePositionMap(posMap, durMap, nullptr, pginfo);
629 else
630 UpdatePositionMap(posMap, durMap, outfile + QString(".map"), pginfo);
631 }
632 else
633 {
634 result = m2f->Start();
635 if (result == REENCODE_OK)
636 {
637 result = BuildKeyframeIndex(m2f, outfile, posMap, durMap, jobID);
638 if (result == REENCODE_OK)
639 {
640 if (update_index)
641 UpdatePositionMap(posMap, durMap, nullptr, pginfo);
642 else
643 UpdatePositionMap(posMap, durMap, outfile + QString(".map"),
644 pginfo);
645 }
646 RecordingInfo recInfo(*pginfo);
647 RecordingFile *recFile = recInfo.GetRecordingFile();
648 if (otype == REPLEX_DVD || otype == REPLEX_MPEG2 ||
649 otype == REPLEX_HDTV)
650 {
652 JobQueue::ChangeJobArgs(jobID, "RENAME_TO_MPG");
653 }
654 else
655 {
657 }
658 recFile->Save();
659 }
660 }
661 delete m2f;
662 m2f = nullptr;
663 }
664
665 if (result == REENCODE_OK)
666 {
667 if (jobID >= 0)
668 JobQueue::ChangeJobStatus(jobID, JOB_STOPPING);
669 LOG(VB_GENERAL, LOG_NOTICE, QString("%1 %2 done")
670 .arg(build_index ? "Building Index for" : "Transcoding", infile));
671 }
672 else if (result == REENCODE_CUTLIST_CHANGE)
673 {
674 if (jobID >= 0)
676 LOG(VB_GENERAL, LOG_NOTICE,
677 QString("Transcoding %1 aborted because of cutlist update")
678 .arg(infile));
679 exitcode = GENERIC_EXIT_RESTART;
680 }
681 else if (result == REENCODE_STOPPED)
682 {
683 if (jobID >= 0)
684 JobQueue::ChangeJobStatus(jobID, JOB_ABORTING);
685 LOG(VB_GENERAL, LOG_NOTICE,
686 QString("Transcoding %1 stopped because of stop command")
687 .arg(infile));
688 exitcode = GENERIC_EXIT_KILLED;
689 }
690 else
691 {
692 if (jobID >= 0)
693 JobQueue::ChangeJobStatus(jobID, JOB_ERRORING);
694 LOG(VB_GENERAL, LOG_ERR, QString("Transcoding %1 failed").arg(infile));
695 exitcode = result;
696 }
697
698 if (deleteOriginal || jobID >= 0)
699 CompleteJob(jobID, pginfo, useCutlist, &deleteMap, exitcode, result, deleteOriginal);
700
701 transcode->deleteLater();
702
703 return exitcode;
704}
705
706static int transUnlink(const QString& filename, ProgramInfo *pginfo)
707{
708 QString hostname = pginfo->GetHostname();
709
710 if (!pginfo->GetStorageGroup().isEmpty() &&
711 !hostname.isEmpty())
712 {
714 QString basename = filename.section('/', -1);
715 QString uri = MythCoreContext::GenMythURL(hostname, port, basename,
716 pginfo->GetStorageGroup());
717
718 LOG(VB_GENERAL, LOG_NOTICE, QString("Requesting delete for file '%1'.")
719 .arg(uri));
720 bool ok = RemoteFile::DeleteFile(uri);
721 if (ok)
722 return 0;
723 }
724
725 LOG(VB_GENERAL, LOG_NOTICE, QString("Deleting file '%1'.").arg(filename));
726 return unlink(filename.toLocal8Bit().constData());
727}
728
729static uint64_t ComputeNewBookmark(uint64_t oldBookmark,
730 frm_dir_map_t *deleteMap)
731{
732 if (deleteMap == nullptr)
733 return oldBookmark;
734
735 uint64_t subtraction = 0;
736 uint64_t startOfCutRegion = 0;
737 frm_dir_map_t delMap = *deleteMap;
738 bool withinCut = false;
739 bool firstMark = true;
740 while (!delMap.empty() && delMap.begin().key() <= oldBookmark)
741 {
742 uint64_t key = delMap.begin().key();
743 MarkTypes mark = delMap.begin().value();
744
745 if (mark == MARK_CUT_START && !withinCut)
746 {
747 withinCut = true;
748 startOfCutRegion = key;
749 }
750 else if (mark == MARK_CUT_END && firstMark)
751 {
752 subtraction += key;
753 }
754 else if (mark == MARK_CUT_END && withinCut)
755 {
756 withinCut = false;
757 subtraction += (key - startOfCutRegion);
758 }
759 delMap.remove(key);
760 firstMark = false;
761 }
762 if (withinCut)
763 subtraction += (oldBookmark - startOfCutRegion);
764 return oldBookmark - subtraction;
765}
766
767static uint64_t ReloadBookmark(ProgramInfo *pginfo)
768{
770 uint64_t currentBookmark = 0;
771 query.prepare("SELECT DISTINCT mark FROM recordedmarkup "
772 "WHERE chanid = :CHANID "
773 "AND starttime = :STARTIME "
774 "AND type = :MARKTYPE ;");
775 query.bindValue(":CHANID", pginfo->GetChanID());
776 query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
777 query.bindValue(":MARKTYPE", MARK_BOOKMARK);
778 if (query.exec() && query.next())
779 {
780 currentBookmark = query.value(0).toLongLong();
781 }
782 return currentBookmark;
783}
784
785static void WaitToDelete(ProgramInfo *pginfo)
786{
787 LOG(VB_GENERAL, LOG_NOTICE,
788 "Transcode: delete old file: waiting while program is in use.");
789
790 bool inUse = true;
792 while (inUse)
793 {
794 query.prepare("SELECT count(*) FROM inuseprograms "
795 "WHERE chanid = :CHANID "
796 "AND starttime = :STARTTIME "
797 "AND recusage = 'player' ;");
798 query.bindValue(":CHANID", pginfo->GetChanID());
799 query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
800 if (!query.exec() || !query.next())
801 {
802 LOG(VB_GENERAL, LOG_ERR,
803 "Transcode: delete old file: in-use query failed;");
804 inUse = false;
805 }
806 else
807 {
808 inUse = (query.value(0).toUInt() != 0);
809 }
810
811 if (inUse)
812 {
813 constexpr std::chrono::seconds kSecondsToWait = 10s;
814 LOG(VB_GENERAL, LOG_NOTICE,
815 QString("Transcode: program in use, rechecking in %1 seconds.")
816 .arg(kSecondsToWait.count()));
817 std::this_thread::sleep_for(kSecondsToWait);
818 }
819 }
820 LOG(VB_GENERAL, LOG_NOTICE, "Transcode: program is no longer in use.");
821}
822
823static void CompleteJob(int jobID, ProgramInfo *pginfo, bool useCutlist,
824 frm_dir_map_t *deleteMap, int &exitCode, int resultCode, bool forceDelete)
825{
826 int status = JOB_UNKNOWN;
827 if (jobID >= 0)
829
830 if (!pginfo)
831 {
832 if (jobID >= 0)
833 JobQueue::ChangeJobStatus(jobID, JOB_ERRORED,
834 QObject::tr("Job errored, unable to find Program Info for job"));
835 LOG(VB_GENERAL, LOG_CRIT, "MythTranscode: Cleanup errored, unable to find Program Info");
836 return;
837 }
838
839 const QString filename = pginfo->GetPlaybackURL(false, true);
840 const QByteArray fname = filename.toLocal8Bit();
841
842 if (resultCode == REENCODE_OK)
843 {
844 WaitToDelete(pginfo);
845
846 // Transcoding may take several minutes. Reload the bookmark
847 // in case it changed, then save its translated value back.
848 uint64_t previousBookmark =
849 ComputeNewBookmark(ReloadBookmark(pginfo), deleteMap);
850 pginfo->SaveBookmark(previousBookmark);
851
852 QString jobArgs;
853 if (jobID >= 0)
854 jobArgs = JobQueue::GetJobArgs(jobID);
855
856 const QString tmpfile = filename + ".tmp";
857 const QByteArray atmpfile = tmpfile.toLocal8Bit();
858
859 // To save the original file...
860 const QString oldfile = filename + ".old";
861 const QByteArray aoldfile = oldfile.toLocal8Bit();
862
863 QFileInfo st(tmpfile);
864 qint64 newSize = 0;
865 if (st.exists())
866 newSize = st.size();
867
868 QString cnf = filename;
869 if (jobID >= 0)
870 {
871 if (filename.endsWith(".mpg") && jobArgs == "RENAME_TO_NUV")
872 {
873 QString newbase = pginfo->QueryBasename();
874 cnf.replace(".mpg", ".nuv");
875 newbase.replace(".mpg", ".nuv");
876 pginfo->SaveBasename(newbase);
877 }
878 else if (filename.endsWith(".ts") &&
879 (jobArgs == "RENAME_TO_MPG"))
880 {
881 QString newbase = pginfo->QueryBasename();
882 // MPEG-TS to MPEG-PS
883 cnf.replace(".ts", ".mpg");
884 newbase.replace(".ts", ".mpg");
885 pginfo->SaveBasename(newbase);
886 }
887 }
888
889 const QString newfile = cnf;
890 const QByteArray anewfile = newfile.toLocal8Bit();
891
892 if (rename(fname.constData(), aoldfile.constData()) == -1)
893 {
894 LOG(VB_GENERAL, LOG_ERR,
895 QString("mythtranscode: Error Renaming '%1' to '%2'")
896 .arg(filename, oldfile) + ENO);
897 }
898
899 if (rename(atmpfile.constData(), anewfile.constData()) == -1)
900 {
901 LOG(VB_GENERAL, LOG_ERR,
902 QString("mythtranscode: Error Renaming '%1' to '%2'")
903 .arg(tmpfile, newfile) + ENO);
904 }
905
906 if (!gCoreContext->GetBoolSetting("SaveTranscoding", false) || forceDelete)
907 {
908 bool followLinks =
909 gCoreContext->GetBoolSetting("DeletesFollowLinks", false);
910
911 LOG(VB_FILE, LOG_INFO,
912 QString("mythtranscode: About to unlink/delete file: %1")
913 .arg(oldfile));
914
915 QFileInfo finfo(oldfile);
916 if (followLinks && finfo.isSymLink())
917 {
918 QString link = getSymlinkTarget(oldfile);
919 QByteArray alink = link.toLocal8Bit();
920 int err = transUnlink(alink, pginfo);
921 if (err)
922 {
923 LOG(VB_GENERAL, LOG_ERR,
924 QString("mythtranscode: Error deleting '%1' "
925 "pointed to by '%2'")
926 .arg(alink.constData(), aoldfile.constData()) + ENO);
927 }
928
929 err = unlink(aoldfile.constData());
930 if (err)
931 {
932 LOG(VB_GENERAL, LOG_ERR,
933 QString("mythtranscode: Error deleting '%1', "
934 "a link pointing to '%2'")
935 .arg(aoldfile.constData(), alink.constData()) + ENO);
936 }
937 }
938 else
939 {
940 int err = transUnlink(aoldfile.constData(), pginfo);
941 if (err)
942 {
943 LOG(VB_GENERAL, LOG_ERR,
944 QString("mythtranscode: Error deleting '%1': ")
945 .arg(oldfile) + ENO);
946 }
947 }
948 }
949
950 // Rename or delete all preview thumbnails.
951 //
952 // TODO: This cleanup should be moved to RecordingInfo, and triggered
953 // when SaveBasename() is called
954 QFileInfo fInfo(filename);
955 QStringList nameFilters;
956 nameFilters.push_back(fInfo.fileName() + "*.png");
957 nameFilters.push_back(fInfo.fileName() + "*.jpg");
958
959 QDir dir (fInfo.path());
960 QFileInfoList previewFiles = dir.entryInfoList(nameFilters);
961
962 for (const auto & previewFile : std::as_const(previewFiles))
963 {
964 QString oldFileName = previewFile.absoluteFilePath();
965
966 // Delete previews if cutlist was applied. They will be re-created as
967 // required. This prevents the user from being stuck with a preview
968 // from a cut area and ensures that the "dimensioned" previews
969 // correspond to the new timeline
970 if (useCutlist)
971 {
972 // If unlink fails, keeping the old preview is not a problem.
973 // The RENAME_TO_NUV check below will attempt to rename the
974 // file, if required.
975 if (transUnlink(oldFileName.toLocal8Bit().constData(), pginfo) != -1)
976 continue;
977 }
978
979 if (jobArgs == "RENAME_TO_NUV" || jobArgs == "RENAME_TO_MPG")
980 {
981 QString newExtension = "mpg";
982 if (jobArgs == "RENAME_TO_NUV")
983 newExtension = "nuv";
984
985 QString oldSuffix = previewFile.completeSuffix();
986
987 if (!oldSuffix.startsWith(newExtension))
988 {
989 QString newSuffix = oldSuffix;
990 QString oldExtension = oldSuffix.section(".", 0, 0);
991 newSuffix.replace(oldExtension, newExtension);
992
993 QString newFileName = oldFileName;
994 newFileName.replace(oldSuffix, newSuffix);
995
996 if (!QFile::rename(oldFileName, newFileName))
997 {
998 LOG(VB_GENERAL, LOG_ERR,
999 QString("mythtranscode: Error renaming %1 to %2")
1000 .arg(oldFileName, newFileName));
1001 }
1002 }
1003 }
1004 }
1005
1007
1008 if (useCutlist)
1009 {
1010 query.prepare("DELETE FROM recordedmarkup "
1011 "WHERE chanid = :CHANID "
1012 "AND starttime = :STARTTIME "
1013 "AND type != :BOOKMARK ");
1014 query.bindValue(":CHANID", pginfo->GetChanID());
1015 query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
1016 query.bindValue(":BOOKMARK", MARK_BOOKMARK);
1017
1018 if (!query.exec())
1019 MythDB::DBError("Error in mythtranscode", query);
1020
1021 query.prepare("UPDATE recorded "
1022 "SET cutlist = :CUTLIST "
1023 "WHERE chanid = :CHANID "
1024 "AND starttime = :STARTTIME ;");
1025 query.bindValue(":CUTLIST", "0");
1026 query.bindValue(":CHANID", pginfo->GetChanID());
1027 query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
1028
1029 if (!query.exec())
1030 MythDB::DBError("Error in mythtranscode", query);
1031
1033 }
1034 else
1035 {
1036 query.prepare("DELETE FROM recordedmarkup "
1037 "WHERE chanid = :CHANID "
1038 "AND starttime = :STARTTIME "
1039 "AND type not in ( :COMM_START, "
1040 " :COMM_END, :BOOKMARK, "
1041 " :CUTLIST_START, :CUTLIST_END) ;");
1042 query.bindValue(":CHANID", pginfo->GetChanID());
1043 query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
1044 query.bindValue(":COMM_START", MARK_COMM_START);
1045 query.bindValue(":COMM_END", MARK_COMM_END);
1046 query.bindValue(":BOOKMARK", MARK_BOOKMARK);
1047 query.bindValue(":CUTLIST_START", MARK_CUT_START);
1048 query.bindValue(":CUTLIST_END", MARK_CUT_END);
1049
1050 if (!query.exec())
1051 MythDB::DBError("Error in mythtranscode", query);
1052 }
1053
1054 if (newSize)
1055 pginfo->SaveFilesize(newSize);
1056
1057 if (jobID >= 0)
1058 JobQueue::ChangeJobStatus(jobID, JOB_FINISHED);
1059 }
1060 else
1061 {
1062 // Not a successful run, so remove the files we created
1063 QString filename_tmp = filename + ".tmp";
1064 QByteArray fname_tmp = filename_tmp.toLocal8Bit();
1065 LOG(VB_GENERAL, LOG_NOTICE, QString("Deleting %1").arg(filename_tmp));
1066 transUnlink(fname_tmp.constData(), pginfo);
1067
1068 QString filename_map = filename + ".tmp.map";
1069 QByteArray fname_map = filename_map.toLocal8Bit();
1070 unlink(fname_map.constData());
1071
1072 if (jobID >= 0)
1073 {
1074 if (status == JOB_ABORTING) // Stop command was sent
1075 {
1076 JobQueue::ChangeJobStatus(jobID, JOB_ABORTED,
1077 QObject::tr("Job Aborted"));
1078 }
1079 else if (status != JOB_ERRORING) // Recoverable error
1080 {
1081 exitCode = GENERIC_EXIT_RESTART;
1082 }
1083 else // Unrecoverable error
1084 {
1085 JobQueue::ChangeJobStatus(jobID, JOB_ERRORED,
1086 QObject::tr("Unrecoverable error"));
1087 }
1088 }
1089 }
1090}
1091/* vim: set expandtab tabstop=4 shiftwidth=4: */
static QString GetJobArgs(int jobID)
Definition: jobqueue.cpp:1498
static bool GetJobInfoFromID(int jobID, int &jobType, uint &chanid, QDateTime &recstartts)
Definition: jobqueue.cpp:677
static bool ChangeJobArgs(int jobID, const QString &args="")
Definition: jobqueue.cpp:1047
static enum JobCmds GetJobCmd(int jobID)
Definition: jobqueue.cpp:1477
static bool QueueJob(int jobType, uint chanid, const QDateTime &recstartts, const QString &args="", const QString &comment="", QString host="", int flags=0, int status=JOB_QUEUED, QDateTime schedruntime=QDateTime())
Definition: jobqueue.cpp:520
static bool ChangeJobComment(int jobID, const QString &comment="")
Definition: jobqueue.cpp:1022
static bool ChangeJobStatus(int jobID, int newStatus, const QString &comment="")
Definition: jobqueue.cpp:995
static enum JobStatus GetJobStatus(int jobID)
Definition: jobqueue.cpp:1540
int BuildKeyframeIndex(const QString &file, frm_pos_map_t &posMap, frm_pos_map_t &durMap)
Definition: mpeg2fix.cpp:2891
QSqlQuery wrapper that fetches a DB connection from the connection pool.
Definition: mythdbcon.h:128
bool prepare(const QString &query)
QSqlQuery::prepare() is not thread safe in Qt <= 3.3.2.
Definition: mythdbcon.cpp:838
QVariant value(int i) const
Definition: mythdbcon.h:204
static bool testDBConnection()
Checks DB connection + login (login info via Mythcontext)
Definition: mythdbcon.cpp:877
bool exec(void)
Wrap QSqlQuery::exec() so we can display SQL.
Definition: mythdbcon.cpp:619
void bindValue(const QString &placeholder, const QVariant &val)
Add a single binding.
Definition: mythdbcon.cpp:889
bool next(void)
Wrap QSqlQuery::next() so we can display the query results.
Definition: mythdbcon.cpp:813
static MSqlQueryInfo InitCon(ConnectionReuse _reuse=kNormalConnection)
Only use this in combination with MSqlQuery constructor.
Definition: mythdbcon.cpp:551
bool toBool(const QString &key) const
Returns stored QVariant as a boolean.
int toInt(const QString &key) const
Returns stored QVariant as an integer, falling to default if not provided.
virtual bool Parse(int argc, const char *const *argv)
Loop through argv and populate arguments with values.
void ApplySettingsOverride(void)
Apply all overrides to the global context.
int ConfigureLogging(const QString &mask="general", bool progress=false)
Read in logging options and initialize the logging interface.
QString toString(const QString &key) const
Returns stored QVariant as a QString, falling to default if not provided.
static void PrintVersion(void)
Print application version information.
QDateTime toDateTime(const QString &key) const
Returns stored QVariant as a QDateTime, falling to default if not provided.
QStringList toStringList(const QString &key, const QString &sep="") const
Returns stored QVariant as a QStringList, falling to default if not provided.
uint toUInt(const QString &key) const
Returns stored QVariant as an unsigned integer, falling to default if not provided.
void PrintHelp(void) const
Print command line option help.
Startup context for MythTV.
Definition: mythcontext.h:20
int GetBackendServerPort(void)
Returns the locally defined backend control port.
static QString GenMythURL(const QString &host=QString(), int port=0, QString path=QString(), const QString &storageGroup=QString())
bool GetBoolSetting(const QString &key, bool defaultval=false)
static void DBError(const QString &where, const MSqlQuery &query)
Definition: mythdb.cpp:225
static void load(const QString &module_name)
Load a QTranslator for the user's preferred language.
Holds information on recordings and videos.
Definition: programinfo.h:74
uint GetChanID(void) const
This is the unique key used in the database to locate tuning information.
Definition: programinfo.h:380
virtual void SaveFilesize(uint64_t fsize)
Sets recording file size in database, and sets "filesize" field.
uint GetRecordingID(void) const
Definition: programinfo.h:457
void ClearPositionMap(MarkTypes type) const
QString GetHostname(void) const
Definition: programinfo.h:429
bool SaveBasename(const QString &basename)
Sets a recording's basename in the database.
QString GetStorageGroup(void) const
Definition: programinfo.h:430
QDateTime GetRecordingStartTime(void) const
Approximate time the recording started.
Definition: programinfo.h:412
void SavePositionMap(frm_pos_map_t &posMap, MarkTypes type, int64_t min_frame=-1, int64_t max_frame=-1) const
QString QueryBasename(void) const
Gets the basename, from the DB if necessary.
bool QueryCutList(frm_dir_map_t &delMap, bool loadAutosave=false) const
QString GetPlaybackURL(bool checkMaster=false, bool forceCheckLocal=false)
Returns filename or URL to be used to play back this recording.
void SaveCommFlagged(CommFlagStatus flag)
Set "commflagged" field in "recorded" table to "flag".
void SaveBookmark(uint64_t frame)
Clears any existing bookmark in DB and if frame is greater than 0 sets a new bookmark.
Holds information on a recording file and it's video and audio streams.
Definition: recordingfile.h:29
AVContainer m_containerFormat
Definition: recordingfile.h:46
Holds information on a TV Program one might wish to record.
Definition: recordinginfo.h:36
RecordingFile * GetRecordingFile() const
void ApplyTranscoderProfileChange(const QString &profile) const
Sets the transcoder profile for a recording.
static bool DeleteFile(const QString &url)
Definition: remotefile.cpp:420
unsigned int uint
Definition: compat.h:60
@ GENERIC_EXIT_RESTART
Need to restart transcoding.
Definition: exitcodes.h:34
@ GENERIC_EXIT_NO_MYTHCONTEXT
No MythContext available.
Definition: exitcodes.h:16
@ GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:13
@ GENERIC_EXIT_NO_RECORDING_DATA
No program/recording data.
Definition: exitcodes.h:32
@ GENERIC_EXIT_REMOTE_FILE
Can't transcode a remote file.
Definition: exitcodes.h:33
@ GENERIC_EXIT_KILLED
Process killed or stopped.
Definition: exitcodes.h:26
@ GENERIC_EXIT_INVALID_CMDLINE
Command line parse error.
Definition: exitcodes.h:18
@ GENERIC_EXIT_DB_ERROR
Database error.
Definition: exitcodes.h:20
@ JOB_NONE
Definition: jobqueue.h:75
@ JOB_TRANSCODE
Definition: jobqueue.h:78
@ JOB_STOP
Definition: jobqueue.h:54
@ JOB_USE_CUTLIST
Definition: jobqueue.h:60
#define REPLEX_MPEG2
Definition: multiplex.h:43
#define REPLEX_HDTV
Definition: multiplex.h:45
#define REPLEX_DVD
Definition: multiplex.h:44
#define REPLEX_TS_SD
Definition: multiplex.h:46
static constexpr const char * MYTH_APPNAME_MYTHTRANSCODE
Definition: mythappname.h:12
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
#define ENO
This can be appended to the LOG args with "+".
Definition: mythlogging.h:74
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
QString getSymlinkTarget(const QString &start_file, QStringList *intermediaries, unsigned maxLinks)
int main(int argc, char *argv[])
static void UpdatePositionMap(frm_pos_map_t &posMap, frm_pos_map_t &durMap, const QString &mapfile, ProgramInfo *pginfo)
static int transUnlink(const QString &filename, ProgramInfo *pginfo)
static QString recorderOptions
static uint64_t ReloadBookmark(ProgramInfo *pginfo)
static int BuildKeyframeIndex(MPEG2fixup *m2f, const QString &infile, frm_pos_map_t &posMap, frm_pos_map_t &durMap, int jobID)
static void WaitToDelete(ProgramInfo *pginfo)
static void CompleteJob(int jobID, ProgramInfo *pginfo, bool useCutlist, frm_dir_map_t *deleteMap, int &exitCode, int resultCode, bool forceDelete)
static void UpdateJobQueue(float percent_done)
static uint64_t ComputeNewBookmark(uint64_t oldBookmark, frm_dir_map_t *deleteMap)
static int QueueTranscodeJob(ProgramInfo *pginfo, const QString &profile, const QString &hostname, bool usecutlist)
static int glbl_jobID
static int CheckJobQueue()
@ ISODate
Default UTC.
Definition: mythdate.h:17
MythCommFlagCommandLineParser cmdline
string hostname
Definition: caa.py:17
int FILE
Definition: mythburn.py:137
static bool isVideo(const QString &mimeType)
Definition: newssite.cpp:294
MarkTypes
Definition: programtypes.h:46
@ MARK_CUT_START
Definition: programtypes.h:55
@ MARK_KEYFRAME
Definition: programtypes.h:61
@ MARK_BOOKMARK
Definition: programtypes.h:56
@ MARK_GOP_BYFRAME
Definition: programtypes.h:63
@ MARK_CUT_END
Definition: programtypes.h:54
@ MARK_COMM_END
Definition: programtypes.h:59
@ MARK_COMM_START
Definition: programtypes.h:58
@ MARK_DURATION_MS
Definition: programtypes.h:73
@ MARK_GOP_START
Definition: programtypes.h:60
QMap< uint64_t, MarkTypes > frm_dir_map_t
Frame # -> Mark map.
Definition: programtypes.h:117
@ COMM_FLAG_NOT_FLAGGED
Definition: programtypes.h:120
QMap< long long, long long > frm_pos_map_t
Frame # -> File offset map.
Definition: programtypes.h:44
@ formatMPEG2_TS
Definition: recordingfile.h:15
@ formatMPEG2_PS
Definition: recordingfile.h:16
@ formatNUV
Definition: recordingfile.h:14
@ REENCODE_STOPPED
Definition: transcodedefs.h:9
@ REENCODE_CUTLIST_CHANGE
Definition: transcodedefs.h:6
@ REENCODE_OK
Definition: transcodedefs.h:7