# HG changeset patch # User Stepan777 # Date 1340559153 -14400 # Node ID 24c6fa591866f4543a9c97a5aa4a5e54bde1a598 # Parent c65992e2d7945205451fbf14448320e671ad1523# Parent b817a478dcfb77ff3ffa1924840ed3ddbc4d2a66 merge diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/CMakeLists.txt --- a/QTfrontend/CMakeLists.txt Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/CMakeLists.txt Sun Jun 24 21:32:33 2012 +0400 @@ -156,6 +156,9 @@ endif() endif() +IF (WIN32) + link_directories(${CMAKE_SOURCE_DIR}/misc/winutils/lib) +ENDIF() add_executable(hedgewars WIN32 ${hwfr_src} @@ -167,6 +170,9 @@ set(HW_LINK_LIBS quazip + avformat + avcodec + avutil ${QT_LIBRARIES} ${SDL_LIBRARY} ${SDLMIXER_LIBRARY} diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/binds.cpp --- a/QTfrontend/binds.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/binds.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -64,5 +64,6 @@ {"+volup", "0", QT_TRANSLATE_NOOP("binds", "volume up"), NULL, NULL}, {"fullscr", "f12", QT_TRANSLATE_NOOP("binds", "change mode"), NULL, QT_TRANSLATE_NOOP("binds (descriptions)", "Toggle fullscreen mode:")}, {"capture", "c", QT_TRANSLATE_NOOP("binds", "capture"), NULL, QT_TRANSLATE_NOOP("binds (descriptions)", "Take a screenshot:")}, - {"rotmask", "delete", QT_TRANSLATE_NOOP("binds", "hedgehogs\ninfo"), NULL, QT_TRANSLATE_NOOP("binds (descriptions)", "Toggle labels above hedgehogs:")} + {"rotmask", "delete", QT_TRANSLATE_NOOP("binds", "hedgehogs\ninfo"), NULL, QT_TRANSLATE_NOOP("binds (descriptions)", "Toggle labels above hedgehogs:")}, + {"record", "r", QT_TRANSLATE_NOOP("binds", "record"), NULL, QT_TRANSLATE_NOOP("binds (descriptions)", "Record video:")} }; diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/binds.h --- a/QTfrontend/binds.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/binds.h Sun Jun 24 21:32:33 2012 +0400 @@ -21,7 +21,7 @@ #include -#define BINDS_NUMBER 44 +#define BINDS_NUMBER 45 struct BindAction { diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/game.cpp --- a/QTfrontend/game.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/game.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -53,20 +53,20 @@ { switch (gameType) { - case gtSave: - if (gameState == gsInterrupted || gameState == gsHalted) - emit HaveRecord(false, demo); - else if (gameState == gsFinished) - emit HaveRecord(true, demo); - break; case gtDemo: + // for video recording we need demo anyway + emit HaveRecord(rtNeither, demo); break; case gtNet: - emit HaveRecord(true, demo); + emit HaveRecord(rtDemo, demo); break; default: - if (gameState == gsInterrupted || gameState == gsHalted) emit HaveRecord(false, demo); - else if (gameState == gsFinished) emit HaveRecord(true, demo); + if (gameState == gsInterrupted || gameState == gsHalted) + emit HaveRecord(rtSave, demo); + else if (gameState == gsFinished) + emit HaveRecord(rtDemo, demo); + else + emit HaveRecord(rtNeither, demo); } SetGameState(gsStopped); } @@ -335,6 +335,8 @@ arguments << QString::number(config->translateQuality()); arguments << QString::number(config->stereoMode()); arguments << tr("en.txt"); + arguments << QString::number(config->rec_Framerate()); // framerate num + arguments << "1"; // framerate den return arguments; } diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/game.h --- a/QTfrontend/game.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/game.h Sun Jun 24 21:32:33 2012 +0400 @@ -40,6 +40,13 @@ gsHalted = 6 }; +enum RecordType +{ + rtDemo, + rtSave, + rtNeither, +}; + bool checkForDir(const QString & dir); class HWGame : public TCPBase @@ -70,7 +77,7 @@ void SendTeamMessage(const QString & msg); void GameStateChanged(GameState gameState); void GameStats(char type, const QString & info); - void HaveRecord(bool isDemo, const QByteArray & record); + void HaveRecord(RecordType type, const QByteArray & record); void ErrorMessage(const QString &); public slots: diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/gameuiconfig.cpp --- a/QTfrontend/gameuiconfig.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/gameuiconfig.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -26,6 +26,7 @@ #include "gameuiconfig.h" #include "hwform.h" #include "pageoptions.h" +#include "pagevideos.h" #include "pagenetserver.h" #include "hwconsts.h" #include "fpsedit.h" @@ -42,6 +43,7 @@ resizeToConfigValues(); reloadValues(); + reloadVideosValues(); } void GameUIConfig::reloadValues(void) @@ -110,6 +112,29 @@ else if (depth > 16) depth = 32; } +void GameUIConfig::reloadVideosValues(void) +{ + Form->ui.pageVideos->framerateBox->setValue(value("videorec/fps",25).toUInt()); + bool useGameRes = value("videorec/usegameres",true).toBool(); + if (useGameRes) + { + QRect res = vid_Resolution(); + Form->ui.pageVideos->widthEdit->setText(QString::number(res.width())); + Form->ui.pageVideos->heightEdit->setText(QString::number(res.height())); + } + else + { + Form->ui.pageVideos->widthEdit->setText(value("videorec/width","800").toString()); + Form->ui.pageVideos->heightEdit->setText(value("videorec/height","600").toString()); + } + Form->ui.pageVideos->checkUseGameRes->setChecked(useGameRes); + Form->ui.pageVideos->checkRecordAudio->setChecked(value("videorec/audio",true).toBool()); + if (!Form->ui.pageVideos->tryCodecs(value("videorec/format","no").toString(), + value("videorec/videocodec","no").toString(), + value("videorec/audiocodec","no").toString())) + Form->ui.pageVideos->setDefaultCodecs(); +} + QStringList GameUIConfig::GetTeamsList() { QDir teamdir; @@ -182,6 +207,22 @@ #ifdef SPARKLE_ENABLED setValue("misc/autoUpdate", isAutoUpdateEnabled()); #endif + + Form->gameSettings->sync(); +} + +void GameUIConfig::SaveVideosOptions() +{ + QRect res = rec_Resolution(); + setValue("videorec/format", AVFormat()); + setValue("videorec/videocodec", videoCodec()); + setValue("videorec/audiocodec", audioCodec()); + setValue("videorec/fps", rec_Framerate()); + setValue("videorec/width", res.width()); + setValue("videorec/height", res.height()); + setValue("videorec/usegameres", Form->ui.pageVideos->checkUseGameRes->isChecked()); + setValue("videorec/audio", recordAudio()); + Form->gameSettings->sync(); } @@ -380,3 +421,38 @@ { return Form->ui.pageOptions->volumeBox->value() * 128 / 100; } + +QString GameUIConfig::AVFormat() +{ + return Form->ui.pageVideos->format(); +} + +QString GameUIConfig::videoCodec() +{ + return Form->ui.pageVideos->videoCodec(); +} + +QString GameUIConfig::audioCodec() +{ + return Form->ui.pageVideos->audioCodec(); +} + +QRect GameUIConfig::rec_Resolution() +{ + if (Form->ui.pageVideos->checkUseGameRes->isChecked()) + return vid_Resolution(); + QRect res(0,0,0,0); + res.setWidth(Form->ui.pageVideos->widthEdit->text().toUInt()); + res.setHeight(Form->ui.pageVideos->heightEdit->text().toUInt()); + return res; +} + +int GameUIConfig::rec_Framerate() +{ + return Form->ui.pageVideos->framerateBox->value(); +} + +bool GameUIConfig::recordAudio() +{ + return Form->ui.pageVideos->checkRecordAudio->isChecked(); +} diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/gameuiconfig.h --- a/QTfrontend/gameuiconfig.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/gameuiconfig.h Sun Jun 24 21:32:33 2012 +0400 @@ -59,18 +59,27 @@ void resizeToConfigValues(); quint32 stereoMode() const; + QString AVFormat(); + QString videoCodec(); + QString audioCodec(); + QRect rec_Resolution(); + int rec_Framerate(); + bool recordAudio(); + #ifdef __APPLE__ #ifdef SPARKLE_ENABLED bool isAutoUpdateEnabled(); #endif #endif - void reloadValues(void); + void reloadValues(); + void reloadVideosValues(); signals: void frontendFullscreen(bool value); public slots: void SaveOptions(); + void SaveVideosOptions(); void updNetNick(); private: bool netPasswordIsValid(); diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/hwform.cpp --- a/QTfrontend/hwform.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/hwform.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -76,6 +76,7 @@ #include "pagegamestats.h" #include "pageplayrecord.h" #include "pagedata.h" +#include "pagevideos.h" #include "hwconsts.h" #include "newnetclient.h" #include "gamecfgwidget.h" @@ -90,6 +91,7 @@ #include "drawmapwidget.h" #include "mouseoverfilter.h" #include "roomslistmodel.h" +#include "recorder.h" #include "DataManager.h" @@ -140,6 +142,8 @@ config = new GameUIConfig(this, cfgdir->absolutePath() + "/hedgewars.ini"); + ui.pageVideos->config = config; + #ifdef __APPLE__ panel = new M3Panel; @@ -198,6 +202,9 @@ connect(ui.pageNetGame, SIGNAL(DLCClicked()), pageSwitchMapper, SLOT(map())); pageSwitchMapper->setMapping(ui.pageNetGame, ID_PAGE_DATADOWNLOAD); + connect(ui.pageMain->BtnVideos, SIGNAL(clicked()), pageSwitchMapper, SLOT(map())); + pageSwitchMapper->setMapping(ui.pageMain->BtnVideos, ID_PAGE_VIDEOS); + //connect(ui.pageMain->BtnExit, SIGNAL(pressed()), this, SLOT(btnExitPressed())); //connect(ui.pageMain->BtnExit, SIGNAL(clicked()), this, SLOT(btnExitClicked())); @@ -288,6 +295,7 @@ connect(ui.pageConnecting, SIGNAL(cancelConnection()), this, SLOT(GoBack())); + connect(ui.pageVideos, SIGNAL(goBack()), config, SLOT(SaveVideosOptions())); ammoSchemeModel = new AmmoSchemeModel(this, cfgdir->absolutePath() + "/schemes.ini"); ui.pageScheme->setModel(ammoSchemeModel); @@ -603,6 +611,11 @@ config->reloadValues(); } + if (id == ID_PAGE_VIDEOS ) + { + config->reloadVideosValues(); + } + // load and save ignore/friends lists if (lastid == ID_PAGE_NETGAME) // leaving a room ui.pageNetGame->pChatWidget->saveLists(ui.pageOptions->editNetNick->text()); @@ -1357,7 +1370,7 @@ connect(game, SIGNAL(GameStateChanged(GameState)), this, SLOT(GameStateChanged(GameState))); connect(game, SIGNAL(GameStats(char, const QString &)), ui.pageGameStats, SLOT(GameStats(char, const QString &))); connect(game, SIGNAL(ErrorMessage(const QString &)), this, SLOT(ShowErrorMessage(const QString &)), Qt::QueuedConnection); - connect(game, SIGNAL(HaveRecord(bool, const QByteArray &)), this, SLOT(GetRecord(bool, const QByteArray &))); + connect(game, SIGNAL(HaveRecord(RecordType, const QByteArray &)), this, SLOT(GetRecord(RecordType, const QByteArray &))); m_lastDemo = QByteArray(); } @@ -1368,43 +1381,59 @@ msg); } -void HWForm::GetRecord(bool isDemo, const QByteArray & record) +void HWForm::GetRecord(RecordType type, const QByteArray & record) { - QString filename; - QByteArray demo = record; - QString recordFileName = - config->appendDateTimeToRecordName() ? - QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm") : - "LastRound"; + if (type != rtNeither) + { + QString filename; + QByteArray demo = record; + QString recordFileName = + config->appendDateTimeToRecordName() ? + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm") : + "LastRound"; - QStringList versionParts = cVersionString->split('-'); - if ( (versionParts.size() == 2) && (!versionParts[1].isEmpty()) && (versionParts[1].contains(':')) ) - recordFileName = recordFileName + "_" + versionParts[1].replace(':','-'); + QStringList versionParts = cVersionString->split('-'); + if ( (versionParts.size() == 2) && (!versionParts[1].isEmpty()) && (versionParts[1].contains(':')) ) + recordFileName = recordFileName + "_" + versionParts[1].replace(':','-'); - if (isDemo) - { - demo.replace(QByteArray("\x02TL"), QByteArray("\x02TD")); - demo.replace(QByteArray("\x02TN"), QByteArray("\x02TD")); - demo.replace(QByteArray("\x02TS"), QByteArray("\x02TD")); - filename = cfgdir->absolutePath() + "/Demos/" + recordFileName + "." + *cProtoVer + ".hwd"; - m_lastDemo = demo; - } - else - { - demo.replace(QByteArray("\x02TL"), QByteArray("\x02TS")); - demo.replace(QByteArray("\x02TN"), QByteArray("\x02TS")); - filename = cfgdir->absolutePath() + "/Saves/" + recordFileName + "." + *cProtoVer + ".hws"; + if (type == rtDemo) + { + demo.replace(QByteArray("\x02TL"), QByteArray("\x02TD")); + demo.replace(QByteArray("\x02TN"), QByteArray("\x02TD")); + demo.replace(QByteArray("\x02TS"), QByteArray("\x02TD")); + filename = cfgdir->absolutePath() + "/Demos/" + recordFileName + "." + *cProtoVer + ".hwd"; + m_lastDemo = demo; + } + else + { + demo.replace(QByteArray("\x02TL"), QByteArray("\x02TS")); + demo.replace(QByteArray("\x02TN"), QByteArray("\x02TS")); + filename = cfgdir->absolutePath() + "/Saves/" + recordFileName + "." + *cProtoVer + ".hws"; + } + + QFile demofile(filename); + if (!demofile.open(QIODevice::WriteOnly)) + ShowErrorMessage(tr("Cannot save record to file %1").arg(filename)); + else + { + demofile.write(demo); + demofile.close(); + } } - - QFile demofile(filename); - if (!demofile.open(QIODevice::WriteOnly)) + // encode videos + QDir videosDir(cfgdir->absolutePath() + "/VideoTemp/"); + QStringList files = videosDir.entryList(QStringList("*.txtout"), QDir::Files); + foreach (const QString & str, files) { - ShowErrorMessage(tr("Cannot save record to file %1").arg(filename)); - return ; + QString prefix = str; + prefix.chop(7); // remove ".txtout" + videosDir.rename(prefix + ".txtout", prefix + ".txtin"); // rename this file to not open it twice + HWRecorder* pRecorder = new HWRecorder(config, prefix); + ui.pageVideos->addRecorder(pRecorder); + int numFrames = QFileInfo(videosDir.absoluteFilePath(prefix + ".txtin")).size()/16; + pRecorder->EncodeVideo(record, numFrames); } - demofile.write(demo); - demofile.close(); } void HWForm::startTraining(const QString & scriptName) @@ -1445,6 +1474,7 @@ xfire_free(); #endif config->SaveOptions(); + config->SaveVideosOptions(); event->accept(); } diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/hwform.h --- a/QTfrontend/hwform.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/hwform.h Sun Jun 24 21:32:33 2012 +0400 @@ -114,7 +114,7 @@ void GameStateChanged(GameState gameState); void ForcedDisconnect(const QString & reason); void ShowErrorMessage(const QString &); - void GetRecord(bool isDemo, const QByteArray & record); + void GetRecord(RecordType type, const QByteArray & record); void CreateNetGame(); void UpdateWeapons(); void onFrontendFullscreen(bool value); @@ -175,6 +175,7 @@ ID_PAGE_DRAWMAP , ID_PAGE_DATADOWNLOAD , ID_PAGE_FEEDBACK , + ID_PAGE_VIDEOS, MAX_PAGE }; QPointer game; diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/main.cpp --- a/QTfrontend/main.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/main.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -197,6 +197,8 @@ checkForDir(cfgdir->absolutePath() + "/Screenshots"); checkForDir(cfgdir->absolutePath() + "/Teams"); checkForDir(cfgdir->absolutePath() + "/Logs"); + checkForDir(cfgdir->absolutePath() + "/Videos"); + checkForDir(cfgdir->absolutePath() + "/VideoTemp"); } datadir->cd(bindir->absolutePath()); diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/net/recorder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/net/recorder.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,118 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +//#include + +#include "recorder.h" +#include "gameuiconfig.h" +#include "hwconsts.h" +#include "game.h" +#include "libav_iteraction.h" + +HWRecorder::HWRecorder(GameUIConfig * config, const QString &prefix) : + TCPBase(false) +{ + this->config = config; + this->prefix = prefix; + finished = false; + name = prefix + "." + LibavIteraction::instance().getExtension(config->AVFormat()); +} + +HWRecorder::~HWRecorder() +{ + emit encodingFinished(finished); +} + +void HWRecorder::onClientDisconnect() +{ +} + +void HWRecorder::onClientRead() +{ + quint8 msglen; + quint32 bufsize; + while (!readbuffer.isEmpty() && ((bufsize = readbuffer.size()) > 0) && + ((msglen = readbuffer.data()[0]) < bufsize)) + { + QByteArray msg = readbuffer.left(msglen + 1); + readbuffer.remove(0, msglen + 1); + switch (msg.at(1)) + { + case '?': + SendIPC("!"); + break; + case 'p': + emit onProgress(float(++curFrame)/numFrames); + break; + case 'v': + finished = true; + break; + } + } +} + +void HWRecorder::EncodeVideo(const QByteArray & record, int numFrames) +{ + this->numFrames = numFrames; + curFrame = 0; + + toSendBuf = record; + toSendBuf.replace(QByteArray("\x02TD"), QByteArray("\x02TV")); + toSendBuf.replace(QByteArray("\x02TL"), QByteArray("\x02TV")); + toSendBuf.replace(QByteArray("\x02TN"), QByteArray("\x02TV")); + toSendBuf.replace(QByteArray("\x02TS"), QByteArray("\x02TV")); + + // run engine + Start(); +} + +QStringList HWRecorder::getArguments() +{ + QStringList arguments; + QRect resolution = config->rec_Resolution(); + arguments << cfgdir->absolutePath(); + arguments << QString::number(resolution.width()); + arguments << QString::number(resolution.height()); + arguments << "32"; // bpp + arguments << QString("%1").arg(ipc_port); + arguments << "0"; // fullscreen + arguments << "0"; // sound + arguments << "0"; // music + arguments << "0"; // sound volume + arguments << QString::number(config->timerInterval()); + arguments << datadir->absolutePath(); + arguments << (config->isShowFPSEnabled() ? "1" : "0"); + arguments << (config->isAltDamageEnabled() ? "1" : "0"); + arguments << config->netNick().toUtf8().toBase64(); + arguments << QString::number(config->translateQuality()); + arguments << QString::number(config->stereoMode()); + arguments << HWGame::tr("en.txt"); + arguments << QString::number(config->rec_Framerate()); // framerate num + arguments << "1"; // framerate den + arguments << prefix; + arguments << config->AVFormat(); + arguments << config->videoCodec(); + arguments << "5"; // video quality + arguments << "medium"; + arguments << (config->recordAudio()? config->audioCodec() : "no"); + arguments << "5"; // audio quality + + return arguments; +} diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/net/recorder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/net/recorder.h Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,60 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef RECORDER_H +#define RECORDER_H + +#include +#include + +#include "tcpBase.h" + +class GameUIConfig; +class VideoItem; + +class HWRecorder : public TCPBase +{ + Q_OBJECT + public: + HWRecorder(GameUIConfig * config, const QString & prefix); + virtual ~HWRecorder(); + + void EncodeVideo(const QByteArray & record, int numFrames); + + VideoItem * item; // used by pagevideos + QString name; + QString prefix; + + protected: + // virtuals from TCPBase + virtual QStringList getArguments(); + virtual void onClientRead(); + virtual void onClientDisconnect(); + + signals: + void onProgress(float progress); // 0 < progress < 1 + void encodingFinished(bool success); + + private: + int curFrame; + int numFrames; + bool finished; + GameUIConfig * config; +}; + +#endif // RECORDER_H diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/net/tcpBase.cpp --- a/QTfrontend/net/tcpBase.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/net/tcpBase.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -26,8 +26,8 @@ #include "hwconsts.h" -QList srvsList; -QPointer TCPBase::IPCServer(0); +//QList srvsList; +//QPointer TCPBase::IPCServer(0); TCPBase::~TCPBase() { @@ -35,7 +35,7 @@ TCPBase::TCPBase(bool demoMode) : m_isDemoMode(demoMode), - IPCSocket(0) + IPCSocket(0), IPCServer(0) { if(!IPCServer) { @@ -67,7 +67,7 @@ SendToClientFirst(); } -void TCPBase::RealStart() +void TCPBase::/*Real*/Start() { connect(IPCServer, SIGNAL(newConnection()), this, SLOT(NewConnection())); IPCSocket = 0; @@ -88,8 +88,8 @@ disconnect(IPCSocket, SIGNAL(readyRead()), this, SLOT(ClientRead())); onClientDisconnect(); - if(srvsList.size()==1) srvsList.pop_front(); - emit isReadyNow(); + /* if(srvsList.size()==1) srvsList.pop_front(); + emit isReadyNow();*/ IPCSocket->deleteLater(); deleteLater(); } @@ -109,13 +109,13 @@ .arg(error) + bindir->absolutePath() + "/hwengine)"); } +/* void TCPBase::tcpServerReady() { disconnect(srvsList.takeFirst(), SIGNAL(isReadyNow()), this, SLOT(tcpServerReady())); RealStart(); } - void TCPBase::Start() { if(srvsList.isEmpty()) @@ -130,7 +130,7 @@ } RealStart(); -} +}*/ void TCPBase::onClientRead() { diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/net/tcpBase.h --- a/QTfrontend/net/tcpBase.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/net/tcpBase.h Sun Jun 24 21:32:33 2012 +0400 @@ -62,11 +62,11 @@ virtual void onClientDisconnect(); virtual void SendToClientFirst(); + // void RealStart(); private: - static QPointer IPCServer; + /*static*/ QPointer IPCServer; bool m_isDemoMode; - void RealStart(); QPointer IPCSocket; private slots: @@ -75,7 +75,7 @@ void ClientRead(); void StartProcessError(QProcess::ProcessError error); - void tcpServerReady(); + // void tcpServerReady(); }; #endif // _TCPBASE_INCLUDED diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui/page/pagemain.cpp --- a/QTfrontend/ui/page/pagemain.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/ui/page/pagemain.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -85,9 +85,13 @@ bottomLayout->setStretch(0,1); btnBack->setWhatsThis(tr("Exit game")); - - BtnSetup = addButton(":/res/Settings.png", bottomLayout, 1, true); + + BtnVideos = addButton(":/res/Record.png", bottomLayout, 1, true); + BtnVideos->setWhatsThis(tr("Manage videos recorded from game")); + + BtnSetup = addButton(":/res/Settings.png", bottomLayout, 2, true); BtnSetup->setWhatsThis(tr("Edit game preferences")); + return bottomLayout; } diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui/page/pagemain.h --- a/QTfrontend/ui/page/pagemain.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/ui/page/pagemain.h Sun Jun 24 21:32:33 2012 +0400 @@ -34,6 +34,7 @@ QPushButton * BtnFeedback; QPushButton * BtnInfo; QPushButton * BtnDataDownload; + QPushButton * BtnVideos; QLabel * mainNote; private: diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui/page/pagevideos.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/ui/page/pagevideos.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,695 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "hwconsts.h" +#include "pagevideos.h" +#include "igbox.h" +#include "libav_iteraction.h" +#include "gameuiconfig.h" +#include "recorder.h" + +// columns in table with list of video files +enum VideosColumns +{ + vcName, + vcSize, + vcProgress, + + vcNumColumns, +}; + +class VideoItem : public QTableWidgetItem +{ + // note: QTableWidgetItem is not Q_OBJECT + + public: + VideoItem(const QString& name); + ~VideoItem(); + + QString name; + QString desc; // description + HWRecorder * pRecorder; // non NULL if file is being encoded + bool seen; // used when updating directory + float lastSizeUpdate; + + bool ready() + { return !pRecorder; } + + QString path() + { return cfgdir->absoluteFilePath("Videos/" + name); } +}; + +VideoItem::VideoItem(const QString& name) + : QTableWidgetItem(name, UserType) +{ + this->name = name; + pRecorder = NULL; + lastSizeUpdate = 0; +} + +VideoItem::~VideoItem() +{} + +QLayout * PageVideos::bodyLayoutDefinition() +{ + QGridLayout * pPageLayout = new QGridLayout(); + pPageLayout->setColumnStretch(0, 1); + pPageLayout->setColumnStretch(1, 1); + + { + IconedGroupBox* pOptionsGroup = new IconedGroupBox(this); + pOptionsGroup->setIcon(QIcon(":/res/graphicsicon.png")); + pOptionsGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + pOptionsGroup->setTitle(QGroupBox::tr("Video recording options")); + QGridLayout * pOptLayout = new QGridLayout(pOptionsGroup); + + // label for format + QLabel *labelFormat = new QLabel(pOptionsGroup); + labelFormat->setText(QLabel::tr("Format")); + pOptLayout->addWidget(labelFormat, 0, 0); + + // list of supported formats + comboAVFormats = new QComboBox(pOptionsGroup); + pOptLayout->addWidget(comboAVFormats, 0, 1, 1, 4); + LibavIteraction::instance().fillFormats(comboAVFormats); + + // separator + QFrame * hr = new QFrame(pOptionsGroup); + hr->setFrameStyle(QFrame::HLine); + hr->setLineWidth(3); + hr->setFixedHeight(10); + pOptLayout->addWidget(hr, 1, 0, 1, 5); + + // label for audio codec + QLabel *labelACodec = new QLabel(pOptionsGroup); + labelACodec->setText(QLabel::tr("Audio codec")); + pOptLayout->addWidget(labelACodec, 2, 0); + + // list of supported audio codecs + comboAudioCodecs = new QComboBox(pOptionsGroup); + pOptLayout->addWidget(comboAudioCodecs, 2, 1, 1, 3); + + // checkbox 'record audio' + checkRecordAudio = new QCheckBox(pOptionsGroup); + checkRecordAudio->setText(QCheckBox::tr("Record audio")); + pOptLayout->addWidget(checkRecordAudio, 2, 4); + + // separator + hr = new QFrame(pOptionsGroup); + hr->setFrameStyle(QFrame::HLine); + hr->setLineWidth(3); + hr->setFixedHeight(10); + pOptLayout->addWidget(hr, 3, 0, 1, 5); + + // label for video codec + QLabel *labelVCodec = new QLabel(pOptionsGroup); + labelVCodec->setText(QLabel::tr("Video codec")); + pOptLayout->addWidget(labelVCodec, 4, 0); + + // list of supported video codecs + comboVideoCodecs = new QComboBox(pOptionsGroup); + pOptLayout->addWidget(comboVideoCodecs, 4, 1, 1, 4); + + // label for resolution + QLabel *labelRes = new QLabel(pOptionsGroup); + labelRes->setText(QLabel::tr("Resolution")); + pOptLayout->addWidget(labelRes, 5, 0); + + // width + widthEdit = new QLineEdit(pOptionsGroup); + widthEdit->setValidator(new QIntValidator(this)); + pOptLayout->addWidget(widthEdit, 5, 1); + + // x + QLabel *labelX = new QLabel(pOptionsGroup); + labelX->setText("X"); + pOptLayout->addWidget(labelX, 5, 2); + + // height + heightEdit = new QLineEdit(pOptionsGroup); + heightEdit->setValidator(new QIntValidator(pOptionsGroup)); + pOptLayout->addWidget(heightEdit, 5, 3); + + // checkbox 'use game resolution' + checkUseGameRes = new QCheckBox(pOptionsGroup); + checkUseGameRes->setText(QCheckBox::tr("Use game resolution")); + pOptLayout->addWidget(checkUseGameRes, 5, 4); + + // label for framerate + QLabel *labelFramerate = new QLabel(pOptionsGroup); + labelFramerate->setText(QLabel::tr("Framerate")); + pOptLayout->addWidget(labelFramerate, 6, 0); + + // framerate + framerateBox = new QSpinBox(pOptionsGroup); + framerateBox->setRange(1, 200); + framerateBox->setSingleStep(1); + pOptLayout->addWidget(framerateBox, 6, 1); + + // button 'set default options' + btnDefaults = new QPushButton(pOptionsGroup); + btnDefaults->setText(QPushButton::tr("Set default options")); + pOptLayout->addWidget(btnDefaults, 7, 0, 1, 5); + + pPageLayout->addWidget(pOptionsGroup, 1, 0); + } + + { + IconedGroupBox* pTableGroup = new IconedGroupBox(this); + pTableGroup->setIcon(QIcon(":/res/graphicsicon.png")); + pTableGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + pTableGroup->setTitle(QGroupBox::tr("Videos")); + + QStringList columns; + columns << tr("Name"); + columns << tr("Size"); + columns << tr("..."); + + filesTable = new QTableWidget(pTableGroup); + filesTable->setColumnCount(vcNumColumns); + filesTable->setHorizontalHeaderLabels(columns); + filesTable->setSelectionBehavior(QAbstractItemView::SelectRows); + filesTable->setEditTriggers(QAbstractItemView::SelectedClicked); + filesTable->verticalHeader()->hide(); + + QHeaderView * header = filesTable->horizontalHeader(); + int length = header->length(); // FIXME + // header->setResizeMode(QHeaderView::ResizeToContents); + header->resizeSection(vcName, length/2); + header->resizeSection(vcSize, length/4); + header->resizeSection(vcProgress, length/4); + + btnOpenDir = new QPushButton(QPushButton::tr("Open videos directory"), pTableGroup); + + QVBoxLayout *box = new QVBoxLayout(pTableGroup); + box->addWidget(filesTable); + box->addWidget(btnOpenDir); + + pPageLayout->addWidget(pTableGroup, 0, 1, 2, 1); + } + + { + IconedGroupBox* pDescGroup = new IconedGroupBox(this); + pDescGroup->setIcon(QIcon(":/res/graphicsicon.png")); + pDescGroup->setTitle(QGroupBox::tr("Description")); + QGridLayout* pDescLayout = new QGridLayout(pDescGroup); + + labelThumbnail = new QLabel(pDescGroup); + pDescLayout->addWidget(labelThumbnail, 0, 0); + + // label with file description + labelDesc = new QLabel(pDescGroup); + labelDesc->setAlignment(Qt::AlignLeft | Qt::AlignTop); + pDescLayout->addWidget(labelDesc, 0, 1); + + // buttons: play and delete + btnPlay = new QPushButton(QPushButton::tr("Play"), pDescGroup); + pDescLayout->addWidget(btnPlay, 1, 0); + btnDelete = new QPushButton(QPushButton::tr("Delete"), pDescGroup); + pDescLayout->addWidget(btnDelete, 1, 1); + + pPageLayout->addWidget(pDescGroup, 0, 0); + } + + return pPageLayout; +} + +QLayout * PageVideos::footerLayoutDefinition() +{ + return NULL; +} + +void PageVideos::connectSignals() +{ + connect(checkUseGameRes, SIGNAL(stateChanged(int)), this, SLOT(changeUseGameRes(int))); + connect(checkRecordAudio, SIGNAL(stateChanged(int)), this, SLOT(changeRecordAudio(int))); + connect(comboAVFormats, SIGNAL(currentIndexChanged(int)), this, SLOT(changeAVFormat(int))); + connect(btnDefaults, SIGNAL(clicked()), this, SLOT(setDefaultOptions())); + connect(filesTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(cellDoubleClicked(int, int))); + connect(filesTable, SIGNAL(cellChanged(int,int)), this, SLOT(cellChanged(int, int))); + connect(filesTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(currentCellChanged(int,int,int,int))); + connect(btnPlay, SIGNAL(clicked()), this, SLOT(playSelectedFile())); + connect(btnDelete, SIGNAL(clicked()), this, SLOT(deleteSelectedFiles())); + connect(btnOpenDir, SIGNAL(clicked()), this, SLOT(openVideosDirectory())); + + QString path = cfgdir->absolutePath() + "/Videos"; + QFileSystemWatcher * pWatcher = new QFileSystemWatcher(this); + pWatcher->addPath(path); + connect(pWatcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(updateFileList(const QString &))); + updateFileList(path); +} + +PageVideos::PageVideos(QWidget* parent) : AbstractPage(parent), + config(0) +{ + nameChangedFromCode = false; + initPage(); +} + +// user changed file format, we need to update list of codecs +void PageVideos::changeAVFormat(int index) +{ + // remember selected codecs + QString prevVCodec = videoCodec(); + QString prevACodec = audioCodec(); + + // clear lists of codecs + comboVideoCodecs->clear(); + comboAudioCodecs->clear(); + + // get list of codecs for specified format + LibavIteraction::instance().fillCodecs(comboAVFormats->itemData(index).toString(), comboVideoCodecs, comboAudioCodecs); + + // disable audio if there is no audio codec + if (comboAudioCodecs->count() == 0) + { + checkRecordAudio->setChecked(false); + checkRecordAudio->setEnabled(false); + } + else + checkRecordAudio->setEnabled(true); + + // restore selected codecs if possible + int iVCodec = comboVideoCodecs->findData(prevVCodec); + if (iVCodec != -1) + comboVideoCodecs->setCurrentIndex(iVCodec); + int iACodec = comboAudioCodecs->findData(prevACodec); + if (iACodec != -1) + comboAudioCodecs->setCurrentIndex(iACodec); +} + +// user switched checkbox 'use game resolution' +void PageVideos::changeUseGameRes(int state) +{ + if (state && config) + { + // set resolution to game resolution + QRect resolution = config->vid_Resolution(); + widthEdit->setText(QString::number(resolution.width())); + heightEdit->setText(QString::number(resolution.height())); + } + widthEdit->setEnabled(!state); + heightEdit->setEnabled(!state); +} + +// user switched checkbox 'record audio' +void PageVideos::changeRecordAudio(int state) +{ + comboAudioCodecs->setEnabled(!!state); +} + +void PageVideos::setDefaultCodecs() +{ + if (tryCodecs("mp4", "libx264", "libmp3lame")) + return; + if (tryCodecs("mp4", "libx264", "libfaac")) + return; + if (tryCodecs("mp4", "libx264", "libvo_aacenc")) + return; + if (tryCodecs("mp4", "libx264", "aac")) + return; + if (tryCodecs("mp4", "libx264", "mp2")) + return; + if (tryCodecs("avi", "libxvid", "libmp3lame")) + return; + if (tryCodecs("avi", "libxvid", "ac3_fixed")) + return; + if (tryCodecs("avi", "libxvid", "mp2")) + return; + if (tryCodecs("avi", "mpeg4", "libmp3lame")) + return; + if (tryCodecs("avi", "mpeg4", "ac3_fixed")) + return; + if (tryCodecs("avi", "mpeg4", "mp2")) + return; + + // this shouldn't happen, just in case + if (tryCodecs("ogg", "libtheora", "libvorbis")) + return; + tryCodecs("ogg", "libtheora", "flac"); +} + +void PageVideos::setDefaultOptions() +{ + framerateBox->setValue(25); + checkRecordAudio->setChecked(true); + checkUseGameRes->setChecked(true); + setDefaultCodecs(); +} + +bool PageVideos::tryCodecs(const QString & format, const QString & vcodec, const QString & acodec) +{ + // first we should change format + int iFormat = comboAVFormats->findData(format); + if (iFormat == -1) + return false; + comboAVFormats->setCurrentIndex(iFormat); + + // try to find video codec + int iVCodec = comboVideoCodecs->findData(vcodec); + if (iVCodec == -1) + return false; + comboVideoCodecs->setCurrentIndex(iVCodec); + + // try to find audio codec + int iACodec = comboAudioCodecs->findData(acodec); + if (iACodec == -1 && checkRecordAudio->isChecked()) + return false; + if (iACodec != -1) + comboAudioCodecs->setCurrentIndex(iACodec); + + return true; +} + +// get file size as string +QString FileSizeStr(const QString & path) +{ + quint64 size = QFileInfo(path).size(); + + quint64 KiB = 1024; + quint64 MiB = 1024*KiB; + quint64 GiB = 1024*MiB; + QString sizeStr; + if (size >= GiB) + return QString("%1 GiB").arg(QString::number(float(size)/GiB, 'f', 2)); + if (size >= MiB) + return QString("%1 MiB").arg(QString::number(float(size)/MiB, 'f', 2)); + if (size >= KiB) + return QString("%1 KiB").arg(QString::number(float(size)/KiB, 'f', 2)); + return PageVideos::tr("%1 bytes").arg(QString::number(size)); +} + +// set file size in file list in specified row +void PageVideos::updateSize(int row) +{ + VideoItem * item = nameItem(row); + QString path = item->ready()? item->path() : cfgdir->absoluteFilePath("VideoTemp/" + item->pRecorder->name); + filesTable->item(row, vcSize)->setText(FileSizeStr(path)); +} + +void PageVideos::updateFileList(const QString & path) +{ + // mark all files as non seen + int numRows = filesTable->rowCount(); + for (int i = 0; i < numRows; i++) + nameItem(i)->seen = false; + + QStringList files = QDir(path).entryList(QDir::Files); + foreach (const QString & name, files) + { + int row = -1; + foreach (QTableWidgetItem * item, filesTable->findItems(name, Qt::MatchExactly)) + { + if (item->type() != QTableWidgetItem::UserType || !((VideoItem*)item)->ready()) + continue; + row = item->row(); + break; + } + if (row == -1) + row = appendRow(name); + VideoItem * item = nameItem(row); + item->seen = true; + item->desc = ""; + updateSize(row); + } + + // remove all non seen files + for (int i = 0; i < filesTable->rowCount();) + { + VideoItem * item = nameItem(i); + if (item->ready() && !item->seen) + filesTable->removeRow(i); + else + i++; + } +} + +void PageVideos::addRecorder(HWRecorder* pRecorder) +{ + int row = appendRow(pRecorder->name); + VideoItem * item = nameItem(row); + item->pRecorder = pRecorder; + pRecorder->item = item; + + // add progress bar + QProgressBar * progressBar = new QProgressBar(filesTable); + progressBar->setMinimum(0); + progressBar->setMaximum(10000); + progressBar->setValue(0); + connect(pRecorder, SIGNAL(onProgress(float)), this, SLOT(updateProgress(float))); + connect(pRecorder, SIGNAL(encodingFinished(bool)), this, SLOT(encodingFinished(bool))); + filesTable->setCellWidget(row, vcProgress, progressBar); +} + +void PageVideos::updateProgress(float value) +{ + HWRecorder * pRecorder = (HWRecorder*)sender(); + VideoItem * item = (VideoItem*)pRecorder->item; + int row = filesTable->row(item); + + // update file size every percent + if (value - item->lastSizeUpdate > 0.01) + { + updateSize(row); + item->lastSizeUpdate = value; + } + + // update progress bar + QProgressBar * progressBar = (QProgressBar*)filesTable->cellWidget(row, vcProgress); + progressBar->setValue(value*10000); + progressBar->setFormat(QString("%1%").arg(value*100, 0, 'f', 2)); +} + +void PageVideos::encodingFinished(bool success) +{ + HWRecorder * pRecorder = (HWRecorder*)sender(); + VideoItem * item = (VideoItem*)pRecorder->item; + int row = filesTable->row(item); + + if (success) + { + // move file to destination + success = cfgdir->rename("VideoTemp/" + pRecorder->name, "Videos/" + item->name); + if (!success) + { + // unable to rename for some reason (maybe user entered incorrect name); + // try to use temp name instead. + success = cfgdir->rename("VideoTemp/" + pRecorder->name, "Videos/" + pRecorder->name); + if (success) + setName(item, pRecorder->name); + } + } + + if (!success) + { + filesTable->removeRow(row); + return; + } + + filesTable->setCellWidget(row, vcProgress, NULL); // remove progress bar + item->pRecorder = NULL; + updateSize(row); + updateDescription(); +} + +void PageVideos::cellDoubleClicked(int row, int column) +{ + play(row); +} + +void PageVideos::cellChanged(int row, int column) +{ + // user can only edit name + if (column != vcName || nameChangedFromCode) + return; + + // user has edited filename, so we should rename the file + VideoItem * item = nameItem(row); + QString oldName = item->name; + QString newName = item->text(); + item->name = newName; + if (item->ready()) + { + if(!cfgdir->rename("Videos/" + oldName, "Videos/" + newName)) + { + // unable to rename for some reason (maybe user entered incorrect name), + // therefore restore old name in cell + setName(item, oldName); + } + } +} + +void PageVideos::setName(VideoItem * item, const QString & newName) +{ + nameChangedFromCode = true; + item->setText(newName); + nameChangedFromCode = false; + item->name = newName; +} + +int PageVideos::appendRow(const QString & name) +{ + int row = filesTable->rowCount(); + filesTable->setRowCount(row+1); + + // add 'name' item + QTableWidgetItem * item = new VideoItem(name); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); + nameChangedFromCode = true; + filesTable->setItem(row, vcName, item); + nameChangedFromCode = false; + + // add 'size' item + item = new QTableWidgetItem(); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); + item->setTextAlignment(Qt::AlignRight); + filesTable->setItem(row, vcSize, item); + + // add 'progress' item + item = new QTableWidgetItem(); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); + filesTable->setItem(row, vcProgress, item); + + return row; +} + +VideoItem* PageVideos::nameItem(int row) +{ + return (VideoItem*)filesTable->item(row, vcName); +} + +void PageVideos::updateDescription() +{ + VideoItem * item = nameItem(filesTable->currentRow()); + QString desc = ""; + if (item) + { + QString t = item->name; + desc += item->name + "\n"; + // t.replace(".mp4", ".bmp"); + // QMessageBox::information(this, "1", cfgdir->absoluteFilePath("Screenshots/" + t)); + // m_pic.load(cfgdir->absoluteFilePath("Screenshots/" + t)); + // m_pic = m_pic.scaledToWidth(400); + // m_thumbnail.setPixmap(m_pic); + + if (item->ready()) + { + QString path = item->path(); + desc += tr("\nSize: ") + FileSizeStr(path) + "\n"; + if (item->desc == "") + item->desc = LibavIteraction::instance().getFileInfo(path); + desc += item->desc; + } + else + desc += tr("(in progress...)"); + } + labelDesc->setText(desc); +} + +// user selected another cell, so we should change description +void PageVideos::currentCellChanged(int row, int column, int previousRow, int previousColumn) +{ + updateDescription(); +} + +// open video file in external media player +void PageVideos::play(int row) +{ + VideoItem * item = nameItem(row); + if (item->ready()) + QDesktopServices::openUrl(QUrl("file:///" + item->path())); +} + +void PageVideos::playSelectedFile() +{ + int index = filesTable->currentRow(); + if (index != -1) + play(index); +} + +void PageVideos::deleteSelectedFiles() +{ + QList items = filesTable->selectedItems(); + int num = items.size() / vcNumColumns; + if (num == 0) + return; + + // ask user if (s)he is serious + if (QMessageBox::question(this, + tr("Are you sure?"), + tr("Do you really want do remove %1 file(s)?").arg(num), + QMessageBox::Yes | QMessageBox::No) + != QMessageBox::Yes) + return; + + // remove + foreach (QTableWidgetItem * witem, items) + { + if (witem->type() != QTableWidgetItem::UserType) + continue; + VideoItem * item = (VideoItem*)witem; + if (!item->ready()) + item->pRecorder->deleteLater(); + else + cfgdir->remove("Videos/" + item->name); + } +} + +void PageVideos::keyPressEvent(QKeyEvent * pEvent) +{ + if (filesTable->hasFocus()) + { + if (pEvent->key() == Qt::Key_Delete) + { + deleteSelectedFiles(); + return; + } + if (pEvent->key() == Qt::Key_Enter) // doesn't work + { + playSelectedFile(); + return; + } + } + AbstractPage::keyPressEvent(pEvent); +} + +void PageVideos::openVideosDirectory() +{ + QDesktopServices::openUrl(QUrl("file:///"+cfgdir->absolutePath() + "/Videos")); +} diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui/page/pagevideos.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/ui/page/pagevideos.h Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,110 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + + +#ifndef PAGE_VIDEOS_H +#define PAGE_VIDEOS_H + +#include +#include "AbstractPage.h" + +class GameUIConfig; +class HWRecorder; +class VideoItem; + +class PageVideos : public AbstractPage +{ + Q_OBJECT + + public: + PageVideos(QWidget* parent = 0); + + QSpinBox *framerateBox; + QLineEdit *widthEdit; + QLineEdit *heightEdit; + QCheckBox *checkUseGameRes; + QCheckBox *checkRecordAudio; + + GameUIConfig * config; + + QString format() + { return comboAVFormats->itemData(comboAVFormats->currentIndex()).toString(); } + + QString videoCodec() + { return comboVideoCodecs->itemData(comboVideoCodecs->currentIndex()).toString(); } + + QString audioCodec() + { return comboAudioCodecs->itemData(comboAudioCodecs->currentIndex()).toString(); } + + void setDefaultCodecs(); + bool tryCodecs(const QString & format, const QString & vcodec, const QString & acodec); + void addRecorder(HWRecorder* pRecorder); + + private: + // virtuals from AbstractPage + QLayout * bodyLayoutDefinition(); + QLayout * footerLayoutDefinition(); + void connectSignals(); + + // virtual from QWidget + void keyPressEvent(QKeyEvent * pEvent); + + void setName(VideoItem * item, const QString & newName); + void updateSize(int row); + int appendRow(const QString & name); + VideoItem* nameItem(int row); + void play(int row); + void updateDescription(); + + // options group + QComboBox *comboAVFormats; + QComboBox *comboVideoCodecs; + QComboBox *comboAudioCodecs; + QPushButton *btnDefaults; + + // file list group + QTableWidget *filesTable; + QPushButton *btnOpenDir; + + // description group + QPushButton *btnPlay, *btnDelete; + QLabel *labelDesc; + QLabel *labelThumbnail; + QPixmap picThumbnail; + + // this flag is used to distinguish if cell was changed from code or by user + // (in signal cellChanged) + bool nameChangedFromCode; + + private slots: + void changeAVFormat(int index); + void changeUseGameRes(int state); + void changeRecordAudio(int state); + void setDefaultOptions(); + void encodingFinished(bool success); + void updateProgress(float value); + void cellDoubleClicked(int row, int column); + void cellChanged(int row, int column); + void currentCellChanged(int row, int column, int previousRow, int previousColumn); + void playSelectedFile(); + void deleteSelectedFiles(); + void openVideosDirectory(); + void updateFileList(const QString & path); +}; + +#endif // PAGE_VIDEOS_H diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui_hwform.cpp --- a/QTfrontend/ui_hwform.cpp Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/ui_hwform.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -46,6 +46,7 @@ #include "pagegamestats.h" #include "pageplayrecord.h" #include "pagedata.h" +#include "pagevideos.h" #include "hwconsts.h" void Ui_HWForm::setupUi(HWForm *HWForm) @@ -145,4 +146,7 @@ pageFeedback = new PageFeedback(); Pages->addWidget(pageFeedback); + + pageVideos = new PageVideos(); + Pages->addWidget(pageVideos); } diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/ui_hwform.h --- a/QTfrontend/ui_hwform.h Sun Jun 24 13:18:33 2012 -0400 +++ b/QTfrontend/ui_hwform.h Sun Jun 24 21:32:33 2012 +0400 @@ -43,6 +43,7 @@ class PageAdmin; class PageNetType; class PageDrawMap; +class PageVideos; class QStackedLayout; class QFont; class QWidget; @@ -78,6 +79,7 @@ PageNetType *pageNetType; PageCampaign *pageCampaign; PageDrawMap *pageDrawMap; + PageVideos *pageVideos; QStackedLayout *Pages; QFont *font14; diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/util/libav_iteraction.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/util/libav_iteraction.cpp Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,331 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#define __STDC_CONSTANT_MACROS +extern "C" +{ +#include "libavformat/avformat.h" +} +#include +#include +#include +#include + +#include "libav_iteraction.h" +#include "HWApplication.h" + +struct Codec +{ + CodecID id; + bool isAudio; + QString shortName; // used for identification + QString longName; // used for displaying to user + bool isRecomended; +}; + +struct Format +{ + QString shortName; + QString longName; + bool isRecomended; + QString extension; + QVector codecs; +}; + +QList codecs; +QMap formats; + +LibavIteraction & LibavIteraction::instance() +{ + static LibavIteraction instance; + return instance; +} + +// test if given format supports given codec +bool FormatQueryCodec(AVOutputFormat *ofmt, enum CodecID codec_id) +{ +#if LIBAVFORMAT_VERSION_MAJOR >= 54 + return avformat_query_codec(ofmt, codec_id, FF_COMPLIANCE_NORMAL) == 1; +#else + if (ofmt->codec_tag) + return !!av_codec_get_tag(ofmt->codec_tag, codec_id); + return codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec; +#endif +} + +LibavIteraction::LibavIteraction() +{ + // initialize libav and register all codecs and formats + av_register_all(); + + // get list of all codecs + AVCodec* pCodec = NULL; + while (pCodec = av_codec_next(pCodec)) + { +#if LIBAVCODEC_VERSION_MAJOR >= 54 + if (!av_codec_is_encoder(pCodec)) +#else + if (!pCodec->encode) +#endif + continue; + + if (pCodec->capabilities & CODEC_CAP_EXPERIMENTAL) + continue; + + if (pCodec->type != AVMEDIA_TYPE_VIDEO && pCodec->type != AVMEDIA_TYPE_AUDIO) + continue; + + // this encoders seems to be buggy + if (strcmp(pCodec->name, "rv10") == 0 || strcmp(pCodec->name, "rv20") == 0) + continue; + + // doesn't support stereo sound + if (strcmp(pCodec->name, "real_144") == 0) + continue; + +#if LIBAVCODEC_VERSION_MAJOR < 54 + // FIXME: theese doesn't work for some reason + if (strcmp(pCodec->name, "libx264") == 0) + continue; + if (strcmp(pCodec->name, "libxvid") == 0) + continue; +#endif + + if (pCodec->type == AVMEDIA_TYPE_VIDEO) + { + if (pCodec->supported_framerates != NULL) + continue; + + // check if codec supports yuv 4:2:0 format + if (!pCodec->pix_fmts) + continue; + bool yuv420Supported = false; + for (const PixelFormat* pfmt = pCodec->pix_fmts; *pfmt != -1; pfmt++) + if (*pfmt == PIX_FMT_YUV420P) + { + yuv420Supported = true; + break; + } + if (!yuv420Supported) + continue; + } + if (pCodec->type == AVMEDIA_TYPE_AUDIO) + { + // check if codec supports signed 16-bit format + if (!pCodec->sample_fmts) + continue; + bool s16Supported = false; + for (const AVSampleFormat* pfmt = pCodec->sample_fmts; *pfmt != -1; pfmt++) + if (*pfmt == AV_SAMPLE_FMT_S16/* || *pfmt == AV_SAMPLE_FMT_FLT*/) + { + s16Supported = true; + break; + } + if (!s16Supported) + continue; + } + // add codec to list of codecs + codecs.push_back(Codec()); + Codec & codec = codecs.back(); + codec.id = pCodec->id; + codec.isAudio = pCodec->type == AVMEDIA_TYPE_AUDIO; + codec.shortName = pCodec->name; + codec.longName = pCodec->long_name; + + codec.isRecomended = false; + if (strcmp(pCodec->name, "libx264") == 0) + { + codec.longName = "H.264/MPEG-4 Part 10 AVC (x264)"; + codec.isRecomended = true; + } + else if (strcmp(pCodec->name, "libxvid") == 0) + { + codec.longName = "MPEG-4 Part 2 (Xvid)"; + codec.isRecomended = true; + } + else if (strcmp(pCodec->name, "libmp3lame") == 0) + { + codec.longName = "MP3 (MPEG audio layer 3) (LAME)"; + codec.isRecomended = true; + } + else + codec.longName = pCodec->long_name; + + if (strcmp(pCodec->name, "mpeg4") == 0 || strcmp(pCodec->name, "ac3_fixed") == 0) + codec.isRecomended = true; + + // FIXME: remove next line + codec.longName += QString(" (%1)").arg(codec.shortName); + } + + // get list of all formats + AVOutputFormat* pFormat = NULL; + while (pFormat = av_oformat_next(pFormat)) + { + if (!pFormat->extensions) + continue; + + // skip some strange formats to not confuse users + if (strstr(pFormat->long_name, "raw")) + continue; + + Format format; + bool hasVideoCodec = false; + for (QList::iterator codec = codecs.begin(); codec != codecs.end(); ++codec) + { + if (!FormatQueryCodec(pFormat, codec->id)) + continue; + format.codecs.push_back(&*codec); + if (!codec->isAudio) + hasVideoCodec = true; + } + if (!hasVideoCodec) + continue; + + QString ext(pFormat->extensions); + ext.truncate(strcspn(pFormat->extensions, ",")); + format.extension = ext; + format.shortName = pFormat->name; + format.longName = QString("%1 (*.%2)").arg(pFormat->long_name).arg(ext); + + // FIXME: remove next line + format.longName += QString(" (%1)").arg(format.shortName); + + format.isRecomended = strcmp(pFormat->name, "mp4") == 0 || strcmp(pFormat->name, "avi") == 0; + + formats[pFormat->name] = format; + } +} + +void LibavIteraction::fillFormats(QComboBox * pFormats) +{ + // first insert recomended formats + foreach(const Format & format, formats) + if (format.isRecomended) + pFormats->addItem(format.longName, format.shortName); + + // remember where to place separator between recomended and other formats + int sep = pFormats->count(); + + // insert remaining formats + foreach(const Format & format, formats) + if (!format.isRecomended) + pFormats->addItem(format.longName, format.shortName); + + // insert separator if necessary + if (sep != 0 && sep != pFormats->count()) + pFormats->insertSeparator(sep); +} + +void LibavIteraction::fillCodecs(const QString & fmt, QComboBox * pVCodecs, QComboBox * pACodecs) +{ + Format & format = formats[fmt]; + + // first insert recomended codecs + foreach(Codec * codec, format.codecs) + { + if (codec->isRecomended) + { + if (codec->isAudio) + pACodecs->addItem(codec->longName, codec->shortName); + else + pVCodecs->addItem(codec->longName, codec->shortName); + } + } + + // remember where to place separators between recomended and other codecs + int vsep = pVCodecs->count(); + int asep = pACodecs->count(); + + // insert remaining codecs + foreach(Codec * codec, format.codecs) + { + if (!codec->isRecomended) + { + if (codec->isAudio) + pACodecs->addItem(codec->longName, codec->shortName); + else + pVCodecs->addItem(codec->longName, codec->shortName); + } + } + + // insert separators if necessary + if (vsep != 0 && vsep != pVCodecs->count()) + pVCodecs->insertSeparator(vsep); + if (asep != 0 && asep != pACodecs->count()) + pACodecs->insertSeparator(asep); +} + +QString LibavIteraction::getExtension(const QString & format) +{ + return formats[format].extension; +} + +QString tr(QString a) +{ + return a; +} + +// get information abaout file (duration, resolution etc) in multiline string +QString LibavIteraction::getFileInfo(const QString & filepath) +{ + AVFormatContext* pContext = NULL; + QByteArray utf8path = filepath.toUtf8(); + if (avformat_open_input(&pContext, utf8path.data(), NULL, NULL) < 0) + return ""; + if (avformat_find_stream_info(pContext, NULL) < 0) + return ""; + + int s = float(pContext->duration)/AV_TIME_BASE; + QString desc = QString(tr("Duration: %1m %2s\n")).arg(s/60).arg(s%60); + for (int i = 0; i < pContext->nb_streams; i++) + { + AVStream* pStream = pContext->streams[i]; + if (!pStream) + continue; + AVCodecContext* pCodec = pContext->streams[i]->codec; + if (!pCodec) + continue; + + if (pCodec->codec_type == AVMEDIA_TYPE_VIDEO) + { + desc += QString(tr("Video: %1x%2, ")).arg(pCodec->width).arg(pCodec->height); + if (pStream->avg_frame_rate.den) + { + float fps = float(pStream->avg_frame_rate.num)/pStream->avg_frame_rate.den; + desc += QString(tr("%1 fps, ")).arg(fps, 0, 'f', 2); + } + } + else if (pCodec->codec_type == AVMEDIA_TYPE_AUDIO) + desc += tr("Audio: "); + else + continue; + AVCodec* pDecoder = avcodec_find_decoder(pCodec->codec_id); + desc += pDecoder? pDecoder->name : "unknown"; + desc += "\n"; + } + AVDictionaryEntry* pComment = av_dict_get(pContext->metadata, "comment", NULL, 0); + if (pComment) + desc += QString("\n") + pComment->value; +#if LIBAVCODEC_VERSION_MAJOR < 54 + av_close_input_file(pContext); +#else + avformat_close_input(&pContext); +#endif + return desc; +} diff -r b817a478dcfb -r 24c6fa591866 QTfrontend/util/libav_iteraction.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/QTfrontend/util/libav_iteraction.h Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,49 @@ +/* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef LIBAV_ITERACTION +#define LIBAV_ITERACTION + +#include + +/** + * @brief Class for interacting with ffmpeg/libav libraries + * + * @see singleton pattern + */ +class LibavIteraction +{ + LibavIteraction(); + +public: + + static LibavIteraction & instance(); + + // fill combo box with known file formats + void fillFormats(QComboBox * pFormats); + + // fill combo boxes with known codecs for given formats + void fillCodecs(const QString & format, QComboBox * pVCodecs, QComboBox * pACodecs); + + QString getExtension(const QString & format); + + // get information about file (duration, resolution etc) in multiline string + QString getFileInfo(const QString & filepath); +}; + +#endif // LIBAV_ITERACTION diff -r b817a478dcfb -r 24c6fa591866 hedgewars/ArgParsers.inc --- a/hedgewars/ArgParsers.inc Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/ArgParsers.inc Sun Jun 24 21:32:33 2012 +0400 @@ -61,8 +61,27 @@ else cStereoMode:= TStereoMode(max(0, min(ord(high(TStereoMode)), tmp-6))); cLocaleFName:= ParamStr(17); +{$IFDEF USE_VIDEO_RECORDING} + cVideoFramerateNum:= StrToInt(ParamStr(18)); + cVideoFramerateDen:= StrToInt(ParamStr(19)); +{$ENDIF} end; +{$IFDEF USE_VIDEO_RECORDING} +procedure internalStartVideoRecordingWithParameters(); +begin + internalStartGameWithParameters(); + GameType:= gmtRecord; + cRecPrefix:= ParamStr(20); + cAVFormat:= ParamStr(21); + cVideoCodec:= ParamStr(22); + cVideoQuality:= StrToInt(ParamStr(23)); + cVideoPreset:= ParamStr(24); + cAudioCodec:= ParamStr(25); + cAudioQuality:= StrToInt(ParamStr(26)); +end; +{$ENDIF} + procedure setVideo(screenWidth: LongInt; screenHeight: LongInt; bitsStr: LongInt); begin cScreenWidth:= screenWidth; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/CMakeLists.txt --- a/hedgewars/CMakeLists.txt Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/CMakeLists.txt Sun Jun 24 21:32:33 2012 +0400 @@ -59,6 +59,7 @@ uTypes.pas uUtils.pas uVariables.pas + uVideoRec.pas uVisualGears.pas uWorld.pas GSHandlers.inc @@ -184,6 +185,15 @@ set(fpc_flags ${noexecstack_flags} ${pascal_flags} ${hwengine_project}) +IF (WIN32) + set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) + include_directories(${CMAKE_SOURCE_DIR}/misc/winutils/include) + link_directories(${CMAKE_SOURCE_DIR}/misc/winutils/lib) + add_library(avwrapper SHARED avwrapper.c) + target_link_libraries(avwrapper avcodec avformat avutil) +ELSE() + add_library(avwrapper STATIC avwrapper.c) +ENDIF() IF(NOT APPLE) #here is the command for standard executables or for shared library @@ -224,10 +234,12 @@ #this command is a workaround to some inlining issues present in older # FreePascal versions and fixed in 2.6, That version is mandatory on OSX, # hence the command is not needed there -if(NOT APPLE) - add_custom_target(ENGINECLEAN COMMAND ${CMAKE_BUILD_TOOL} "clean" "${PROJECT_BINARY_DIR}" "${hedgewars_SOURCE_DIR}/hedgewars") - add_dependencies(${engine_output_name} ENGINECLEAN) -endif() +# if(NOT APPLE) +# add_custom_target(ENGINECLEAN COMMAND ${CMAKE_BUILD_TOOL} "clean" "${PROJECT_BINARY_DIR}" "${hedgewars_SOURCE_DIR}/hedgewars") +# add_dependencies(${engine_output_name} ENGINECLEAN) +# endif() install(PROGRAMS "${EXECUTABLE_OUTPUT_PATH}/${engine_output_name}${CMAKE_EXECUTABLE_SUFFIX}" DESTINATION ${target_dir}) - +IF (WIN32) + install(PROGRAMS "${EXECUTABLE_OUTPUT_PATH}/${CMAKE_SHARED_LIBRARY_PREFIX}avwrapper${CMAKE_SHARED_LIBRARY_SUFFIX}" DESTINATION ${target_dir}) +ENDIF() diff -r b817a478dcfb -r 24c6fa591866 hedgewars/SDLh.pas --- a/hedgewars/SDLh.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/SDLh.pas Sun Jun 24 21:32:33 2012 +0400 @@ -829,6 +829,8 @@ TMixMusic = record end; + TPostMix = procedure(udata: pointer; stream: PByte; len: LongInt); cdecl; + {* SDL_net *} TIPAddress = record host: LongWord; @@ -959,6 +961,9 @@ function SDL_GL_SetAttribute(attr: TSDL_GLattr; value: LongInt): LongInt; cdecl; external SDLLibName; procedure SDL_GL_SwapBuffers; cdecl; external SDLLibName; +procedure SDL_LockAudio; cdecl; external SDLLibName; +procedure SDL_UnlockAudio; cdecl; external SDLLibName; + function SDL_NumJoysticks: LongInt; cdecl; external SDLLibName; function SDL_JoystickName(idx: LongInt): PChar; cdecl; external SDLLibName; function SDL_JoystickOpen(idx: LongInt): PSDL_Joystick; cdecl; external SDLLibName; @@ -1010,6 +1015,7 @@ function Mix_OpenAudio(frequency: LongInt; format: Word; channels: LongInt; chunksize: LongInt): LongInt; cdecl; external SDL_MixerLibName; procedure Mix_CloseAudio; cdecl; external SDL_MixerLibName; +function Mix_QuerySpec(frequency: PLongInt; format: PWord; channels: PLongInt): LongInt; cdecl; external SDL_MixerLibName; function Mix_Volume(channel: LongInt; volume: LongInt): LongInt; cdecl; external SDL_MixerLibName; function Mix_SetDistance(channel: LongInt; distance: Byte): LongInt; cdecl; external SDL_MixerLibName; @@ -1037,6 +1043,8 @@ function Mix_FadeInChannelTimed(channel: LongInt; chunk: PMixChunk; loops: LongInt; fadems: LongInt; ticks: LongInt): LongInt; cdecl; external SDL_MixerLibName; function Mix_FadeOutChannel(channel: LongInt; fadems: LongInt): LongInt; cdecl; external SDL_MixerLibName; +procedure Mix_SetPostMix( mix_func: TPostMix; arg: pointer); cdecl; external SDL_MixerLibName; + (* SDL_image *) function IMG_Init(flags: LongInt): LongInt; {$IFDEF SDL_IMAGE_NEWER}cdecl; external SDL_ImageLibName;{$ENDIF} procedure IMG_Quit; {$IFDEF SDL_IMAGE_NEWER}cdecl; external SDL_ImageLibName;{$ENDIF} diff -r b817a478dcfb -r 24c6fa591866 hedgewars/avwrapper.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hedgewars/avwrapper.c Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,461 @@ + +#include +#include +#include +#include +#include +#include "libavformat/avformat.h" + +static AVFormatContext* g_pContainer; +static AVOutputFormat* g_pFormat; +static AVStream* g_pAStream; +static AVStream* g_pVStream; +static AVFrame* g_pAFrame; +static AVFrame* g_pVFrame; +static AVCodec* g_pACodec; +static AVCodec* g_pVCodec; +static AVCodecContext* g_pAudio; +static AVCodecContext* g_pVideo; + +static int g_Width, g_Height; +static uint32_t g_Frequency, g_Channels; +static int g_VQuality, g_AQuality; +static AVRational g_Framerate; +static const char* g_pPreset; + +static FILE* g_pSoundFile; +static int16_t* g_pSamples; +static int g_NumSamples; + +/* +Initially I wrote code for latest ffmpeg, but on Linux (Ubuntu) +only older version is available from repository. That's why you see here +all of this #if LIBAVCODEC_VERSION_MAJOR < 54. +Actually, it may be possible to remove code for newer version +and use only code for older version. +*/ + +#if LIBAVCODEC_VERSION_MAJOR < 54 +#define OUTBUFFER_SIZE 200000 +static uint8_t g_OutBuffer[OUTBUFFER_SIZE]; +#endif + +// pointer to function from hwengine (uUtils.pas) +static void (*AddFileLogRaw)(const char* pString); + +static void FatalError(const char* pFmt, ...) +{ + const char Buffer[1024]; + va_list VaArgs; + + va_start(VaArgs, pFmt); + vsnprintf(Buffer, 1024, pFmt, VaArgs); + va_end(VaArgs); + + AddFileLogRaw("Error in av-wrapper: "); + AddFileLogRaw(Buffer); + AddFileLogRaw("\n"); + exit(1); +} + +// Function to be called from libav for logging. +// Note: libav can call LogCallback from different threads +// (there is mutex in AddFileLogRaw). +static void LogCallback(void* p, int Level, const char* pFmt, va_list VaArgs) +{ + const char Buffer[1024]; + + vsnprintf(Buffer, 1024, pFmt, VaArgs); + AddFileLogRaw(Buffer); +} + +static void Log(const char* pFmt, ...) +{ + const char Buffer[1024]; + va_list VaArgs; + + va_start(VaArgs, pFmt); + vsnprintf(Buffer, 1024, pFmt, VaArgs); + va_end(VaArgs); + + AddFileLogRaw(Buffer); +} + +static void AddAudioStream() +{ +#if LIBAVFORMAT_VERSION_MAJOR >= 54 + g_pAStream = avformat_new_stream(g_pContainer, g_pACodec); +#else + g_pAStream = av_new_stream(g_pContainer, 1); +#endif + if(!g_pAStream) + { + Log("Could not allocate audio stream"); + return; + } + g_pAStream->id = 1; + + g_pAudio = g_pAStream->codec; + + avcodec_get_context_defaults3(g_pAudio, g_pACodec); + g_pAudio->codec_id = g_pACodec->id; + + // put parameters + g_pAudio->sample_fmt = AV_SAMPLE_FMT_S16; + g_pAudio->sample_rate = g_Frequency; + g_pAudio->channels = g_Channels; + + // set quality + if (g_AQuality > 100) + g_pAudio->bit_rate = g_AQuality; + else + { + g_pAudio->flags |= CODEC_FLAG_QSCALE; + g_pAudio->global_quality = g_AQuality*FF_QP2LAMBDA; + } + + // some formats want stream headers to be separate + if (g_pFormat->flags & AVFMT_GLOBALHEADER) + g_pAudio->flags |= CODEC_FLAG_GLOBAL_HEADER; + + // open it + if (avcodec_open2(g_pAudio, g_pACodec, NULL) < 0) + { + Log("Could not open audio codec %s", g_pACodec->long_name); + return; + } + +#if LIBAVCODEC_VERSION_MAJOR >= 54 + if (g_pACodec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) +#else + if (g_pAudio->frame_size == 0) +#endif + g_NumSamples = 4096; + else + g_NumSamples = g_pAudio->frame_size; + g_pSamples = (int16_t*)av_malloc(g_NumSamples*g_Channels*sizeof(int16_t)); + g_pAFrame = avcodec_alloc_frame(); + if (!g_pAFrame) + { + Log("Could not allocate frame"); + return; + } +} + +// returns non-zero if there is more sound +static int WriteAudioFrame() +{ + if (!g_pAStream) + return 0; + + AVPacket Packet = { 0 }; + av_init_packet(&Packet); + + int NumSamples = fread(g_pSamples, 2*g_Channels, g_NumSamples, g_pSoundFile); + +#if LIBAVCODEC_VERSION_MAJOR >= 54 + AVFrame* pFrame = NULL; + if (NumSamples > 0) + { + g_pAFrame->nb_samples = NumSamples; + avcodec_fill_audio_frame(g_pAFrame, g_Channels, AV_SAMPLE_FMT_S16, + (uint8_t*)g_pSamples, NumSamples*2*g_Channels, 1); + pFrame = g_pAFrame; + } + // when NumSamples == 0 we still need to call encode_audio2 to flush + int got_packet; + if (avcodec_encode_audio2(g_pAudio, &Packet, pFrame, &got_packet) != 0) + FatalError("avcodec_encode_audio2 failed"); + if (!got_packet) + return 0; +#else + if (NumSamples == 0) + return 0; + int BufferSize = OUTBUFFER_SIZE; + if (g_pAudio->frame_size == 0) + BufferSize = NumSamples*g_Channels*2; + Packet.size = avcodec_encode_audio(g_pAudio, g_OutBuffer, BufferSize, g_pSamples); + if (Packet.size == 0) + return 1; + if (g_pAudio->coded_frame && g_pAudio->coded_frame->pts != AV_NOPTS_VALUE) + Packet.pts = av_rescale_q(g_pAudio->coded_frame->pts, g_pAudio->time_base, g_pAStream->time_base); + Packet.flags |= AV_PKT_FLAG_KEY; + Packet.data = g_OutBuffer; +#endif + + // Write the compressed frame to the media file. + Packet.stream_index = g_pAStream->index; + if (av_interleaved_write_frame(g_pContainer, &Packet) != 0) + FatalError("Error while writing audio frame"); + return 1; +} + +// add a video output stream +static void AddVideoStream() +{ +#if LIBAVFORMAT_VERSION_MAJOR >= 54 + g_pVStream = avformat_new_stream(g_pContainer, g_pVCodec); +#else + g_pVStream = av_new_stream(g_pContainer, 0); +#endif + if (!g_pVStream) + FatalError("Could not allocate video stream"); + + g_pVideo = g_pVStream->codec; + + avcodec_get_context_defaults3(g_pVideo, g_pVCodec); + g_pVideo->codec_id = g_pVCodec->id; + + // put parameters + // resolution must be a multiple of two + g_pVideo->width = g_Width & ~1; // make even (dimensions should be even) + g_pVideo->height = g_Height & ~1; // make even + /* time base: this is the fundamental unit of time (in seconds) in terms + of which frame timestamps are represented. for fixed-fps content, + timebase should be 1/framerate and timestamp increments should be + identically 1. */ + g_pVideo->time_base.den = g_Framerate.num; + g_pVideo->time_base.num = g_Framerate.den; + //g_pVideo->gop_size = 12; /* emit one intra frame every twelve frames at most */ + g_pVideo->pix_fmt = PIX_FMT_YUV420P; + + // set quality + if (g_VQuality > 100) + g_pVideo->bit_rate = g_VQuality; + else + { + g_pVideo->flags |= CODEC_FLAG_QSCALE; + g_pVideo->global_quality = g_VQuality*FF_QP2LAMBDA; + } + + AVDictionary* pDict = NULL; + if (strcmp(g_pVCodec->name, "libx264") == 0) + av_dict_set(&pDict, "preset", g_pPreset, 0); + + // some formats want stream headers to be separate + if (g_pFormat->flags & AVFMT_GLOBALHEADER) + g_pVideo->flags |= CODEC_FLAG_GLOBAL_HEADER; + + // open the codec + if (avcodec_open2(g_pVideo, g_pVCodec, &pDict) < 0) + FatalError("Could not open video codec %s", g_pVCodec->long_name); + + g_pVFrame = avcodec_alloc_frame(); + if (!g_pVFrame) + FatalError("Could not allocate frame"); + + g_pVFrame->linesize[0] = g_Width; + g_pVFrame->linesize[1] = g_Width/2; + g_pVFrame->linesize[2] = g_Width/2; + g_pVFrame->linesize[3] = 0; +} + +static int WriteFrame(AVFrame* pFrame) +{ + double AudioTime, VideoTime; + + // write interleaved audio frame + if (g_pAStream) + { + VideoTime = (double)g_pVStream->pts.val*g_pVStream->time_base.num/g_pVStream->time_base.den; + do + AudioTime = (double)g_pAStream->pts.val*g_pAStream->time_base.num/g_pAStream->time_base.den; + while (AudioTime < VideoTime && WriteAudioFrame()); + } + + if (!g_pVStream) + return 0; + + AVPacket Packet; + av_init_packet(&Packet); + Packet.data = NULL; + Packet.size = 0; + + g_pVFrame->pts++; + if (g_pFormat->flags & AVFMT_RAWPICTURE) + { + /* raw video case. The API will change slightly in the near + future for that. */ + Packet.flags |= AV_PKT_FLAG_KEY; + Packet.stream_index = g_pVStream->index; + Packet.data = (uint8_t*)pFrame; + Packet.size = sizeof(AVPicture); + + if (av_interleaved_write_frame(g_pContainer, &Packet) != 0) + FatalError("Error while writing video frame"); + return 0; + } + else + { +#if LIBAVCODEC_VERSION_MAJOR >= 54 + int got_packet; + if (avcodec_encode_video2(g_pVideo, &Packet, pFrame, &got_packet) < 0) + FatalError("avcodec_encode_video2 failed"); + if (!got_packet) + return 0; + + if (Packet.pts != AV_NOPTS_VALUE) + Packet.pts = av_rescale_q(Packet.pts, g_pVideo->time_base, g_pVStream->time_base); + if (Packet.dts != AV_NOPTS_VALUE) + Packet.dts = av_rescale_q(Packet.dts, g_pVideo->time_base, g_pVStream->time_base); +#else + Packet.size = avcodec_encode_video(g_pVideo, g_OutBuffer, OUTBUFFER_SIZE, pFrame); + if (Packet.size < 0) + FatalError("avcodec_encode_video failed"); + if (Packet.size == 0) + return 0; + + if( g_pVideo->coded_frame->pts != AV_NOPTS_VALUE) + Packet.pts = av_rescale_q(g_pVideo->coded_frame->pts, g_pVideo->time_base, g_pVStream->time_base); + if( g_pVideo->coded_frame->key_frame ) + Packet.flags |= AV_PKT_FLAG_KEY; + Packet.data = g_OutBuffer; +#endif + // write the compressed frame in the media file + Packet.stream_index = g_pVStream->index; + if (av_interleaved_write_frame(g_pContainer, &Packet) != 0) + FatalError("Error while writing video frame"); + + return 1; + } +} + +void AVWrapper_WriteFrame(uint8_t* pY, uint8_t* pCb, uint8_t* pCr) +{ + g_pVFrame->data[0] = pY; + g_pVFrame->data[1] = pCb; + g_pVFrame->data[2] = pCr; + WriteFrame(g_pVFrame); +} + +void AVWrapper_Init( + void (*pAddFileLogRaw)(const char*), + const char* pFilename, + const char* pDesc, + const char* pSoundFile, + const char* pFormatName, + const char* pVCodecName, + const char* pACodecName, + const char* pVPreset, + int Width, int Height, + int FramerateNum, int FramerateDen, + int VQuality, int AQuality) +{ + AddFileLogRaw = pAddFileLogRaw; + av_log_set_callback( &LogCallback ); + + g_Width = Width; + g_Height = Height; + g_Framerate.num = FramerateNum; + g_Framerate.den = FramerateDen; + g_VQuality = VQuality; + g_AQuality = AQuality; + g_pPreset = pVPreset; + + // initialize libav and register all codecs and formats + av_register_all(); + + // find format + g_pFormat = av_guess_format(pFormatName, NULL, NULL); + if (!g_pFormat) + FatalError("Format \"%s\" was not found", pFormatName); + + // allocate the output media context + g_pContainer = avformat_alloc_context(); + if (!g_pContainer) + FatalError("Could not allocate output context"); + + g_pContainer->oformat = g_pFormat; + + // store description of file + av_dict_set(&g_pContainer->metadata, "comment", pDesc, 0); + + // append extesnion to filename + char ext[16]; + strncpy(ext, g_pFormat->extensions, 16); + ext[15] = 0; + ext[strcspn(ext,",")] = 0; + snprintf(g_pContainer->filename, sizeof(g_pContainer->filename), "%s.%s", pFilename, ext); + + // find codecs + g_pVCodec = avcodec_find_encoder_by_name(pVCodecName); + g_pACodec = avcodec_find_encoder_by_name(pACodecName); + + // add audio and video stream to container + g_pVStream = NULL; + g_pAStream = NULL; + + if (g_pVCodec) + AddVideoStream(); + else + Log("Video codec \"%s\" was not found; video will be ignored.\n", pVCodecName); + + if (g_pACodec) + { + g_pSoundFile = fopen(pSoundFile, "rb"); + if (g_pSoundFile) + { + fread(&g_Frequency, 4, 1, g_pSoundFile); + fread(&g_Channels, 4, 1, g_pSoundFile); + AddAudioStream(); + } + else + Log("Could not open %s", pSoundFile); + } + else + Log("Audio codec \"%s\" was not found; audio will be ignored.\n", pACodecName); + + if (!g_pAStream && !g_pVStream) + FatalError("No video, no audio, aborting..."); + + // write format info to log + av_dump_format(g_pContainer, 0, g_pContainer->filename, 1); + + // open the output file, if needed + if (!(g_pFormat->flags & AVFMT_NOFILE)) + { + if (avio_open(&g_pContainer->pb, g_pContainer->filename, AVIO_FLAG_WRITE) < 0) + FatalError("Could not open output file (%s)", pFilename); + } + + // write the stream header, if any + avformat_write_header(g_pContainer, NULL); + + g_pVFrame->pts = -1; +} + +void AVWrapper_Close() +{ + // output buffered frames + if (g_pVCodec->capabilities & CODEC_CAP_DELAY) + while( WriteFrame(NULL) ); + // output any remaining audio + while( WriteAudioFrame() ); + + // write the trailer, if any. + av_write_trailer(g_pContainer); + + // close the output file + if (!(g_pFormat->flags & AVFMT_NOFILE)) + avio_close(g_pContainer->pb); + + // free everything + if (g_pVStream) + { + avcodec_close(g_pVideo); + av_free(g_pVideo); + av_free(g_pVStream); + av_free(g_pVFrame); + } + if (g_pAStream) + { + avcodec_close(g_pAudio); + av_free(g_pAudio); + av_free(g_pAStream); + av_free(g_pAFrame); + av_free(g_pSamples); + fclose(g_pSoundFile); + } + + av_free(g_pContainer); +} diff -r b817a478dcfb -r 24c6fa591866 hedgewars/hwengine.pas --- a/hedgewars/hwengine.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/hwengine.pas Sun Jun 24 21:32:33 2012 +0400 @@ -32,6 +32,7 @@ uses SDLh, uMisc, uConsole, uGame, uConsts, uLand, uAmmos, uVisualGears, uGears, uStore, uWorld, uInputHandler, uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uRandom, uLandTexture, uCollisions, SysUtils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted + {$IFDEF USE_VIDEO_RECORDING}, uVideoRec {$ENDIF} {$IFDEF SDL13}, uTouch{$ENDIF}{$IFDEF ANDROID}, GLUnit{$ENDIF}; {$IFDEF HWLIBRARY} @@ -101,6 +102,11 @@ SwapBuffers; +{$IFDEF USE_VIDEO_RECORDING} + if flagPrerecording then + SaveCameraPosition; +{$ENDIF} + if flagMakeCapture then begin flagMakeCapture:= false; @@ -261,6 +267,33 @@ end; end; +{$IFDEF USE_VIDEO_RECORDING} +procedure RecorderMainLoop; +var CurrTime, PrevTime: LongInt; +begin + if not BeginVideoRecording() then + exit; + DoTimer(0); // gsLandGen -> gsStart + DoTimer(0); // gsStart -> gsGame + + CurrTime:= LoadNextCameraPosition(); + fastScrolling:= true; + DoTimer(CurrTime); + fastScrolling:= false; + while true do + begin + EncodeFrame(); + PrevTime:= CurrTime; + CurrTime:= LoadNextCameraPosition(); + if CurrTime = -1 then + break; + DoTimer(CurrTime - PrevTime); + IPCCheckSock(); + end; + StopVideoRecording(); +end; +{$ENDIF} + /////////////// procedure Game{$IFDEF HWLIBRARY}(gameArgs: PPChar); cdecl; export{$ENDIF}; var p: TPathType; @@ -327,11 +360,16 @@ SDLTry(TTF_Init() <> -1, true); WriteLnToConsole(msgOK); - // show main window - if cFullScreen then - ParseCommand('fullscr 1', true) + if GameType = gmtRecord then + InitOffscreenOpenGL() else - ParseCommand('fullscr 0', true); + begin + // show main window + if cFullScreen then + ParseCommand('fullscr 1', true) + else + ParseCommand('fullscr 0', true); + end; ControllerInit(); // has to happen before InitKbdKeyTable to map keys InitKbdKeyTable(); @@ -368,12 +406,22 @@ InitTeams(); AssignStores(); + + if GameType = gmtRecord then + SetSound(false); + InitSound(); isDeveloperMode:= false; TryDo(InitStepsFlags = cifAllInited, 'Some parameters not set (flags = ' + inttostr(InitStepsFlags) + ')', true); ParseCommand('rotmask', true); - MainLoop(); + +{$IFDEF USE_VIDEO_RECORDING} + if GameType = gmtRecord then + RecorderMainLoop() + else +{$ENDIF} + MainLoop(); // clean up all the memory allocated freeEverything(true); @@ -456,6 +504,7 @@ //uAIAmmoTests does not need to be freed //uAIActions does not need to be freed uStore.freeModule; + uVideoRec.freeModule; end; uIO.freeModule; @@ -529,11 +578,14 @@ else if (ParamCount = 3) and ((ParamStr(3) = '--stats-only') or (ParamStr(3) = 'landpreview')) then internalSetGameTypeLandPreviewFromParameters() + else if ParamCount = cDefaultParamNum then + internalStartGameWithParameters() +{$IFDEF USE_VIDEO_RECORDING} + else if ParamCount = cVideorecParamNum then + internalStartVideoRecordingWithParameters() +{$ENDIF} else - if (ParamCount = cDefaultParamNum) then - internalStartGameWithParameters() - else - playReplayFileWithParameters(); + playReplayFileWithParameters(); end; //////////////////////////////////////////////////////////////////////////////// diff -r b817a478dcfb -r 24c6fa591866 hedgewars/options.inc --- a/hedgewars/options.inc Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/options.inc Sun Jun 24 21:32:33 2012 +0400 @@ -50,6 +50,7 @@ {$DEFINE USE_TOUCH_INTERFACE} {$ELSE} {$DEFINE USE_AM_NUMCOLUMN} + {$DEFINE USE_VIDEO_RECORDING} {$ENDIF} diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uCommandHandlers.pas --- a/hedgewars/uCommandHandlers.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uCommandHandlers.pas Sun Jun 24 21:32:33 2012 +0400 @@ -26,7 +26,8 @@ procedure freeModule; implementation -uses uCommands, uTypes, uVariables, uIO, uDebug, uConsts, uScript, uUtils, SDLh, uRandom, uCaptions; +uses uCommands, uTypes, uVariables, uIO, uDebug, uConsts, uScript, uUtils, SDLh, uRandom, uCaptions + {$IFDEF USE_VIDEO_RECORDING}, uVideoRec {$ENDIF}; var prevGState: TGameState = gsConfirm; @@ -529,6 +530,17 @@ flagMakeCapture:= true end; +procedure chRecord(var s: shortstring); +begin +s:= s; // avoid compiler hint +{$IFDEF USE_VIDEO_RECORDING} +if flagPrerecording then + StopPreRecording() +else + BeginPreRecording(); +{$ENDIF} +end; + procedure chSetMap(var s: shortstring); begin if isDeveloperMode then @@ -865,6 +877,7 @@ RegisterVariable('-cur_l' , @chCurL_m , true ); RegisterVariable('+cur_r' , @chCurR_p , true ); RegisterVariable('-cur_r' , @chCurR_m , true ); + RegisterVariable('record' , @chRecord , true ); end; procedure freeModule; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uConsts.pas --- a/hedgewars/uConsts.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uConsts.pas Sun Jun 24 21:32:33 2012 +0400 @@ -27,7 +27,12 @@ const sfMax = 1000; +{$IFNDEF USE_VIDEO_RECORDING} cDefaultParamNum = 17; +{$ELSE} + cDefaultParamNum = 19; + cVideorecParamNum = cDefaultParamNum + 7; +{$ENDIF} // message constants errmsgCreateSurface = 'Error creating SDL surface'; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uGame.pas --- a/hedgewars/uGame.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uGame.pas Sun Jun 24 21:32:33 2012 +0400 @@ -39,17 +39,20 @@ isInLag:= false; SendKeepAliveMessage(Lag) end; -if Lag > 100 then - Lag:= 100 -else if (GameType = gmtSave) or (fastUntilLag and (GameType = gmtNet)) then - Lag:= 2500; +if GameType <> gmtRecord then + begin + if Lag > 100 then + Lag:= 100 + else if (GameType = gmtSave) or (fastUntilLag and (GameType = gmtNet)) then + Lag:= 2500; -if (GameType = gmtDemo) then - if isSpeed then - Lag:= Lag * 10 - else - if cOnlyStats then - Lag:= High(LongInt); + if (GameType = gmtDemo) then + if isSpeed then + Lag:= Lag * 10 + else + if cOnlyStats then + Lag:= High(LongInt); + end; PlayNextVoice; i:= 1; while (GameState <> gsExit) and (i <= Lag) do diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uGearsHedgehog.pas --- a/hedgewars/uGearsHedgehog.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uGearsHedgehog.pas Sun Jun 24 21:32:33 2012 +0400 @@ -602,7 +602,7 @@ if (not (HH^.Hedgehog^.Team^.ExtDriven or (HH^.Hedgehog^.BotLevel > 0))) or (HH^.Hedgehog^.Team^.Clan^.ClanIndex = LocalClan) - or (GameType = gmtDemo) then + or (GameType in [gmtDemo, gmtRecord]) then begin s:= trammo[Ammoz[a].NameId] + ' (+' + IntToStr(Ammoz[a].NumberInCase) + ')'; AddCaption(s, HH^.Hedgehog^.Team^.Clan^.Color, capgrpAmmoinfo); diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uIO.pas --- a/hedgewars/uIO.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uIO.pas Sun Jun 24 21:32:33 2012 +0400 @@ -126,6 +126,7 @@ 'D': GameType:= gmtDemo; 'N': GameType:= gmtNet; 'S': GameType:= gmtSave; + 'V': GameType:= gmtRecord; else OutError(errmsgIncorrectUse + ' IPC "T" :' + s[2], true) end; else loTicks:= SDLNet_Read16(@s[byte(s[0]) - 1]); diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uInputHandler.pas --- a/hedgewars/uInputHandler.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uInputHandler.pas Sun Jun 24 21:32:33 2012 +0400 @@ -249,6 +249,7 @@ DefaultBinds[KeyNameToCode(_S'0')]:= '+volup'; DefaultBinds[KeyNameToCode(_S'9')]:= '+voldown'; DefaultBinds[KeyNameToCode(_S'c')]:= 'capture'; +DefaultBinds[KeyNameToCode(_S'r')]:= 'record'; DefaultBinds[KeyNameToCode(_S'h')]:= 'findhh'; DefaultBinds[KeyNameToCode(_S'p')]:= 'pause'; DefaultBinds[KeyNameToCode(_S's')]:= '+speedup'; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uStore.pas --- a/hedgewars/uStore.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uStore.pas Sun Jun 24 21:32:33 2012 +0400 @@ -40,13 +40,16 @@ procedure ShowWeaponTooltip(x, y: LongInt); procedure FreeWeaponTooltip; procedure MakeCrossHairs; +{$IFDEF USE_VIDEO_RECORDING} +procedure InitOffscreenOpenGL; +{$ENDIF} procedure WarpMouse(x, y: Word); inline; procedure SwapBuffers; inline; implementation uses uMisc, uConsole, uMobile, uVariables, uUtils, uTextures, uRender, uRenderUtils, uCommands, - uDebug{$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF}; + uDebug{$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF} {$IFDEF USE_VIDEO_RECORDING}, glut {$ENDIF}; //type TGPUVendor = (gvUnknown, gvNVIDIA, gvATI, gvIntel, gvApple); @@ -438,6 +441,31 @@ IMG_Quit(); end; +{$IF NOT DEFINED(S3D_DISABLED) OR DEFINED(USE_VIDEO_RECORDING)} +procedure CreateFramebuffer(var frame, depth, tex: GLuint); +begin + glGenFramebuffersEXT(1, @frame); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frame); + glGenRenderbuffersEXT(1, @depth); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, cScreenWidth, cScreenHeight); + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth); + glGenTextures(1, @tex); + glBindTexture(GL_TEXTURE_2D, tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cScreenWidth, cScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex, 0); +end; + +procedure DeleteFramebuffer(var frame, depth, tex: GLuint); +begin + glDeleteTextures(1, @tex); + glDeleteRenderbuffersEXT(1, @depth); + glDeleteFramebuffersEXT(1, @frame); +end; +{$ENDIF} + procedure StoreRelease(reload: boolean); var ii: TSprite; ai: TAmmoType; @@ -511,15 +539,15 @@ end; end; end; +{$IFDEF USE_VIDEO_RECORDING} + if defaultFrame <> 0 then + DeleteFramebuffer(defaultFrame, depthv, texv); +{$ENDIF} {$IFNDEF S3D_DISABLED} if (cStereoMode = smHorizontal) or (cStereoMode = smVertical) or (cStereoMode = smAFR) then begin - glDeleteTextures(1, @texl); - glDeleteRenderbuffersEXT(1, @depthl); - glDeleteFramebuffersEXT(1, @framel); - glDeleteTextures(1, @texr); - glDeleteRenderbuffersEXT(1, @depthr); - glDeleteFramebuffersEXT(1, @framer) + DeleteFramebuffer(framel, depthl, texl); + DeleteFramebuffer(framer, depthr, texr); end {$ENDIF} end; @@ -628,6 +656,7 @@ procedure SetupOpenGL; //var vendor: shortstring = ''; var buf: array[byte] of char; + AuxBufNum: LongInt; begin buf[0]:= char(0); // avoid compiler hint AddFileLog('Setting up OpenGL (using driver: ' + shortstring(SDL_VideoDriverName(buf, sizeof(buf))) + ')'); @@ -673,14 +702,43 @@ {$ENDIF} //SupportNPOTT:= glLoadExtension('GL_ARB_texture_non_power_of_two'); *) + glGetIntegerv(GL_AUX_BUFFERS, @AuxBufNum); // everyone love debugging AddFileLog('OpenGL-- Renderer: ' + shortstring(pchar(glGetString(GL_RENDERER)))); AddFileLog(' |----- Vendor: ' + shortstring(pchar(glGetString(GL_VENDOR)))); AddFileLog(' |----- Version: ' + shortstring(pchar(glGetString(GL_VERSION)))); AddFileLog(' |----- Texture Size: ' + inttostr(MaxTextureSize)); - AddFileLog(' \----- Extensions: ' + shortstring(pchar(glGetString(GL_EXTENSIONS)))); - //TODO: don't have the Extensions line trimmed but slipt it into multiple lines + AddFileLog(' |----- Number of auxilary buffers: ' + inttostr(AuxBufNum)); + AddFileLog(' \----- Extensions: '); + AddFileLogRaw(glGetString(GL_EXTENSIONS)); + AddFileLog(''); + //TODO: slipt Extensions line into multiple lines + + defaultFrame:= 0; +{$IFDEF USE_VIDEO_RECORDING} + if GameType = gmtRecord then + begin + if AuxBufNum > 0 then + begin + glDrawBuffer(GL_AUX0); + glReadBuffer(GL_AUX0); + AddFileLog('Using auxilary buffer for video recording.'); + end + else if glLoadExtension('GL_EXT_framebuffer_object') then + begin + CreateFramebuffer(defaultFrame, depthv, texv); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, defaultFrame); + AddFileLog('Using framebuffer for video recording.'); + end + else + begin + glDrawBuffer(GL_BACK); + glReadBuffer(GL_BACK); + AddFileLog('Warning: off-screen rendering is not supported; using back buffer but it may not work.'); + end; + end; +{$ENDIF} {$IFNDEF S3D_DISABLED} if (cStereoMode = smHorizontal) or (cStereoMode = smVertical) or (cStereoMode = smAFR) then @@ -688,36 +746,11 @@ // prepare left and right frame buffers and associated textures if glLoadExtension('GL_EXT_framebuffer_object') then begin - // left - glGenFramebuffersEXT(1, @framel); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framel); - glGenRenderbuffersEXT(1, @depthl); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthl); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, cScreenWidth, cScreenHeight); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthl); - glGenTextures(1, @texl); - glBindTexture(GL_TEXTURE_2D, texl); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cScreenWidth, cScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texl, 0); - - // right - glGenFramebuffersEXT(1, @framer); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framer); - glGenRenderbuffersEXT(1, @depthr); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthr); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, cScreenWidth, cScreenHeight); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthr); - glGenTextures(1, @texr); - glBindTexture(GL_TEXTURE_2D, texr); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cScreenWidth, cScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texr, 0); + CreateFramebuffer(framel, depthl, texl); + CreateFramebuffer(framer, depthr, texr); // reset - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0) + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, defaultFrame) end else cStereoMode:= smNone; @@ -991,6 +1024,21 @@ WeaponTooltipTex:= nil end; +{$IFDEF USE_VIDEO_RECORDING} +procedure InitOffscreenOpenGL; +var ArgCount: LongInt; + PrgName: pchar; +begin + ArgCount:= 1; + PrgName:= 'hwengine'; + glutInit(@ArgCount, @PrgName); + glutInitWindowSize(cScreenWidth, cScreenHeight); + glutCreateWindow('You don''t see this'); // we don't need a window, but if this function is not called then OpenGL will not be initialized + glutHideWindow(); + SetupOpenGL(); +end; +{$ENDIF} + procedure chFullScr(var s: shortstring); var flags: Longword = 0; reinit: boolean = false; @@ -1171,6 +1219,8 @@ procedure SwapBuffers; inline; begin + if GameType = gmtRecord then + exit; {$IFDEF SDL13} SDL_GL_SwapWindow(SDLwindow); {$ELSE} diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uTeams.pas --- a/hedgewars/uTeams.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uTeams.pas Sun Jun 24 21:32:33 2012 +0400 @@ -531,7 +531,7 @@ AddTeam(Color); CurrentTeam^.TeamName:= ts; CurrentTeam^.PlayerHash:= s; - if GameType in [gmtDemo, gmtSave] then + if GameType in [gmtDemo, gmtSave, gmtRecord] then CurrentTeam^.ExtDriven:= true; CurrentTeam^.voicepack:= AskForVoicepack('Default') diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uTypes.pas --- a/hedgewars/uTypes.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uTypes.pas Sun Jun 24 21:32:33 2012 +0400 @@ -39,7 +39,7 @@ TGameState = (gsLandGen, gsStart, gsGame, gsChat, gsConfirm, gsExit, gsSuspend); // Game types that help determining what the engine is actually supposed to do - TGameType = (gmtLocal, gmtDemo, gmtNet, gmtSave, gmtLandPreview, gmtSyntax); + TGameType = (gmtLocal, gmtDemo, gmtNet, gmtSave, gmtLandPreview, gmtSyntax, gmtRecord); // Different files are stored in different folders, this enumeration is used to tell which folder to use TPathType = (ptNone, ptData, ptGraphics, ptThemes, ptCurrTheme, ptTeams, ptMaps, diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uUtils.pas --- a/hedgewars/uUtils.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uUtils.pas Sun Jun 24 21:32:33 2012 +0400 @@ -61,6 +61,7 @@ function CheckCJKFont(s: ansistring; font: THWFont): THWFont; procedure AddFileLog(s: shortstring); +procedure AddFileLogRaw(s: pchar); cdecl; function CheckNoTeamOrHH: boolean; inline; @@ -81,6 +82,9 @@ {$IFDEF DEBUGFILE} var f: textfile; +{$IFDEF USE_VIDEO_RECORDING} + logMutex: TRTLCriticalSection; // mutex for debug file +{$ENDIF} {$ENDIF} var CharArray: array[byte] of Char; @@ -303,11 +307,31 @@ begin s:= s; {$IFDEF DEBUGFILE} +{$IFDEF USE_VIDEO_RECORDING} +EnterCriticalSection(logMutex); +{$ENDIF} writeln(f, inttostr(GameTicks) + ': ' + s); -flush(f) +flush(f); +{$IFDEF USE_VIDEO_RECORDING} +LeaveCriticalSection(logMutex); +{$ENDIF} {$ENDIF} end; +procedure AddFileLogRaw(s: pchar); cdecl; +begin +s:= s; +{$IFDEF DEBUGFILE} +{$IFDEF USE_VIDEO_RECORDING} +EnterCriticalSection(logMutex); +{$ENDIF} +write(f, s); +flush(f); +{$IFDEF USE_VIDEO_RECORDING} +LeaveCriticalSection(logMutex); +{$ENDIF} +{$ENDIF} +end; function CheckCJKFont(s: ansistring; font: THWFont): THWFont; var l, i : LongInt; @@ -400,6 +424,9 @@ logfileBase:= 'game' else logfileBase:= 'preview'; +{$IFDEF USE_VIDEO_RECORDING} + InitCriticalSection(logMutex); +{$ENDIF} {$I-} {$IFDEF MOBILE} {$IFDEF IPHONEOS} Assign(f,'../Documents/hw-' + logfileBase + '.log'); {$ENDIF} @@ -436,6 +463,9 @@ writeln(f, 'halt at ' + inttostr(GameTicks) + ' ticks. TurnTimeLeft = ' + inttostr(TurnTimeLeft)); flush(f); close(f); +{$IFDEF USE_VIDEO_RECORDING} + DoneCriticalSection(logMutex); +{$ENDIF} {$ENDIF} end; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uVariables.pas --- a/hedgewars/uVariables.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uVariables.pas Sun Jun 24 21:32:33 2012 +0400 @@ -52,6 +52,17 @@ cReadyDelay : Longword = 5000; cStereoMode : TStereoMode = smNone; cOnlyStats : boolean = False; +{$IFDEF USE_VIDEO_RECORDING} + cRecPrefix : shortstring; + cAVFormat : shortstring; + cVideoCodec : shortstring; + cVideoFramerateNum : LongInt = 25; + cVideoFramerateDen : LongInt = 1; + cVideoQuality : LongInt; + cVideoPreset : shortstring; + cAudioCodec : shortstring; + cAudioQuality : LongInt; +{$ENDIF} ////////////////////////// cMapName : shortstring = ''; @@ -62,6 +73,7 @@ isSpeed : boolean; fastUntilLag : boolean; + fastScrolling : boolean; autoCameraOn : boolean; GameTicks : LongWord; @@ -2439,6 +2451,10 @@ framel, framer, depthl, depthr: GLuint; texl, texr: GLuint; + // video recorder framebuffer and texture + defaultFrame, depthv: GLuint; + texv: GLuint; + VisualGearLayers: array[0..6] of PVisualGear; lastVisualGearByUID: PVisualGear; vobFrameTicks, vobFramesCount, vobCount: Longword; @@ -2563,7 +2579,7 @@ cExplosives := 2; GameState := Low(TGameState); - GameType := gmtLocal; +// GameType := gmtLocal; zoom := cDefaultZoomLevel; ZoomValue := cDefaultZoomLevel; WeaponTooltipTex:= nil; @@ -2579,6 +2595,7 @@ isInMultiShoot := false; isSpeed := false; fastUntilLag := false; + fastScrolling := false; autoCameraOn := true; cScriptName := ''; cSeed := ''; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uVideoRec.pas --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hedgewars/uVideoRec.pas Sun Jun 24 21:32:33 2012 +0400 @@ -0,0 +1,305 @@ +(* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2004-2012 Andrey Korotaev + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + *) + +{$INCLUDE "options.inc"} + +unit uVideoRec; + +{$IFDEF UNIX} + {$LINKLIB avwrapper} + {$LINKLIB avutil} + {$LINKLIB avcodec} + {$LINKLIB avformat} +{$ENDIF} + +interface + +var flagPrerecording: boolean = false; + +function BeginVideoRecording: Boolean; +function LoadNextCameraPosition: LongInt; +procedure EncodeFrame; +procedure StopVideoRecording; + +procedure BeginPreRecording; +procedure StopPreRecording; +procedure SaveCameraPosition; + +procedure freeModule; + +implementation + +uses uVariables, uUtils, GLunit, SDLh, SysUtils, uIO; + +{$IFDEF WIN32} +const AVWrapperLibName = 'libavwrapper.dll'; +{$ENDIF} + +type TAddFileLogRaw = procedure (s: pchar); cdecl; + +{$IFDEF WIN32} +procedure AVWrapper_Init( + AddLog: TAddFileLogRaw; + filename, desc, soundFile, format, vcodec, acodec, preset: PChar; + width, height, framerateNum, framerateDen, vquality, aquality: LongInt); cdecl; external AVWrapperLibName; +procedure AVWrapper_Close; cdecl; external AVWrapperLibName; +procedure AVWrapper_WriteFrame( pY, pCb, pCr: PByte ); cdecl; external AVWrapperLibName; +{$ELSE} +procedure AVWrapper_Init( + AddLog: TAddFileLogRaw; + filename, desc, soundFile, format, vcodec, acodec, preset: PChar; + width, height, framerateNum, framerateDen, vquality, aquality: LongInt); cdecl; external; +procedure AVWrapper_Close; cdecl; external; +procedure AVWrapper_WriteFrame( pY, pCb, pCr: PByte ); cdecl; external; +{$ENDIF} + +type TFrame = record + ticks: LongWord; + CamX, CamY: LongInt; + zoom: single; + end; + +var YCbCr_Planes: array[0..2] of PByte; + RGB_Buffer: PByte; + cameraFile: File of TFrame; + audioFile: File; + numPixels: LongWord; + startTime, numFrames: LongWord; + cameraFilePath, soundFilePath: shortstring; + +function BeginVideoRecording: Boolean; +var filename, desc: shortstring; +begin + AddFileLog('BeginVideoRecording'); + + numPixels:= cScreenWidth*cScreenHeight; + +{$IOCHECKS OFF} + // open file with prerecorded camera positions + cameraFilePath:= UserPathPrefix + '/VideoTemp/' + cRecPrefix + '.txtin'; + Assign(cameraFile, cameraFilePath); + Reset(cameraFile); + if IOResult <> 0 then + begin + AddFileLog('Error: Could not read from ' + cameraFilePath); + exit(false); + end; +{$IOCHECKS ON} + + desc:= ''; + if UserNick <> '' then + desc+= 'Player: ' + UserNick + #10; + if recordFileName <> '' then + desc+= 'Record: ' + recordFileName + #10; + if cMapName <> '' then + desc+= 'Map: ' + cMapName + #10; + if Theme <> '' then + desc+= 'Theme: ' + Theme + #10; + desc+= #0; + + filename:= UserPathPrefix + '/VideoTemp/' + cRecPrefix + #0; + soundFilePath:= UserPathPrefix + '/VideoTemp/' + cRecPrefix + '.sw' + #0; + cAVFormat+= #0; + cAudioCodec+= #0; + cVideoCodec+= #0; + cVideoPreset+= #0; + AVWrapper_Init(@AddFileLogRaw, @filename[1], @desc[1], @soundFilePath[1], @cAVFormat[1], @cVideoCodec[1], @cAudioCodec[1], @cVideoPreset[1], + cScreenWidth, cScreenHeight, cVideoFramerateNum, cVideoFramerateDen, cAudioQuality, cVideoQuality); + + YCbCr_Planes[0]:= GetMem(numPixels); + YCbCr_Planes[1]:= GetMem(numPixels div 4); + YCbCr_Planes[2]:= GetMem(numPixels div 4); + + if (YCbCr_Planes[0] = nil) or (YCbCr_Planes[1] = nil) or (YCbCr_Planes[2] = nil) then + begin + AddFileLog('Error: Could not allocate memory for video recording (YCbCr buffer).'); + exit(false); + end; + + RGB_Buffer:= GetMem(4*numPixels); + if RGB_Buffer = nil then + begin + AddFileLog('Error: Could not allocate memory for video recording (RGB buffer).'); + exit(false); + end; + + BeginVideoRecording:= true; +end; + +procedure StopVideoRecording; +begin + AddFileLog('StopVideoRecording'); + FreeMem(YCbCr_Planes[0], numPixels); + FreeMem(YCbCr_Planes[1], numPixels div 4); + FreeMem(YCbCr_Planes[2], numPixels div 4); + FreeMem(RGB_Buffer, 4*numPixels); + Close(cameraFile); + AVWrapper_Close(); + DeleteFile(cameraFilePath); + DeleteFile(soundFilePath); + SendIPC(_S'v'); +end; + +function pixel(x, y, color: LongInt): LongInt; +begin + pixel:= RGB_Buffer[(cScreenHeight-y-1)*cScreenWidth*4 + x*4 + color]; +end; + +procedure EncodeFrame; +var x, y, r, g, b: LongInt; +begin + // read pixels from OpenGL + glReadPixels(0, 0, cScreenWidth, cScreenHeight, GL_RGBA, GL_UNSIGNED_BYTE, RGB_Buffer); + + // convert to YCbCr 4:2:0 format + // Y + for y := 0 to cScreenHeight-1 do + for x := 0 to cScreenWidth-1 do + YCbCr_Planes[0][y*cScreenWidth + x]:= Byte(16 + ((16828*pixel(x,y,0) + 33038*pixel(x,y,1) + 6416*pixel(x,y,2)) shr 16)); + + // Cb and Cr + for y := 0 to cScreenHeight div 2 - 1 do + for x := 0 to cScreenWidth div 2 - 1 do + begin + r:= pixel(2*x,2*y,0) + pixel(2*x+1,2*y,0) + pixel(2*x,2*y+1,0) + pixel(2*x+1,2*y+1,0); + g:= pixel(2*x,2*y,1) + pixel(2*x+1,2*y,1) + pixel(2*x,2*y+1,1) + pixel(2*x+1,2*y+1,1); + b:= pixel(2*x,2*y,2) + pixel(2*x+1,2*y,2) + pixel(2*x,2*y+1,2) + pixel(2*x+1,2*y+1,2); + YCbCr_Planes[1][y*(cScreenWidth div 2) + x]:= Byte(128 + ((-2428*r - 4768*g + 7196*b) shr 16)); + YCbCr_Planes[2][y*(cScreenWidth div 2) + x]:= Byte(128 + (( 7196*r - 6026*g - 1170*b) shr 16)); + end; + + AVWrapper_WriteFrame(YCbCr_Planes[0], YCbCr_Planes[1], YCbCr_Planes[2]); + + // inform frontend that we have encoded new frame (p for progress) + SendIPC(_S'p'); +end; + +// returns new game ticks +function LoadNextCameraPosition: LongInt; +var frame: TFrame; +begin +{$IOCHECKS OFF} + if eof(cameraFile) then + exit(-1); + BlockRead(cameraFile, frame, 1); +{$IOCHECKS ON} + WorldDx:= frame.CamX; + WorldDy:= frame.CamY + cScreenHeight div 2; + zoom:= frame.zoom*cScreenWidth; + ZoomValue:= zoom; + LoadNextCameraPosition:= frame.ticks; +end; + +// Callback which records sound. +// This procedure may be called from different thread. +procedure RecordPostMix(udata: pointer; stream: PByte; len: LongInt); cdecl; +begin + udata:= udata; // avoid warning +{$IOCHECKS OFF} + BlockWrite(audioFile, stream^, len); +{$IOCHECKS ON} +end; + +procedure BeginPreRecording; +var format: word; + filePrefix, filename: shortstring; + frequency, channels: LongInt; +begin + AddFileLog('BeginPreRecording'); + + numFrames:= 0; + startTime:= SDL_GetTicks(); + + filePrefix:= FormatDateTime('YYYY-MM-DD_HH-mm-ss', Now()); + + Mix_QuerySpec(@frequency, @format, @channels); + AddFileLog('sound: frequency = ' + IntToStr(frequency) + ', format = ' + IntToStr(format) + ', channels = ' + IntToStr(channels)); + if format <> $8010 then + begin + // TODO: support any audio format + AddFileLog('Error: Unexpected audio format ' + IntToStr(format)); + exit; + end; + +{$IOCHECKS OFF} + // create sound file + filename:= UserPathPrefix + '/VideoTemp/' + filePrefix + '.sw'; + Assign(audioFile, filename); + Rewrite(audioFile, 1); + if IOResult <> 0 then + begin + AddFileLog('Error: Could not write to ' + filename); + exit; + end; + + // create file with camera positions + filename:= UserPathPrefix + '/VideoTemp/' + filePrefix + '.txtout'; + Assign(cameraFile, filename); + Rewrite(cameraFile); + if IOResult <> 0 then + begin + AddFileLog('Error: Could not write to ' + filename); + exit; + end; + + BlockWrite(audioFile, frequency, 4); + BlockWrite(audioFile, channels, 4); +{$IOCHECKS ON} + + // register callback for actual audio recording + Mix_SetPostMix(@RecordPostMix, nil); + + flagPrerecording:= true; +end; + +procedure StopPreRecording; +begin + AddFileLog('StopPreRecording'); + flagPrerecording:= false; + + // call SDL_LockAudio because RecordPostMix may be executing right now + SDL_LockAudio(); + Close(audioFile); + Close(cameraFile); + Mix_SetPostMix(nil, nil); + SDL_UnlockAudio(); +end; + +procedure SaveCameraPosition; +var curTime: LongInt; + frame: TFrame; +begin + curTime:= SDL_GetTicks(); + while Int64(curTime - startTime)*cVideoFramerateNum > Int64(numFrames)*cVideoFramerateDen*1000 do + begin + frame.ticks:= GameTicks; + frame.CamX:= WorldDx; + frame.CamY:= WorldDy - cScreenHeight div 2; + frame.zoom:= zoom/cScreenWidth; + BlockWrite(cameraFile, frame, 1); + inc(numFrames); + end; +end; + +procedure freeModule; +begin + if flagPrerecording then + StopPreRecording(); +end; + +end. diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uVisualGears.pas --- a/hedgewars/uVisualGears.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uVisualGears.pas Sun Jun 24 21:32:33 2012 +0400 @@ -135,7 +135,7 @@ sp: real; begin AddVisualGear:= nil; -if ((GameType = gmtSave) or (fastUntilLag and (GameType = gmtNet))) and // we are scrolling now +if ((GameType = gmtSave) or (fastUntilLag and (GameType = gmtNet)) or fastScrolling) and // we are scrolling now ((Kind <> vgtCloud) and (not Critical)) then exit; diff -r b817a478dcfb -r 24c6fa591866 hedgewars/uWorld.pas --- a/hedgewars/uWorld.pas Sun Jun 24 13:18:33 2012 -0400 +++ b/hedgewars/uWorld.pas Sun Jun 24 21:32:33 2012 +0400 @@ -60,7 +60,8 @@ uCaptions, uCursor, uCommands, - uMobile + uMobile, + uVideoRec ; var cWaveWidth, cWaveHeight: LongInt; @@ -80,6 +81,7 @@ stereoDepth: GLfloat; isFirstFrame: boolean; AMAnimType: LongInt; + recTexture: PTexture; const cStereo_Sky = 0.0500; cStereo_Horizon = 0.0250; @@ -377,6 +379,8 @@ timeTexture:= nil; FreeTexture(missionTex); missionTex:= nil; + FreeTexture(recTexture); + recTexture:= nil; end; function GetAmmoMenuTexture(Ammo: PHHAmmo): PTexture; @@ -954,7 +958,7 @@ //glPushMatrix; //glScalef(1.0, 1.0, 1.0); - if not isPaused then + if (not isPaused) and (GameType <> gmtRecord) then MoveCamera; if cStereoMode = smNone then @@ -985,7 +989,7 @@ DrawWorldStereo(0, rmRightEye); // detatch drawing from fbs - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, defaultFrame); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); SetScale(cDefaultZoomLevel); @@ -1566,6 +1570,33 @@ end end; +{$IFDEF USE_VIDEO_RECORDING} +// during video prerecording draw red blinking circle and text 'rec' +if flagPrerecording then + begin + if recTexture = nil then + begin + s:= 'rec'; + tmpSurface:= TTF_RenderUTF8_Blended(Fontz[fntBig].Handle, Str2PChar(s), cWhiteColorChannels); + tmpSurface:= doSurfaceConversion(tmpSurface); + FreeTexture(recTexture); + recTexture:= Surface2Tex(tmpSurface, false); + SDL_FreeSurface(tmpSurface) + end; + DrawTexture( -(cScreenWidth shr 1) + 50, 20, recTexture); + + // draw red circle + glDisable(GL_TEXTURE_2D); + Tint($FF, $00, $00, Byte(Round(127*(1 + sin(SDL_GetTicks()*0.007))))); + glBegin(GL_POLYGON); + for i:= 0 to 20 do + glVertex2f(-(cScreenWidth shr 1) + 30 + sin(i*2*Pi/20)*10, 35 + cos(i*2*Pi/20)*10); + glEnd(); + Tint($FF, $FF, $FF, $FF); + glEnable(GL_TEXTURE_2D); + end; +{$ENDIF} + SetScale(zoom); // Cursor @@ -1748,8 +1779,12 @@ if (not cHasFocus) and (GameState <> gsConfirm) then ParseCommand('quit', true); -if not cHasFocus then DampenAudio() -else UndampenAudio(); +// do not change volume during prerecording as it will affect sound in video file +if not flagPrerecording then + begin + if not cHasFocus then DampenAudio() + else UndampenAudio(); + end; end; procedure SetUtilityWidgetState(ammoType: TAmmoType); @@ -1806,6 +1841,7 @@ procedure initModule; begin fpsTexture:= nil; + recTexture:= nil; FollowGear:= nil; WindBarWidth:= 0; bShowAmmoMenu:= false; @@ -1836,7 +1872,9 @@ FreeTexture(timeTexture); timeTexture:= nil; FreeTexture(missionTex); - missionTex:= nil + missionTex:= nil; + FreeTexture(recTexture); + recTexture:= nil; end; end. diff -r b817a478dcfb -r 24c6fa591866 project_files/hedgewars.pro --- a/project_files/hedgewars.pro Sun Jun 24 13:18:33 2012 -0400 +++ b/project_files/hedgewars.pro Sun Jun 24 21:32:33 2012 +0400 @@ -104,7 +104,10 @@ ../QTfrontend/ui/dialog/input_password.h \ ../QTfrontend/ui/widget/colorwidget.h \ ../QTfrontend/model/HatModel.h \ - ../QTfrontend/model/GameStyleModel.h + ../QTfrontend/model/GameStyleModel.h \ + ../QTfrontend/util/libav_iteraction.h \ + ../QTfrontend/ui/page/pagevideos.h \ + ../QTfrontend/net/recorder.h SOURCES += ../QTfrontend/model/ammoSchemeModel.cpp \ ../QTfrontend/model/MapModel.cpp \ @@ -186,7 +189,10 @@ ../QTfrontend/ui/dialog/input_password.cpp \ ../QTfrontend/ui/widget/colorwidget.cpp \ ../QTfrontend/model/HatModel.cpp \ - ../QTfrontend/model/GameStyleModel.cpp + ../QTfrontend/model/GameStyleModel.cpp \ + ../QTfrontend/util/libav_iteraction.cpp \ + ../QTfrontend/ui/page/pagevideos.cpp \ + ../QTfrontend/net/recorder.cpp win32 { SOURCES += ../QTfrontend/xfire.cpp