#include "movie.hh"

#include <iostream>
#include <QTime>
#include <QString>
#include <QStringList>
#include <QApplication>

Movie::
Movie(Viewer3D* src):
  QThread(src),
  src_(src)
{
  pipe_.setProcessChannelMode(QProcess::MergedChannels);
}

bool Movie::
setup(QString filename)
{
  run_=false;
  QStringList dirs;
  dirs << "" << ("\""+QCoreApplication::applicationDirPath()+"\"/") << "/usr/bin/" << "/usr/local/bin/" << "/opt/bin/" << "/opt/local/bin/" << (qgetenv("HOME")+"/bin/");
  for (int i=0; i<dirs.size() && !run_; i++)
    {
      pipe_.start(dirs.at(i)+"ffmpeg -y -r 25 -f image2pipe -i - -vcodec libx264 -pix_fmt yuv420p -crf 20 -r 25 \""+filename+"\"");
      run_=pipe_.waitForStarted();
    }
  QString output=pipe_.readAll();
  std::cout << qPrintable(output) << std::flush;
  return run_;
  
}
void Movie::
stop(void)
{
  run_=false;
}
void Movie::
run(void)
{
  src_->setCapture(true);
  QTime last;
  QString output;
  last.start();
  while (run_)
    {
      output=pipe_.readAll();
      if (output.length())
	std::cout << qPrintable(output) << std::flush;
      src_->lock();
      QImage img=src_->lastImage();
      src_->unlock();
      img.save(&pipe_, "BMP");
      while (last.elapsed()<40)
	usleep(500);
      last.restart();
    }
   pipe_.closeWriteChannel();
   output=pipe_.readAll();
   if (output.length())
     std::cout << qPrintable(output) << std::flush;
   pipe_.waitForFinished();
   src_->setCapture(false);
}
