MythTV  master
previewgenerator.cpp
Go to the documentation of this file.
1 // C headers
2 #include <cmath>
3 #include <utility>
4 
5 // POSIX headers
6 #include <sys/types.h> // for utime
7 #include <sys/time.h>
8 #include <fcntl.h>
9 #include <utime.h> // for utime
10 
11 // Qt headers
12 #include <QApplication>
13 #include <QCoreApplication>
14 #include <QDir>
15 #include <QFileInfo>
16 #include <QImage>
17 #include <QMetaType>
18 #include <QTemporaryFile>
19 #include <QUrl>
20 
21 // MythTV headers
22 #include "mythconfig.h"
23 #include "io/mythmediabuffer.h"
24 #include "mythpreviewplayer.h"
25 #include "previewgenerator.h"
26 #include "tv_rec.h"
27 #include "mythsocket.h"
28 #include "remotefile.h"
29 #include "storagegroup.h"
30 #include "mythdate.h"
31 #include "playercontext.h"
32 #include "mythdirs.h"
33 #include "remoteutil.h"
34 #include "mythsystemlegacy.h"
35 #include "exitcodes.h"
36 #include "mythlogging.h"
37 #include "mythmiscutil.h"
38 
39 #define LOC QString("Preview: ")
40 
73  QString token,
75  : MThread("PreviewGenerator"),
76  m_programInfo(*pginfo), m_mode(mode),
77  m_pathname(pginfo->GetPathname()),
78  m_token(std::move(token))
79 {
80  // Qt requires that a receiver have the same thread affinity as the QThread
81  // sending the event, which is used to dispatch MythEvents sent by
82  // gCoreContext->dispatchNow(me)
83  moveToThread(QApplication::instance()->thread());
84 }
85 
87 {
88  TeardownAll();
89  wait();
90 }
91 
92 void PreviewGenerator::SetOutputFilename(const QString &fileName)
93 {
94  if (fileName.isEmpty())
95  return;
96  QFileInfo fileinfo = QFileInfo(fileName);
97  m_outFileName = fileName;
98  m_outFormat = fileinfo.suffix().toUpper();
99 }
100 
102 {
103  QMutexLocker locker(&m_previewLock);
104  m_previewWaitCondition.wakeAll();
105  m_listener = nullptr;
106 }
107 
109 {
110  TeardownAll();
111  QObject::deleteLater();
112 }
113 
115 {
116  QMutexLocker locker(&m_previewLock);
117  m_listener = obj;
118 }
119 
124 {
125  QString msg;
126  QTime tm = QTime::currentTime();
127  QElapsedTimer te; te.start();
128  bool ok = false;
129  bool is_local = IsLocal();
130 
131  if (!is_local && !!(m_mode & kRemote))
132  {
133  LOG(VB_GENERAL, LOG_ERR, LOC +
134  QString("RunReal() file not local: '%1'")
135  .arg(m_pathname));
136  }
137  else if (!(m_mode & kLocal) && !(m_mode & kRemote))
138  {
139  LOG(VB_GENERAL, LOG_ERR, LOC +
140  QString("RunReal() Preview of '%1' failed "
141  "because mode was invalid 0x%2")
142  .arg(m_pathname).arg((int)m_mode,0,16));
143  }
144  else if (!!(m_mode & kLocal) && LocalPreviewRun())
145  {
146  ok = true;
147  msg = QString("Generated on %1 in %2 seconds, starting at %3")
148  .arg(gCoreContext->GetHostName())
149  .arg(te.elapsed()*0.001)
150  .arg(tm.toString(Qt::ISODate));
151  }
152  else if (!!(m_mode & kRemote))
153  {
154  if (is_local && (m_mode & kLocal))
155  {
156  LOG(VB_GENERAL, LOG_WARNING, LOC + "Failed to save preview."
157  "\n\t\t\tYou may need to check user and group ownership on"
158  "\n\t\t\tyour frontend and backend for quicker previews.\n"
159  "\n\t\t\tAttempting to regenerate preview on backend.\n");
160  }
161  ok = RemotePreviewRun();
162  if (ok)
163  {
164  msg = QString("Generated remotely in %1 seconds, starting at %2")
165  .arg(te.elapsed()*0.001)
166  .arg(tm.toString(Qt::ISODate));
167  }
168  else
169  {
170  msg = "Remote preview failed";
171  }
172  }
173  else
174  {
175  msg = "Could not access recording";
176  }
177 
178  QMutexLocker locker(&m_previewLock);
179  if (m_listener)
180  {
181  // keep in sync with default filename in
182  // PreviewGeneratorQueue::GeneratePreviewImage
183  QString output_fn = m_outFileName.isEmpty() ?
185 
186  QDateTime dt;
187  if (ok)
188  {
189  QFileInfo fi(output_fn);
190  if (fi.exists())
191  dt = fi.lastModified();
192  }
193 
194  QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
195  QStringList list;
196  list.push_back(QString::number(m_programInfo.GetRecordingID()));
197  list.push_back(output_fn);
198  list.push_back(msg);
199  list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):"");
200  list.push_back(m_token);
201  QCoreApplication::postEvent(m_listener, new MythEvent(message, list));
202  }
203 
204  return ok;
205 }
206 
208 {
209  QString msg;
210  QTime tm = QTime::currentTime();
211  QElapsedTimer te; te.start();
212  bool ok = false;
213  QString command = GetAppBinDir() + "mythpreviewgen";
214  bool local_ok = ((IsLocal() || ((m_mode & kForceLocal) != 0)) &&
215  ((m_mode & kLocal) != 0) &&
216  QFileInfo(command).isExecutable());
217  if (!local_ok)
218  {
219  if (!!(m_mode & kRemote))
220  {
221  ok = RemotePreviewRun();
222  if (ok)
223  {
224  msg =
225  QString("Generated remotely in %1 seconds, starting at %2")
226  .arg(te.elapsed()*0.001)
227  .arg(tm.toString(Qt::ISODate));
228  }
229  }
230  else
231  {
232  LOG(VB_GENERAL, LOG_ERR, LOC +
233  QString("Run() cannot generate preview locally for: '%1'")
234  .arg(m_pathname));
235  msg = "Failed, local preview requested for remote file.";
236  }
237  }
238  else
239  {
240  // This is where we fork and run mythpreviewgen to actually make preview
241  QStringList cmdargs;
242 
243  cmdargs << "--size"
244  << QString("%1x%2").arg(m_outSize.width()).arg(m_outSize.height());
245  if (m_captureTime >= 0s)
246  cmdargs << "--seconds" << QString::number(m_captureTime.count());
247  else if (m_captureFrame >= 0)
248  cmdargs << "--frame" << QString::number(m_captureFrame);
249  cmdargs << "--chanid"
250  << QString::number(m_programInfo.GetChanID())
251  << "--starttime"
253 
254  if (!m_outFileName.isEmpty())
255  cmdargs << "--outfile" << m_outFileName;
256 
257  // Timeout in 30s
258  auto *ms = new MythSystemLegacy(command, cmdargs,
264  ms->SetNice(10);
265  ms->SetIOPrio(7);
266 
267  ms->Run(30s);
268  uint ret = ms->Wait();
269  delete ms;
270 
271  if (ret != GENERIC_EXIT_OK)
272  {
273  LOG(VB_GENERAL, LOG_ERR, LOC +
274  QString("Encountered problems running '%1 %2' - (%3)")
275  .arg(command, cmdargs.join(" "), QString::number(ret)));
276  }
277  else
278  {
279  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0.");
280  QString outname = (!m_outFileName.isEmpty()) ?
281  m_outFileName : (m_pathname + ".png");
282 
283  QString lpath = QFileInfo(outname).fileName();
284  if (lpath == outname)
285  {
286  StorageGroup sgroup;
287  QString tmpFile = sgroup.FindFile(lpath);
288  outname = (tmpFile.isEmpty()) ? outname : tmpFile;
289  }
290 
291  QFileInfo fi(outname);
292  ok = (fi.exists() && fi.isReadable() && (fi.size() != 0));
293  if (ok)
294  {
295  LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok.");
296  msg = QString("Generated on %1 in %2 seconds, starting at %3")
297  .arg(gCoreContext->GetHostName())
298  .arg(te.elapsed()*0.001)
299  .arg(tm.toString(Qt::ISODate));
300  }
301  else
302  {
303  LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." +
304  QString("\n\t\t\tfileinfo(%1)").arg(outname) +
305  QString(" exists: %1").arg(fi.exists()) +
306  QString(" readable: %1").arg(fi.isReadable()) +
307  QString(" size: %1").arg(fi.size()));
308  LOG(VB_GENERAL, LOG_ERR, LOC +
309  QString("Despite command '%1' returning success")
310  .arg(command));
311  msg = QString("Failed to read preview image despite "
312  "preview process returning success.");
313  }
314  }
315  }
316 
317  QMutexLocker locker(&m_previewLock);
318 
319  // Backdate file to start of preview time in case a bookmark was made
320  // while we were generating the preview.
321  QString output_fn = m_outFileName.isEmpty() ?
323 
324  QDateTime dt;
325  if (ok)
326  {
327  QFileInfo fi(output_fn);
328  if (fi.exists())
329  dt = fi.lastModified();
330  }
331 
332  QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
333  if (m_listener)
334  {
335  QStringList list;
336  list.push_back(QString::number(m_programInfo.GetRecordingID()));
337  list.push_back(output_fn);
338  list.push_back(msg);
339  list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):"");
340  list.push_back(m_token);
341  QCoreApplication::postEvent(m_listener, new MythEvent(message, list));
342  }
343 
344  return ok;
345 }
346 
348 {
349  RunProlog();
350  Run();
351  RunEpilog();
352 }
353 
355 {
356  QStringList strlist( "QUERY_GENPIXMAP2" );
357  if (m_token.isEmpty())
358  {
359  m_token = QString("%1:%2")
360  .arg(m_programInfo.MakeUniqueKey()).arg(MythRandom());
361  }
362  strlist.push_back(m_token);
363  m_programInfo.ToStringList(strlist);
364  if (m_captureTime >= 0s)
365  {
366  strlist.push_back("s");
367  strlist.push_back(QString::number(m_captureTime.count()));
368  }
369  else
370  {
371  strlist.push_back("f");
372  strlist.push_back(QString::number(m_captureFrame));
373  }
374  if (m_outFileName.isEmpty())
375  {
376  strlist.push_back("<EMPTY>");
377  }
378  else
379  {
380  QFileInfo fi(m_outFileName);
381  strlist.push_back(fi.fileName());
382  }
383  strlist.push_back(QString::number(m_outSize.width()));
384  strlist.push_back(QString::number(m_outSize.height()));
385 
386  gCoreContext->addListener(this);
387  m_pixmapOk = false;
388 
389  bool ok = gCoreContext->SendReceiveStringList(strlist);
390  if (!ok || strlist.empty() || (strlist[0] != "OK"))
391  {
392  if (!ok)
393  {
394  LOG(VB_GENERAL, LOG_ERR, LOC +
395  "Remote Preview failed due to communications error.");
396  }
397  else if (strlist.size() > 1)
398  {
399  LOG(VB_GENERAL, LOG_ERR, LOC +
400  "Remote Preview failed, reason given: " + strlist[1]);
401  }
402 
404 
405  return false;
406  }
407 
408  QMutexLocker locker(&m_previewLock);
409 
410  // wait up to 35 seconds for the preview to complete
411  // The backend waits 30s for creation
412  if (!m_gotReply)
413  m_previewWaitCondition.wait(&m_previewLock, 35 * 1000);
414 
415  if (!m_gotReply)
416  LOG(VB_GENERAL, LOG_NOTICE, LOC + "RemotePreviewRun() -- no reply..");
417 
419 
420  return m_pixmapOk;
421 }
422 
423 bool PreviewGenerator::event(QEvent *e)
424 {
425  if (e->type() != MythEvent::MythEventMessage)
426  return QObject::event(e);
427 
428  auto *me = dynamic_cast<MythEvent*>(e);
429  if (me == nullptr)
430  return QObject::event(e);
431  if (me->Message() != "GENERATED_PIXMAP" || me->ExtraDataCount() < 3)
432  return QObject::event(e);
433 
434  bool ok = me->ExtraData(0) == "OK";
435  bool ours = false;
436  uint i = ok ? 4 : 3;
437  for (; i < (uint) me->ExtraDataCount() && !ours; i++)
438  ours |= me->ExtraData(i) == m_token;
439  if (!ours)
440  return QObject::event(e);
441 
442  const QString& pginfokey = me->ExtraData(1);
443 
444  QMutexLocker locker(&m_previewLock);
445  m_gotReply = true;
446  m_pixmapOk = ok;
447  if (!ok)
448  {
449  LOG(VB_GENERAL, LOG_ERR, LOC + pginfokey + ": " + me->ExtraData(2));
450  m_previewWaitCondition.wakeAll();
451  return true;
452  }
453 
454  if (me->ExtraDataCount() < 5)
455  {
456  m_pixmapOk = false;
457  m_previewWaitCondition.wakeAll();
458  return true; // could only happen with very broken client...
459  }
460 
461  QDateTime datetime = MythDate::fromString(me->ExtraData(3));
462  if (!datetime.isValid())
463  {
464  m_pixmapOk = false;
465  LOG(VB_GENERAL, LOG_ERR, LOC + pginfokey + "Got invalid date");
466  m_previewWaitCondition.wakeAll();
467  return QObject::event(e);
468  }
469 
470  size_t length = me->ExtraData(4).toULongLong();
471  quint16 checksum16 = me->ExtraData(5).toUInt();
472  QByteArray data = QByteArray::fromBase64(me->ExtraData(6).toLatin1());
473  if ((size_t) data.size() < length)
474  { // (note data.size() may be up to 3
475  // bytes longer after decoding
476  LOG(VB_GENERAL, LOG_ERR, LOC +
477  QString("Preview size check failed %1 < %2")
478  .arg(data.size()).arg(length));
479  data.clear();
480  }
481  data.resize(length);
482 
483 #if QT_VERSION < QT_VERSION_CHECK(6,0,0)
484  quint16 calculated = qChecksum(data.constData(), data.size());
485 #else
486  quint16 calculated = qChecksum(data);
487 #endif
488  if (checksum16 != calculated)
489  {
490  LOG(VB_GENERAL, LOG_ERR, LOC + "Preview checksum failed");
491  data.clear();
492  }
493 
494  m_pixmapOk = (data.isEmpty()) ? false : SaveOutFile(data, datetime);
495 
496  m_previewWaitCondition.wakeAll();
497 
498  return true;
499 }
500 
501 bool PreviewGenerator::SaveOutFile(const QByteArray &data, const QDateTime &dt)
502 {
503  if (m_outFileName.isEmpty())
504  {
505  QString remotecachedirname =
506  QString("%1/cache/remotecache").arg(GetConfDir());
507  QDir remotecachedir(remotecachedirname);
508 
509  if (!remotecachedir.exists())
510  {
511  if (!remotecachedir.mkdir(remotecachedirname))
512  {
513  LOG(VB_GENERAL, LOG_ERR, LOC +
514  "Remote Preview failed because we could not create a "
515  "remote cache directory");
516  return false;
517  }
518  }
519 
520  QString filename = m_programInfo.GetBasename() + ".png";
521  SetOutputFilename(QString("%1/%2").arg(remotecachedirname, filename));
522  }
523 
524  QFile file(m_outFileName);
525  bool ok = file.open(QIODevice::Unbuffered|QIODevice::WriteOnly);
526  if (!ok)
527  {
528  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Failed to open: '%1'")
529  .arg(m_outFileName));
530  }
531 
532  off_t offset = 0;
533  size_t remaining = data.size();
534  uint failure_cnt = 0;
535  while ((remaining > 0) && (failure_cnt < 5))
536  {
537  ssize_t written = file.write(data.data() + offset, remaining);
538  if (written < 0)
539  {
540  failure_cnt++;
541  usleep(50ms);
542  continue;
543  }
544 
545  failure_cnt = 0;
546  offset += written;
547  remaining -= written;
548  }
549 
550  if (ok && !remaining)
551  {
552  file.close();
553  struct utimbuf times {};
554  times.actime = times.modtime = dt.toSecsSinceEpoch();
555  utime(m_outFileName.toLocal8Bit().constData(), &times);
556  LOG(VB_FILE, LOG_INFO, LOC + QString("Saved: '%1'").arg(m_outFileName));
557  }
558  else
559  {
560  file.remove();
561  }
562 
563  return ok;
564 }
565 
567  const unsigned char *data,
568  uint width, uint height, float aspect,
569  int desired_width, int desired_height,
570  const QString &format)
571 {
572  if (!data || !width || !height)
573  return false;
574 
575  const QImage img((unsigned char*) data,
576  width, height, QImage::Format_RGB32);
577 
578  float ppw = std::max(desired_width, 0);
579  float pph = std::max(desired_height, 0);
580  bool desired_size_exactly_specified = true;
581  if ((ppw < 1.0F) && (pph < 1.0F))
582  {
583  ppw = img.width();
584  pph = img.height();
585  desired_size_exactly_specified = false;
586  }
587 
588  aspect = (aspect <= 0.0F) ? ((float) width) / height : aspect;
589  pph = (pph < 1.0F) ? (ppw / aspect) : pph;
590  ppw = (ppw < 1.0F) ? (pph * aspect) : ppw;
591 
592  if (!desired_size_exactly_specified)
593  {
594  if (aspect > ppw / pph)
595  pph = (ppw / aspect);
596  else
597  ppw = (pph * aspect);
598  }
599 
600  ppw = std::max(1.0F, ppw);
601  pph = std::max(1.0F, pph);;
602 
603  QImage small_img = img.scaled((int) ppw, (int) pph,
604  Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
605 
606  QTemporaryFile f(QFileInfo(filename).absoluteFilePath()+".XXXXXX");
607  f.setAutoRemove(false);
608  if (f.open() && small_img.save(&f, format.toLocal8Bit().constData()))
609  {
610  // Let anybody update it
611  bool ret = makeFileAccessible(f.fileName().toLocal8Bit().constData());
612  if (!ret)
613  {
614  LOG(VB_GENERAL, LOG_ERR, "Unable to change permissions on "
615  "preview image. Backends and frontends "
616  "running under different users will be "
617  "unable to access it");
618  }
619  QFile of(filename);
620  of.remove();
621  if (f.rename(filename))
622  {
623  LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Saved preview '%0' %1x%2")
624  .arg(filename).arg((int) ppw).arg((int) pph));
625  return true;
626  }
627  f.remove();
628  }
629 
630  return false;
631 }
632 
634 {
638 
639  float aspect = 0;
640  std::chrono::seconds captime = m_captureTime;
641  long long capframe = -1;
642 
643  QDateTime dt = MythDate::current();
644 
645  if (captime > 0s)
646  LOG(VB_GENERAL, LOG_INFO, "Preview from time spec");
647  else
648  {
649  capframe = m_programInfo.QueryBookmark();
650  if (capframe > 0)
651  {
652  LOG(VB_GENERAL, LOG_INFO,
653  QString("Preview from bookmark (frame %1)").arg(capframe));
654  }
655  }
656 
657  if ((captime <= 0s) && (capframe <= 0))
658  {
659  std::chrono::seconds startEarly = 0s;
660  std::chrono::seconds programDuration = 0s;
661  auto preroll = gCoreContext->GetDurSetting<std::chrono::seconds>("RecordPreRoll", 0s);
662  if (m_programInfo.GetScheduledStartTime().isValid() &&
663  m_programInfo.GetScheduledEndTime().isValid() &&
666  {
667  programDuration = std::chrono::seconds(m_programInfo.GetScheduledStartTime()
669  }
670  if (m_programInfo.GetRecordingStartTime().isValid() &&
671  m_programInfo.GetScheduledStartTime().isValid() &&
674  {
675  startEarly = std::chrono::seconds(m_programInfo.GetRecordingStartTime()
677  }
678  if (programDuration > 0s)
679  {
680  captime = programDuration / 3;
681  if (captime > 10min)
682  captime = 10min;
683  captime += startEarly;
684  }
685  if (captime < 0s)
686  captime = 10min;
687  captime += preroll;
688  LOG(VB_GENERAL, LOG_INFO,
689  QString("Preview at calculated offset (%1 seconds)").arg(captime.count()));
690  }
691 
692  int width = 0;
693  int height = 0;
694  int sz = 0;
695  auto *data = (unsigned char*) GetScreenGrab(m_programInfo, m_pathname,
696  captime, capframe,
697  sz, width, height, aspect);
698 
700 
701  QString format = (m_outFormat.isEmpty()) ? "PNG" : m_outFormat;
702 
703  int dw = (m_outSize.width() < 0) ? width : m_outSize.width();
704  int dh = (m_outSize.height() < 0) ? height : m_outSize.height();
705 
706  bool ok = SavePreview(outname, data, width, height, aspect, dw, dh,
707  format);
708 
709  if (ok)
710  {
711  // Backdate file to start of preview time in case a bookmark was made
712  // while we were generating the preview.
713  struct utimbuf times {};
714  times.actime = times.modtime = dt.toSecsSinceEpoch();
715  utime(outname.toLocal8Bit().constData(), &times);
716  }
717 
718  delete[] data;
719 
721 
722  return ok;
723 }
724 
726  const QString &pathname, const QString &outFileName)
727 {
728  QString outname = pathname + ".png";
729 
730  if (outFileName.isEmpty())
731  return outname;
732 
733  outname = outFileName;
734  QFileInfo fi(outname);
735  if (outname == fi.fileName())
736  {
737  QString dir;
738  if (pathname.contains(':'))
739  {
740  QUrl uinfo(pathname);
741  uinfo.setPath("");
742  dir = uinfo.toString();
743  }
744  else
745  {
746  dir = QFileInfo(pathname).path();
747  }
748  outname = dir + "/" + fi.fileName();
749  LOG(VB_FILE, LOG_INFO, LOC + QString("outfile '%1' -> '%2'")
750  .arg(outFileName, outname));
751  }
752 
753  return outname;
754 }
755 
757 {
758  QString tmppathname = m_pathname;
759 
760  if (tmppathname.startsWith("dvd:"))
761  tmppathname = tmppathname.section(":", 1, 1);
762 
763  if (!QFileInfo(tmppathname).isReadable())
764  return false;
765 
766  tmppathname = m_outFileName.isEmpty() ? tmppathname : m_outFileName;
767  QString pathdir = QFileInfo(tmppathname).path();
768 
769  if (!QFileInfo(pathdir).isWritable())
770  {
771  LOG(VB_GENERAL, LOG_WARNING, LOC +
772  QString("Output path '%1' is not writeable") .arg(pathdir));
773  return false;
774  }
775 
776  return true;
777 }
778 
796  const ProgramInfo &pginfo, const QString &filename,
797  std::chrono::seconds seektime, long long seekframe,
798  int &bufferlen,
799  int &video_width, int &video_height, float &video_aspect)
800 {
801  char *retbuf = nullptr;
802  bufferlen = 0;
803 
805  {
806  LOG(VB_GENERAL, LOG_ERR, LOC + "Previewer could not connect to DB.");
807  return nullptr;
808  }
809 
810  // pre-test local files for existence and size. 500 ms speed-up...
811  if (filename.startsWith("/"))
812  {
813  QFileInfo info(filename);
814  bool invalid = (!info.exists() || !info.isReadable() || (info.isFile() && (info.size() < 8*1024)));
815  if (invalid)
816  {
817  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Previewer file '%1' is not valid.")
818  .arg(filename));
819  return nullptr;
820  }
821  }
822 
823  MythMediaBuffer* buffer = MythMediaBuffer::Create(filename, false, false, 0ms);
824  if (!buffer || !buffer->IsOpen())
825  {
826  LOG(VB_GENERAL, LOG_ERR, LOC + "Previewer could not open file: " +
827  QString("'%1'").arg(filename));
828  delete buffer;
829  return nullptr;
830  }
831 
832  auto *ctx = new PlayerContext(kPreviewGeneratorInUseID);
833  auto * player = new MythPreviewPlayer(ctx, static_cast<PlayerFlags>(kAudioMuted | kVideoIsNull | kNoITV));
834  ctx->SetRingBuffer(buffer);
835  ctx->SetPlayingInfo(&pginfo);
836  ctx->SetPlayer(player);
837 
838  if (seektime >= 0s)
839  {
840  retbuf = player->GetScreenGrab(seektime, bufferlen,
841  video_width, video_height, video_aspect);
842  }
843  else
844  {
845  retbuf = player->GetScreenGrabAtFrame(static_cast<uint64_t>(seekframe), true,
846  bufferlen, video_width, video_height, video_aspect);
847  }
848  delete ctx;
849 
850  auto pos_text = (seektime != std::chrono::seconds::max())
851  ? QString::number(seektime.count()) + "s"
852  : QString::number(seekframe)+ "f";
853  if (retbuf)
854  {
855  LOG(VB_GENERAL, LOG_INFO, LOC + QString("Grabbed preview '%0' %1x%2@%3")
856  .arg(filename).arg(video_width).arg(video_height).arg(pos_text));
857  }
858  else
859  {
860  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Failed to grab preview '%0' %1x%2@%3")
861  .arg(filename).arg(video_width).arg(video_height).arg(pos_text));
862  }
863 
864  return retbuf;
865 }
PreviewGenerator::m_outSize
QSize m_outSize
Definition: previewgenerator.h:118
ProgramInfo::MakeUniqueKey
QString MakeUniqueKey(void) const
Creates a unique string that can be used to identify an existing recording.
Definition: programinfo.h:338
MythEvent::MythEventMessage
static Type MythEventMessage
Definition: mythevent.h:78
GENERIC_EXIT_OK
#define GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:10
kMSDontBlockInputDevs
@ kMSDontBlockInputDevs
avoid blocking LIRC & Joystick Menu
Definition: mythsystem.h:36
MythSystemLegacy
Definition: mythsystemlegacy.h:67
PreviewGenerator::PreviewGenerator
PreviewGenerator(const ProgramInfo *pginfo, QString token, Mode mode=kLocal)
Constructor.
Definition: previewgenerator.cpp:72
MythCoreContext::SendReceiveStringList
bool SendReceiveStringList(QStringList &strlist, bool quickTimeout=false, bool block=true)
Send a message to the backend and wait for a response.
Definition: mythcorecontext.cpp:1383
PreviewGenerator::kRemote
@ kRemote
Definition: previewgenerator.h:43
PreviewGenerator::run
void run(void) override
Runs the Qt event loop unless we have a QRunnable, in which case we run the runnable run instead.
Definition: previewgenerator.cpp:347
PreviewGenerator::AttachSignals
void AttachSignals(QObject *obj)
Definition: previewgenerator.cpp:114
MThread::wait
bool wait(std::chrono::milliseconds time=std::chrono::milliseconds::max())
Wait for the MThread to exit, with a maximum timeout.
Definition: mthread.cpp:303
PreviewGenerator::Run
bool Run(void)
Definition: previewgenerator.cpp:207
PreviewGenerator::m_token
QString m_token
Definition: previewgenerator.h:121
StorageGroup::FindFile
QString FindFile(const QString &filename)
Definition: storagegroup.cpp:602
ProgramInfo::GetRecordingID
uint GetRecordingID(void) const
Definition: programinfo.h:445
MythEvent
This class is used as a container for messages.
Definition: mythevent.h:16
MThread::usleep
static void usleep(std::chrono::microseconds time)
Definition: mthread.cpp:338
PreviewGenerator::RunReal
bool RunReal(void)
This call creates a preview without starting a new thread.
Definition: previewgenerator.cpp:123
PreviewGenerator::m_pathname
QString m_pathname
Definition: previewgenerator.h:112
MythMediaBuffer
Definition: mythmediabuffer.h:50
ProgramInfo::GetScheduledEndTime
QDateTime GetScheduledEndTime(void) const
The scheduled end time of the program.
Definition: programinfo.h:396
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23
MThread::RunProlog
void RunProlog(void)
Sets up a thread, call this if you reimplement run().
Definition: mthread.cpp:196
PlayerFlags
PlayerFlags
Definition: mythplayer.h:65
PreviewGenerator::SavePreview
static bool SavePreview(const QString &filename, const unsigned char *data, uint width, uint height, float aspect, int desired_width, int desired_height, const QString &format)
Definition: previewgenerator.cpp:566
PreviewGenerator::LocalPreviewRun
bool LocalPreviewRun(void)
Definition: previewgenerator.cpp:633
build_compdb.file
file
Definition: build_compdb.py:55
mythdirs.h
PreviewGenerator::m_captureFrame
long long m_captureFrame
Definition: previewgenerator.h:116
remoteutil.h
MythDate::current
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:10
ProgramInfo::GetRecordingStartTime
QDateTime GetRecordingStartTime(void) const
Approximate time the recording started.
Definition: programinfo.h:403
ProgramInfo::GetPathname
QString GetPathname(void) const
Definition: programinfo.h:342
mythsystemlegacy.h
PreviewGenerator::event
bool event(QEvent *e) override
Definition: previewgenerator.cpp:423
MythObservable::addListener
void addListener(QObject *listener)
Add a listener to the observable.
Definition: mythobservable.cpp:38
ProgramInfo::QueryBookmark
uint64_t QueryBookmark(void) const
Gets any bookmark position in database, unless the ignore bookmark flag is set.
Definition: programinfo.cpp:2766
PreviewGenerator::TeardownAll
void TeardownAll(void)
Definition: previewgenerator.cpp:101
ProgramInfo::MarkAsInUse
void MarkAsInUse(bool inuse, const QString &usedFor="")
Tracks a recording's in use status, to prevent deletion and to allow the storage scheduler to perform...
Definition: programinfo.cpp:5012
PreviewGenerator::SetOutputFilename
void SetOutputFilename(const QString &fileName)
Definition: previewgenerator.cpp:92
mythdate.h
ProgramInfo::GetScheduledStartTime
QDateTime GetScheduledStartTime(void) const
The scheduled start time of program.
Definition: programinfo.h:389
PreviewGenerator::m_outFormat
QString m_outFormat
Definition: previewgenerator.h:119
mythlogging.h
GetConfDir
QString GetConfDir(void)
Definition: mythdirs.cpp:224
remotefile.h
MythDate::kFilename
@ kFilename
Default UTC, "yyyyMMddhhmmss".
Definition: mythdate.h:18
MythCoreContext::GetDurSetting
std::enable_if_t< std::chrono::__is_duration< T >::value, T > GetDurSetting(const QString &key, T defaultval=T::zero())
Definition: mythcorecontext.h:170
MSqlQuery::testDBConnection
static bool testDBConnection()
Checks DB connection + login (login info via Mythcontext)
Definition: mythdbcon.cpp:881
MThread::RunEpilog
void RunEpilog(void)
Cleans up a thread's resources, call this if you reimplement run().
Definition: mthread.cpp:209
PreviewGenerator::~PreviewGenerator
~PreviewGenerator() override
Definition: previewgenerator.cpp:86
storagegroup.h
kNoITV
@ kNoITV
Definition: mythplayer.h:76
kMSPropagateLogs
@ kMSPropagateLogs
add arguments for MythTV log propagation
Definition: mythsystem.h:52
PreviewGenerator::IsLocal
bool IsLocal(void) const
Definition: previewgenerator.cpp:756
uint
unsigned int uint
Definition: compat.h:140
PreviewGenerator::kForceLocal
@ kForceLocal
Definition: previewgenerator.h:45
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:60
kPreviewGeneratorInUseID
const QString kPreviewGeneratorInUseID
Definition: programtypes.cpp:22
PreviewGenerator::m_previewWaitCondition
QWaitCondition m_previewWaitCondition
Definition: previewgenerator.h:106
mythmediabuffer.h
kMSAutoCleanup
@ kMSAutoCleanup
automatically delete if backgrounded
Definition: mythsystem.h:45
MythDate::fromString
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:30
PreviewGenerator::SaveOutFile
bool SaveOutFile(const QByteArray &data, const QDateTime &dt)
Definition: previewgenerator.cpp:501
off_t
#define off_t
Definition: mythiowrapper.cpp:240
PreviewGenerator::m_programInfo
ProgramInfo m_programInfo
Definition: previewgenerator.h:108
PreviewGenerator::m_outFileName
QString m_outFileName
Definition: previewgenerator.h:117
PreviewGenerator::RemotePreviewRun
bool RemotePreviewRun(void)
Definition: previewgenerator.cpp:354
PreviewGenerator::m_pixmapOk
bool m_pixmapOk
Definition: previewgenerator.h:123
MythRandom
MBASE_PUBLIC uint32_t MythRandom()
Definition: mythmiscutil.h:21
PreviewGenerator::m_gotReply
bool m_gotReply
Definition: previewgenerator.h:122
ProgramInfo::GetChanID
uint GetChanID(void) const
This is the unique key used in the database to locate tuning information.
Definition: programinfo.h:371
kVideoIsNull
@ kVideoIsNull
Definition: mythplayer.h:74
PreviewGenerator::m_captureTime
std::chrono::seconds m_captureTime
snapshot time in seconds or frame number (seconds has priority)
Definition: previewgenerator.h:115
ProgramInfo
Holds information on recordings and videos.
Definition: programinfo.h:67
mythmiscutil.h
makeFileAccessible
bool makeFileAccessible(const QString &filename)
Definition: mythmiscutil.cpp:443
ProgramInfo::ToStringList
void ToStringList(QStringList &list) const
Serializes ProgramInfo into a QStringList which can be passed over a socket.
Definition: programinfo.cpp:1281
PreviewGenerator::GetScreenGrab
static char * GetScreenGrab(const ProgramInfo &pginfo, const QString &filename, std::chrono::seconds seektime, long long seekframe, int &bufferlen, int &video_width, int &video_height, float &video_aspect)
Returns a AV_PIX_FMT_RGBA32 buffer containg a frame from the video.
Definition: previewgenerator.cpp:795
playercontext.h
PreviewGenerator::CreateAccessibleFilename
static QString CreateAccessibleFilename(const QString &pathname, const QString &outFileName)
Definition: previewgenerator.cpp:725
kMSProcessEvents
@ kMSProcessEvents
process events while waiting
Definition: mythsystem.h:39
remotecachedir
static QString remotecachedir
Definition: mythdirs.cpp:26
LOC
#define LOC
Definition: previewgenerator.cpp:39
std
Definition: mythchrono.h:23
MythDate::ISODate
@ ISODate
Default UTC.
Definition: mythdate.h:17
PreviewGenerator::m_mode
Mode m_mode
Definition: previewgenerator.h:110
MThread
This is a wrapper around QThread that does several additional things.
Definition: mthread.h:48
GetAppBinDir
QString GetAppBinDir(void)
Definition: mythdirs.cpp:221
tv_rec.h
kAudioMuted
@ kAudioMuted
Definition: mythplayer.h:75
StorageGroup
Definition: storagegroup.h:11
PlayerContext
Definition: playercontext.h:52
MythMediaBuffer::Create
static MythMediaBuffer * Create(const QString &Filename, bool Write, bool UseReadAhead=true, std::chrono::milliseconds Timeout=kDefaultOpenTimeout, bool StreamOnly=false)
Creates a RingBuffer instance.
Definition: mythmediabuffer.cpp:97
MythPreviewPlayer
Definition: mythpreviewplayer.h:7
PreviewGenerator::m_listener
QObject * m_listener
Definition: previewgenerator.h:111
PreviewGenerator::deleteLater
void deleteLater()
Definition: previewgenerator.cpp:108
MythCoreContext::GetHostName
QString GetHostName(void)
Definition: mythcorecontext.cpp:862
ProgramInfo::SetIgnoreProgStart
void SetIgnoreProgStart(bool ignore)
If "ignore" is true QueryProgStart() will return 0, otherwise QueryProgStart() will return the progst...
Definition: programinfo.h:565
PreviewGenerator::kLocal
@ kLocal
Definition: previewgenerator.h:42
kMSDontDisableDrawing
@ kMSDontDisableDrawing
avoid disabling UI drawing
Definition: mythsystem.h:37
previewgenerator.h
exitcodes.h
ProgramInfo::GetBasename
QString GetBasename(void) const
Definition: programinfo.h:343
build_compdb.filename
filename
Definition: build_compdb.py:21
mythsocket.h
mythpreviewplayer.h
MythObservable::removeListener
void removeListener(QObject *listener)
Remove a listener to the observable.
Definition: mythobservable.cpp:55
PreviewGenerator::Mode
Mode
Definition: previewgenerator.h:39
ProgramInfo::SetAllowLastPlayPos
void SetAllowLastPlayPos(bool allow)
If "ignore" is true QueryLastPlayPos() will return 0, otherwise QueryLastPlayPos() will return the la...
Definition: programinfo.h:573
PreviewGenerator::m_previewLock
QMutex m_previewLock
Definition: previewgenerator.h:107
MythMediaBuffer::IsOpen
virtual bool IsOpen(void) const =0