PlayerComponent.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. #include "PlayerComponent.h"
  2. #include <QString>
  3. #include <Qt>
  4. #include <QDir>
  5. #include <QCoreApplication>
  6. #include <QGuiApplication>
  7. #include "display/DisplayComponent.h"
  8. #include "settings/SettingsComponent.h"
  9. #include "system/SystemComponent.h"
  10. #include "utils/Utils.h"
  11. #include "utils/Log.h"
  12. #include "ComponentManager.h"
  13. #include "settings/SettingsSection.h"
  14. #include "PlayerQuickItem.h"
  15. #include "input/InputComponent.h"
  16. #include "QsLog.h"
  17. #include <math.h>
  18. #include <string.h>
  19. #include <shared/Paths.h>
  20. #if !defined(Q_OS_WIN)
  21. #include <unistd.h>
  22. #endif
  23. #if !defined(Q_OS_WIN)
  24. #include <unistd.h>
  25. #endif
  26. #ifdef TARGET_RPI
  27. #include <bcm_host.h>
  28. #include <interface/vmcs_host/vcgencmd.h>
  29. #endif
  30. ///////////////////////////////////////////////////////////////////////////////////////////////////
  31. static void wakeup_cb(void *context)
  32. {
  33. PlayerComponent *player = (PlayerComponent *)context;
  34. emit player->onMpvEvents();
  35. }
  36. ///////////////////////////////////////////////////////////////////////////////////////////////////
  37. PlayerComponent::PlayerComponent(QObject* parent)
  38. : ComponentBase(parent), m_state(State::finished), m_paused(false), m_playbackActive(false),
  39. m_windowVisible(false), m_videoPlaybackActive(false), m_inPlayback(false), m_playbackCanceled(false),
  40. m_bufferingPercentage(100), m_lastBufferingPercentage(-1),
  41. m_lastPositionUpdate(0.0), m_playbackAudioDelay(0),
  42. m_window(nullptr), m_mediaFrameRate(0),
  43. m_restoreDisplayTimer(this), m_reloadAudioTimer(this),
  44. m_streamSwitchImminent(false), m_doAc3Transcoding(false),
  45. m_videoRectangle(-1, -1, -1, -1)
  46. {
  47. qmlRegisterType<PlayerQuickItem>("Konvergo", 1, 0, "MpvVideo"); // deprecated name
  48. qmlRegisterType<PlayerQuickItem>("Konvergo", 1, 0, "KonvergoVideo");
  49. m_restoreDisplayTimer.setSingleShot(true);
  50. connect(&m_restoreDisplayTimer, &QTimer::timeout, this, &PlayerComponent::onRestoreDisplay);
  51. connect(&DisplayComponent::Get(), &DisplayComponent::refreshRateChanged, this, &PlayerComponent::onRefreshRateChange);
  52. m_reloadAudioTimer.setSingleShot(true);
  53. connect(&m_reloadAudioTimer, &QTimer::timeout, this, &PlayerComponent::updateAudioDevice);
  54. }
  55. /////////////////////////////////////////////////////////////////////////////////////////
  56. void PlayerComponent::componentPostInitialize()
  57. {
  58. InputComponent::Get().registerHostCommand("player", this, "userCommand");
  59. }
  60. ///////////////////////////////////////////////////////////////////////////////////////////////////
  61. PlayerComponent::~PlayerComponent()
  62. {
  63. if (m_mpv)
  64. mpv_set_wakeup_callback(m_mpv, nullptr, nullptr);
  65. }
  66. ///////////////////////////////////////////////////////////////////////////////////////////////////
  67. bool PlayerComponent::componentInitialize()
  68. {
  69. m_mpv = mpv::qt::Handle::FromRawHandle(mpv_create());
  70. if (!m_mpv)
  71. throw FatalException(tr("Failed to load mpv."));
  72. mpv_request_log_messages(m_mpv, "terminal-default");
  73. mpv::qt::set_property(m_mpv, "msg-level", "all=v");
  74. // Configuration properties defined in the mpv.conf will override our
  75. // hardcoded properties below.
  76. mpv::qt::set_property(m_mpv, "config", "yes");
  77. mpv::qt::set_property(m_mpv, "config-dir", Paths::dataDir());
  78. mpv_set_wakeup_callback(m_mpv, wakeup_cb, this);
  79. // Disable native OSD if mpv_command_string() is used.
  80. mpv::qt::set_property(m_mpv, "osd-level", "0");
  81. // This forces the player not to rebase playback time to 0 with mkv. We
  82. // require this, because mkv transcoding lets files start at times other
  83. // than 0, and web-client expects that we return these times unchanged.
  84. mpv::qt::set_property(m_mpv, "demuxer-mkv-probe-start-time", false);
  85. // Upstream mpv sets this to "auto", which disables probing for HLS (at least),
  86. // in order to speed up playback start. The situation is more complex in PMP
  87. // due to us wanting to use system codecs, so always enable this.
  88. mpv::qt::set_property(m_mpv, "demuxer-lavf-probe-info", true);
  89. // Just discard audio output if no audio device could be opened. This gives
  90. // us better flexibility how to react to such errors (instead of just
  91. // aborting playback immediately).
  92. mpv::qt::set_property(m_mpv, "audio-fallback-to-null", "yes");
  93. // Do not let the decoder downmix (better customization for us).
  94. mpv::qt::set_property(m_mpv, "ad-lavc-downmix", false);
  95. // Make it load the hwdec interop, so hwdec can be enabled at runtime.
  96. mpv::qt::set_property(m_mpv, "hwdec-preload", "auto");
  97. // User-visible application name used by some audio APIs (at least PulseAudio).
  98. mpv::qt::set_property(m_mpv, "audio-client-name", QCoreApplication::applicationName());
  99. // User-visible stream title used by some audio APIs (at least PulseAudio and wasapi).
  100. mpv::qt::set_property(m_mpv, "title", QCoreApplication::applicationName());
  101. // See: https://github.com/plexinc/plex-media-player/issues/736
  102. mpv::qt::set_property(m_mpv, "cache-seek-min", 5000);
  103. if (!SettingsComponent::Get().ignoreSSLErrors()) {
  104. mpv::qt::set_property(m_mpv, "tls-ca-file", "");
  105. mpv::qt::set_property(m_mpv, "tls-verify", "no");
  106. } else {
  107. #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
  108. QList<QByteArray> list;
  109. list << "/etc/ssl/certs/ca-certificates.crt"
  110. << "/etc/pki/tls/certs/ca-bundle.crt"
  111. << "/usr/share/ssl/certs/ca-bundle.crt"
  112. << "/usr/local/share/certs/ca-root-nss.crt"
  113. << "/etc/ssl/cert.pem"
  114. << "/usr/share/curl/curl-ca-bundle.crt"
  115. << "/usr/local/share/curl/curl-ca-bundle.crt"
  116. << "/var/lib/ca-certificates/ca-bundle.pem";
  117. bool success = false;
  118. for (auto path : list)
  119. {
  120. if (access(path.data(), R_OK) == 0) {
  121. mpv::qt::set_property(m_mpv, "tls-ca-file", path.data());
  122. mpv::qt::set_property(m_mpv, "tls-verify", "yes");
  123. success = true;
  124. break;
  125. }
  126. }
  127. if (!success)
  128. throw FatalException(tr("Failed to locate CA bundle."));
  129. #else
  130. // We need to not use Shinchiro's personal CA file...
  131. mpv::qt::set_property(m_mpv, "tls-ca-file", "");
  132. #endif
  133. }
  134. // Apply some low-memory settings on RPI, which is relatively memory-constrained.
  135. #ifdef TARGET_RPI
  136. // The backbuffer makes seeking back faster (without having to do a HTTP-level seek)
  137. mpv::qt::set_property(m_mpv, "cache-backbuffer", 10 * 1024); // KB
  138. // The demuxer queue is used for the readahead, and also for dealing with badly
  139. // interlaved audio/video. Setting it too low increases sensitivity to network
  140. // issues, and could cause playback failure with "bad" files.
  141. mpv::qt::set_property(m_mpv, "demuxer-max-bytes", 50 * 1024 * 1024); // bytes
  142. // Specifically for enabling mpeg4.
  143. mpv::qt::set_property(m_mpv, "hwdec-codecs", "all");
  144. // Do not use exact seeks by default. (This affects the start position in the "loadfile"
  145. // command in particular. We override the seek mode for normal "seek" commands.)
  146. mpv::qt::set_property(m_mpv, "hr-seek", "no");
  147. // Force vo_rpi to fullscreen.
  148. mpv::qt::set_property(m_mpv, "fullscreen", true);
  149. #endif
  150. if (mpv_initialize(m_mpv) < 0)
  151. throw FatalException(tr("Failed to initialize mpv."));
  152. mpv_observe_property(m_mpv, 0, "pause", MPV_FORMAT_FLAG);
  153. mpv_observe_property(m_mpv, 0, "core-idle", MPV_FORMAT_FLAG);
  154. mpv_observe_property(m_mpv, 0, "cache-buffering-state", MPV_FORMAT_INT64);
  155. mpv_observe_property(m_mpv, 0, "playback-time", MPV_FORMAT_DOUBLE);
  156. mpv_observe_property(m_mpv, 0, "vo-configured", MPV_FORMAT_FLAG);
  157. mpv_observe_property(m_mpv, 0, "duration", MPV_FORMAT_DOUBLE);
  158. mpv_observe_property(m_mpv, 0, "audio-device-list", MPV_FORMAT_NODE);
  159. mpv_observe_property(m_mpv, 0, "video-dec-params", MPV_FORMAT_NODE);
  160. // Setup a hook with the ID 1, which is run during the file is loaded.
  161. // Used to delay playback start for display framerate switching.
  162. // (See handler in handleMpvEvent() for details.)
  163. // Setup a hook with the ID 2, which is run at a certain stage during loading.
  164. // We use it to initialize stream selections and to probe the codecs.
  165. #if MPV_CLIENT_API_VERSION < MPV_MAKE_VERSION(1, 100)
  166. mpv::qt::command(m_mpv, QStringList() << "hook-add" << "on_load" << "1" << "0");
  167. mpv::qt::command(m_mpv, QStringList() << "hook-add" << "on_preloaded" << "2" << "0");
  168. #else
  169. mpv_hook_add(m_mpv, 1, "on_load", 0);
  170. mpv_hook_add(m_mpv, 2, "on_preloaded", 0);
  171. #endif
  172. updateAudioDeviceList();
  173. setAudioConfiguration();
  174. updateSubtitleSettings();
  175. updateVideoSettings();
  176. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_VIDEO), &SettingsSection::valuesUpdated,
  177. this, &PlayerComponent::updateVideoSettings);
  178. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_SUBTITLES), &SettingsSection::valuesUpdated,
  179. this, &PlayerComponent::updateSubtitleSettings);
  180. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_AUDIO), &SettingsSection::valuesUpdated,
  181. this, &PlayerComponent::setAudioConfiguration);
  182. initializeCodecSupport();
  183. Codecs::initCodecs();
  184. QString codecInfo;
  185. for (auto codec : Codecs::getCachedCodecList())
  186. {
  187. if (codec.present)
  188. {
  189. if (codecInfo.size())
  190. codecInfo += " ";
  191. codecInfo += codec.driver;
  192. if (codec.type == CodecType::Encoder)
  193. codecInfo += "(enc)";
  194. }
  195. }
  196. QLOG_INFO() << "Present codecs:" << qPrintable(codecInfo);
  197. connect(this, &PlayerComponent::onMpvEvents, this, &PlayerComponent::handleMpvEvents, Qt::QueuedConnection);
  198. emit onMpvEvents();
  199. return true;
  200. }
  201. ///////////////////////////////////////////////////////////////////////////////////////////////////
  202. void PlayerComponent::setVideoRectangle(int x, int y, int w, int h)
  203. {
  204. QRect rc(x, y, w, h);
  205. if (rc != m_videoRectangle)
  206. {
  207. m_videoRectangle = rc;
  208. emit onVideoRecangleChanged();
  209. }
  210. }
  211. ///////////////////////////////////////////////////////////////////////////////////////////////////
  212. void PlayerComponent::setQtQuickWindow(QQuickWindow* window)
  213. {
  214. PlayerQuickItem* video = window->findChild<PlayerQuickItem*>("video");
  215. if (!video)
  216. throw FatalException(tr("Failed to load video element."));
  217. video->initMpv(this);
  218. }
  219. ///////////////////////////////////////////////////////////////////////////////////////////////////
  220. void PlayerComponent::setWindow(QQuickWindow* window)
  221. {
  222. QString vo = "libmpv";
  223. #ifdef TARGET_RPI
  224. window->setFlags(Qt::FramelessWindowHint);
  225. vo = "rpi";
  226. #endif
  227. m_window = window;
  228. if (!window)
  229. return;
  230. QString forceVo = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "debug.force_vo").toString();
  231. if (forceVo.size())
  232. vo = forceVo;
  233. mpv::qt::set_property(m_mpv, "vo", vo);
  234. if (vo == "libmpv")
  235. setQtQuickWindow(window);
  236. }
  237. ///////////////////////////////////////////////////////////////////////////////////////////////////
  238. bool PlayerComponent::load(const QString& url, const QVariantMap& options, const QVariantMap &metadata, const QString& audioStream , const QString& subtitleStream)
  239. {
  240. stop();
  241. queueMedia(url, options, metadata, audioStream, subtitleStream);
  242. return true;
  243. }
  244. ///////////////////////////////////////////////////////////////////////////////////////////////////
  245. void PlayerComponent::queueMedia(const QString& url, const QVariantMap& options, const QVariantMap &metadata, const QString& audioStream, const QString& subtitleStream)
  246. {
  247. InputComponent::Get().cancelAutoRepeat();
  248. m_mediaFrameRate = metadata["frameRate"].toFloat(); // returns 0 on failure
  249. m_serverMediaInfo = metadata["media"].toMap();
  250. updateVideoSettings();
  251. QUrl qurl = url;
  252. QString host = qurl.host();
  253. QVariantList command;
  254. command << "loadfile" << qurl.toString(QUrl::FullyEncoded);
  255. command << "append-play"; // if nothing is playing, play it now, otherwise just enqueue it
  256. QVariantMap extraArgs;
  257. quint64 startMilliseconds = options["startMilliseconds"].toLongLong();
  258. if (startMilliseconds != 0)
  259. extraArgs.insert("start", "+" + QString::number(startMilliseconds / 1000.0));
  260. // we're going to select these streams later, in the preloaded hook
  261. extraArgs.insert("aid", "no");
  262. extraArgs.insert("sid", "no");
  263. m_currentSubtitleStream = subtitleStream;
  264. m_currentAudioStream = audioStream;
  265. if (metadata["type"] == "music")
  266. extraArgs.insert("vid", "no");
  267. extraArgs.insert("pause", options["autoplay"].toBool() ? "no" : "yes");
  268. QString userAgent = metadata["headers"].toMap()["User-Agent"].toString();
  269. if (userAgent.size())
  270. extraArgs.insert("user-agent", userAgent);
  271. // Make sure the list of requested codecs is reset.
  272. extraArgs.insert("ad", "");
  273. extraArgs.insert("vd", "");
  274. command << extraArgs;
  275. mpv::qt::command(m_mpv, command);
  276. emit onMetaData(metadata["metadata"].toMap(), qurl.adjusted(QUrl::RemovePath | QUrl::RemoveQuery));
  277. }
  278. /////////////////////////////////////////////////////////////////////////////////////////
  279. void PlayerComponent::streamSwitch()
  280. {
  281. m_streamSwitchImminent = true;
  282. }
  283. ///////////////////////////////////////////////////////////////////////////////////////////////////
  284. bool PlayerComponent::switchDisplayFrameRate()
  285. {
  286. QLOG_DEBUG() << "Video framerate:" << m_mediaFrameRate << "fps";
  287. if (!SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.auto_switch").toBool())
  288. {
  289. QLOG_DEBUG() << "Not switching refresh-rate (disabled by settings).";
  290. return false;
  291. }
  292. bool fs = SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "fullscreen").toBool();
  293. #if KONVERGO_OPENELEC
  294. fs = true;
  295. #endif
  296. if (!fs)
  297. {
  298. QLOG_DEBUG() << "Not switching refresh-rate (not in fullscreen mode).";
  299. return false;
  300. }
  301. if (m_mediaFrameRate < 1)
  302. {
  303. QLOG_DEBUG() << "Not switching refresh-rate (no known video framerate).";
  304. return false;
  305. }
  306. // Make sure a timer started by the previous file ending isn't accidentally
  307. // still in-flight. It could switch the display back after we've switched.
  308. m_restoreDisplayTimer.stop();
  309. DisplayComponent* display = &DisplayComponent::Get();
  310. if (!display->switchToBestVideoMode(m_mediaFrameRate))
  311. {
  312. QLOG_DEBUG() << "Switching refresh-rate failed or unnecessary.";
  313. return false;
  314. }
  315. // Make sure settings dependent on the display refresh rate are updated properly.
  316. updateVideoSettings();
  317. return true;
  318. }
  319. ///////////////////////////////////////////////////////////////////////////////////////////////////
  320. void PlayerComponent::onRestoreDisplay()
  321. {
  322. // If the player will in fact start another file (or is playing one), don't restore.
  323. if (mpv::qt::get_property(m_mpv, "idle-active").toBool())
  324. DisplayComponent::Get().restorePreviousVideoMode();
  325. }
  326. ///////////////////////////////////////////////////////////////////////////////////////////////////
  327. void PlayerComponent::onRefreshRateChange()
  328. {
  329. // Make sure settings dependent on the display refresh rate are updated properly.
  330. updateVideoSettings();
  331. }
  332. ///////////////////////////////////////////////////////////////////////////////////////////////////
  333. void PlayerComponent::updatePlaybackState()
  334. {
  335. State newState = m_state;
  336. if (m_inPlayback) {
  337. if (m_paused)
  338. {
  339. newState = State::paused;
  340. }
  341. else if (m_playbackActive)
  342. {
  343. newState = State::playing;
  344. }
  345. else
  346. {
  347. // Playback not active, but also not buffering means we're in some "other"
  348. // waiting state. Pretend to web-client that we're buffering.
  349. if (m_bufferingPercentage == 100)
  350. m_bufferingPercentage = 0;
  351. newState = State::buffering;
  352. }
  353. }
  354. else
  355. {
  356. if (!m_playbackError.isEmpty())
  357. newState = State::error;
  358. else if (m_playbackCanceled)
  359. newState = State::canceled;
  360. else
  361. newState = State::finished;
  362. }
  363. if (newState != m_state)
  364. {
  365. switch (newState) {
  366. case State::paused:
  367. QLOG_INFO() << "Entering state: paused";
  368. emit paused();
  369. break;
  370. case State::playing:
  371. QLOG_INFO() << "Entering state: playing";
  372. emit playing();
  373. break;
  374. case State::buffering:
  375. QLOG_INFO() << "Entering state: buffering";
  376. m_lastBufferingPercentage = -1; /* force update below */
  377. break;
  378. case State::finished:
  379. QLOG_INFO() << "Entering state: finished";
  380. emit finished();
  381. emit stopped();
  382. break;
  383. case State::canceled:
  384. QLOG_INFO() << "Entering state: canceled";
  385. emit canceled();
  386. emit stopped();
  387. break;
  388. case State::error:
  389. QLOG_INFO() << ("Entering state: error (" + m_playbackError + ")");
  390. emit error(m_playbackError);
  391. break;
  392. }
  393. emit stateChanged(newState, m_state);
  394. m_state = newState;
  395. }
  396. if (m_state == State::buffering && m_lastBufferingPercentage != m_bufferingPercentage)
  397. emit buffering(m_bufferingPercentage);
  398. m_lastBufferingPercentage = m_bufferingPercentage;
  399. bool is_videoPlaybackActive = m_state == State::playing && m_windowVisible;
  400. if (m_videoPlaybackActive != is_videoPlaybackActive)
  401. {
  402. m_videoPlaybackActive = is_videoPlaybackActive;
  403. emit videoPlaybackActive(m_videoPlaybackActive);
  404. }
  405. }
  406. ///////////////////////////////////////////////////////////////////////////////////////////////////
  407. void PlayerComponent::handleMpvEvent(mpv_event *event)
  408. {
  409. switch (event->event_id)
  410. {
  411. case MPV_EVENT_START_FILE:
  412. {
  413. m_inPlayback = true;
  414. break;
  415. }
  416. case MPV_EVENT_END_FILE:
  417. {
  418. mpv_event_end_file *endFile = (mpv_event_end_file *)event->data;
  419. m_inPlayback = false;
  420. m_playbackCanceled = false;
  421. m_playbackError = "";
  422. switch (endFile->reason)
  423. {
  424. case MPV_END_FILE_REASON_ERROR:
  425. {
  426. m_playbackError = mpv_error_string(endFile->error);
  427. break;
  428. }
  429. case MPV_END_FILE_REASON_STOP:
  430. {
  431. m_playbackCanceled = true;
  432. break;
  433. }
  434. }
  435. if (!m_streamSwitchImminent)
  436. m_restoreDisplayTimer.start(0);
  437. m_streamSwitchImminent = false;
  438. break;
  439. }
  440. case MPV_EVENT_PROPERTY_CHANGE:
  441. {
  442. mpv_event_property *prop = (mpv_event_property *)event->data;
  443. if (strcmp(prop->name, "pause") == 0 && prop->format == MPV_FORMAT_FLAG)
  444. {
  445. m_paused = !!*(int *)prop->data;
  446. }
  447. else if (strcmp(prop->name, "core-idle") == 0 && prop->format == MPV_FORMAT_FLAG)
  448. {
  449. m_playbackActive = !*(int *)prop->data;
  450. }
  451. else if (strcmp(prop->name, "cache-buffering-state") == 0)
  452. {
  453. m_bufferingPercentage = prop->format == MPV_FORMAT_INT64 ? (int)*(int64_t *)prop->data : 100;
  454. }
  455. else if (strcmp(prop->name, "playback-time") == 0 && prop->format == MPV_FORMAT_DOUBLE)
  456. {
  457. double pos = *(double*)prop->data;
  458. if (fabs(pos - m_lastPositionUpdate) > 0.015)
  459. {
  460. quint64 ms = (quint64)(qMax(pos * 1000.0, 0.0));
  461. emit positionUpdate(ms);
  462. m_lastPositionUpdate = pos;
  463. }
  464. }
  465. else if (strcmp(prop->name, "vo-configured") == 0)
  466. {
  467. int state = prop->format == MPV_FORMAT_FLAG ? *(int *)prop->data : 0;
  468. m_windowVisible = state;
  469. emit windowVisible(m_windowVisible);
  470. }
  471. else if (strcmp(prop->name, "duration") == 0)
  472. {
  473. if (prop->format == MPV_FORMAT_DOUBLE)
  474. emit updateDuration(*(double *)prop->data * 1000.0);
  475. }
  476. else if (strcmp(prop->name, "audio-device-list") == 0)
  477. {
  478. updateAudioDeviceList();
  479. }
  480. else if (strcmp(prop->name, "video-dec-params") == 0)
  481. {
  482. // Aspect might be known now (or it changed during playback), so update settings
  483. // dependent on the aspect ratio.
  484. updateVideoAspectSettings();
  485. }
  486. break;
  487. }
  488. case MPV_EVENT_LOG_MESSAGE:
  489. {
  490. mpv_event_log_message *msg = (mpv_event_log_message *)event->data;
  491. // Strip the trailing '\n'
  492. size_t len = strlen(msg->text);
  493. if (len > 0 && msg->text[len - 1] == '\n')
  494. len -= 1;
  495. QString logline = QString::fromUtf8(msg->prefix) + ": " + QString::fromUtf8(msg->text, (int)len);
  496. if (msg->log_level >= MPV_LOG_LEVEL_V)
  497. QLOG_DEBUG() << qPrintable(logline);
  498. else if (msg->log_level >= MPV_LOG_LEVEL_INFO)
  499. QLOG_INFO() << qPrintable(logline);
  500. else if (msg->log_level >= MPV_LOG_LEVEL_WARN)
  501. QLOG_WARN() << qPrintable(logline);
  502. else
  503. QLOG_ERROR() << qPrintable(logline);
  504. break;
  505. }
  506. case MPV_EVENT_CLIENT_MESSAGE:
  507. {
  508. mpv_event_client_message *msg = (mpv_event_client_message *)event->data;
  509. if (msg->num_args < 3 || strcmp(msg->args[0], "hook_run") != 0)
  510. break;
  511. QString resumeId = QString::fromUtf8(msg->args[2]);
  512. // Start "on_load" hook.
  513. // This happens when the player is about to load the file, but no actual loading has taken part yet.
  514. // We use this to block loading until we explicitly tell it to continue.
  515. if (!strcmp(msg->args[1], "1"))
  516. {
  517. // Calling this lambda will instruct mpv to continue loading the file.
  518. auto resume = [=] {
  519. QLOG_INFO() << "checking codecs";
  520. startCodecsLoading([=] {
  521. QLOG_INFO() << "resuming loading";
  522. mpv::qt::command(m_mpv, QStringList() << "hook-ack" << resumeId);
  523. });
  524. };
  525. if (switchDisplayFrameRate())
  526. {
  527. // Now wait for some time for mode change - this is needed because mode changing can take some
  528. // time, during which the screen is black, and initializing hardware decoding could fail due
  529. // to various strange OS-related reasons.
  530. // (Better hope the user doesn't try to exit Konvergo during mode change.)
  531. int pause = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.delay").toInt() * 1000;
  532. QLOG_INFO() << "waiting" << pause << "msec after rate switch before loading";
  533. QTimer::singleShot(pause, resume);
  534. }
  535. else
  536. {
  537. resume();
  538. }
  539. break;
  540. }
  541. // Start "on_preloaded" hook.
  542. // Used initialize stream selections and to probe codecs.
  543. if (!strcmp(msg->args[1], "2"))
  544. {
  545. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  546. reselectStream(m_currentAudioStream, MediaType::Audio);
  547. startCodecsLoading([=] {
  548. mpv::qt::command(m_mpv, QStringList() << "hook-ack" << resumeId);
  549. });
  550. break;
  551. }
  552. break;
  553. }
  554. #if MPV_CLIENT_API_VERSION >= MPV_MAKE_VERSION(1, 100)
  555. case MPV_EVENT_HOOK:
  556. {
  557. mpv_event_hook *hook = (mpv_event_hook *)event->data;
  558. uint64_t id = hook->id;
  559. if (!strcmp(hook->name, "on_load"))
  560. {
  561. // Calling this lambda will instruct mpv to continue loading the file.
  562. auto resume = [=] {
  563. QLOG_INFO() << "checking codecs";
  564. startCodecsLoading([=] {
  565. QLOG_INFO() << "resuming loading";
  566. mpv_hook_continue(m_mpv, id);
  567. });
  568. };
  569. if (switchDisplayFrameRate())
  570. {
  571. // Now wait for some time for mode change - this is needed because mode changing can take some
  572. // time, during which the screen is black, and initializing hardware decoding could fail due
  573. // to various strange OS-related reasons.
  574. // (Better hope the user doesn't try to exit Konvergo during mode change.)
  575. int pause = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.delay").toInt() * 1000;
  576. QLOG_INFO() << "waiting" << pause << "msec after rate switch before loading";
  577. QTimer::singleShot(pause, resume);
  578. }
  579. else
  580. {
  581. resume();
  582. }
  583. break;
  584. }
  585. if (!strcmp(hook->name, "on_preloaded"))
  586. {
  587. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  588. reselectStream(m_currentAudioStream, MediaType::Audio);
  589. startCodecsLoading([=] {
  590. mpv_hook_continue(m_mpv, id);
  591. });
  592. break;
  593. }
  594. break;
  595. }
  596. #endif
  597. default:; /* ignore */
  598. }
  599. }
  600. ///////////////////////////////////////////////////////////////////////////////////////////////////
  601. void PlayerComponent::handleMpvEvents()
  602. {
  603. // Process all events, until the event queue is empty.
  604. while (1)
  605. {
  606. mpv_event *event = mpv_wait_event(m_mpv, 0);
  607. if (event->event_id == MPV_EVENT_NONE)
  608. break;
  609. handleMpvEvent(event);
  610. }
  611. // Once we got all status updates, determine the new canonical state.
  612. updatePlaybackState();
  613. }
  614. ///////////////////////////////////////////////////////////////////////////////////////////////////
  615. void PlayerComponent::setVideoOnlyMode(bool enable)
  616. {
  617. if (m_window)
  618. {
  619. QQuickItem *web = m_window->findChild<QQuickItem *>("web");
  620. if (web)
  621. web->setVisible(!enable);
  622. }
  623. }
  624. ///////////////////////////////////////////////////////////////////////////////////////////////////
  625. void PlayerComponent::play()
  626. {
  627. QStringList args = (QStringList() << "set" << "pause" << "no");
  628. mpv::qt::command(m_mpv, args);
  629. }
  630. ///////////////////////////////////////////////////////////////////////////////////////////////////
  631. void PlayerComponent::stop()
  632. {
  633. QStringList args("stop");
  634. mpv::qt::command(m_mpv, args);
  635. }
  636. ///////////////////////////////////////////////////////////////////////////////////////////////////
  637. void PlayerComponent::clearQueue()
  638. {
  639. QStringList args("playlist_clear");
  640. mpv::qt::command(m_mpv, args);
  641. }
  642. ///////////////////////////////////////////////////////////////////////////////////////////////////
  643. void PlayerComponent::pause()
  644. {
  645. QStringList args = (QStringList() << "set" << "pause" << "yes");
  646. mpv::qt::command(m_mpv, args);
  647. }
  648. ///////////////////////////////////////////////////////////////////////////////////////////////////
  649. void PlayerComponent::seekTo(qint64 ms)
  650. {
  651. double timeSecs = ms / 1000.0;
  652. QVariantList args = (QVariantList() << "seek" << timeSecs << "absolute+exact");
  653. mpv::qt::command(m_mpv, args);
  654. }
  655. ///////////////////////////////////////////////////////////////////////////////////////////////////
  656. QVariant PlayerComponent::getAudioDeviceList()
  657. {
  658. return mpv::qt::get_property(m_mpv, "audio-device-list");
  659. }
  660. ///////////////////////////////////////////////////////////////////////////////////////////////////
  661. void PlayerComponent::setAudioDevice(const QString& name)
  662. {
  663. mpv::qt::set_property(m_mpv, "audio-device", name);
  664. }
  665. ///////////////////////////////////////////////////////////////////////////////////////////////////
  666. void PlayerComponent::setVolume(int volume)
  667. {
  668. // Will fail if no audio output opened (i.e. no file playing)
  669. mpv::qt::set_property(m_mpv, "volume", volume);
  670. }
  671. ///////////////////////////////////////////////////////////////////////////////////////////////////
  672. int PlayerComponent::volume()
  673. {
  674. QVariant volume = mpv::qt::get_property(m_mpv, "volume");
  675. if (volume.isValid())
  676. return volume.toInt();
  677. return 0;
  678. }
  679. ///////////////////////////////////////////////////////////////////////////////////////////////////
  680. void PlayerComponent::setMuted(bool muted)
  681. {
  682. // Will fail if no audio output opened (i.e. no file playing)
  683. mpv::qt::set_property(m_mpv, "mute", muted);
  684. }
  685. ///////////////////////////////////////////////////////////////////////////////////////////////////
  686. bool PlayerComponent::muted()
  687. {
  688. QVariant mute = mpv::qt::get_property(m_mpv, "mute");
  689. if (mute.isValid())
  690. return mute.toBool();
  691. return false;
  692. }
  693. ///////////////////////////////////////////////////////////////////////////////////////////////////
  694. QVariantList PlayerComponent::findStreamsForURL(const QString &url)
  695. {
  696. bool isExternal = !url.isEmpty();
  697. QVariantList res;
  698. auto tracks = mpv::qt::get_property(m_mpv, "track-list");
  699. for (auto track : tracks.toList())
  700. {
  701. QVariantMap map = track.toMap();
  702. if (map["external"].toBool() != isExternal)
  703. continue;
  704. if (!isExternal || map["external-filename"].toString() == url)
  705. res += map;
  706. }
  707. return res;
  708. }
  709. ///////////////////////////////////////////////////////////////////////////////////////////////////
  710. void PlayerComponent::reselectStream(const QString &streamSelection, MediaType target)
  711. {
  712. QString streamIdPropertyName;
  713. QString streamAddCommandName;
  714. QString mpvStreamTypeName;
  715. switch (target)
  716. {
  717. case MediaType::Subtitle:
  718. mpvStreamTypeName = "sub";
  719. streamIdPropertyName = "sid";
  720. streamAddCommandName = "sub-add";
  721. break;
  722. case MediaType::Audio:
  723. mpvStreamTypeName = "audio";
  724. streamIdPropertyName = "aid";
  725. streamAddCommandName = "audio-add";
  726. break;
  727. }
  728. QString streamName;
  729. QString streamID;
  730. if (streamSelection.startsWith("#"))
  731. {
  732. int splitPos = streamSelection.indexOf(",");
  733. if (splitPos < 0)
  734. {
  735. // Stream from the main file
  736. streamID = streamSelection.mid(1);
  737. streamName = "";
  738. }
  739. else
  740. {
  741. // Stream from an external file
  742. streamID = streamSelection.mid(1, splitPos - 1);
  743. streamName = streamSelection.mid(splitPos + 1);
  744. }
  745. }
  746. else if (streamSelection.isEmpty())
  747. {
  748. mpv::qt::set_property(m_mpv, streamIdPropertyName, "no");
  749. return;
  750. }
  751. if (!streamName.isEmpty())
  752. {
  753. auto streams = findStreamsForURL(streamName);
  754. if (streams.isEmpty())
  755. {
  756. QStringList args = (QStringList() << streamAddCommandName << streamName);
  757. mpv::qt::command(m_mpv, args);
  758. }
  759. }
  760. QString selection = "no";
  761. for (auto stream : findStreamsForURL(streamName))
  762. {
  763. auto map = stream.toMap();
  764. if (map["type"].toString() != mpvStreamTypeName)
  765. continue;
  766. if (!streamID.isEmpty() && map["ff-index"].toString() == streamID)
  767. {
  768. selection = map["id"].toString();
  769. break;
  770. } else if (streamID.isEmpty() && map["external-filename"].toString() == streamName) {
  771. selection = map["id"].toString();
  772. break;
  773. }
  774. }
  775. // Fallback to the first stream if none could be found.
  776. // Useful if web-client uses wrong stream IDs when e.g. transcoding.
  777. if ((target == MediaType::Audio || !streamID.isEmpty()) && selection == "no")
  778. selection = "1";
  779. mpv::qt::set_property(m_mpv, streamIdPropertyName, selection);
  780. }
  781. ///////////////////////////////////////////////////////////////////////////////////////////////////
  782. void PlayerComponent::setSubtitleStream(const QString &subtitleStream)
  783. {
  784. m_currentSubtitleStream = subtitleStream;
  785. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  786. }
  787. ///////////////////////////////////////////////////////////////////////////////////////////////////
  788. void PlayerComponent::setAudioStream(const QString &audioStream)
  789. {
  790. m_currentAudioStream = audioStream;
  791. reselectStream(m_currentAudioStream, MediaType::Audio);
  792. }
  793. /////////////////////////////////////////////////////////////////////////////////////////
  794. void PlayerComponent::setAudioDelay(qint64 milliseconds)
  795. {
  796. m_playbackAudioDelay = milliseconds;
  797. double displayFps = DisplayComponent::Get().currentRefreshRate();
  798. const char *audioDelaySetting = "audio_delay.normal";
  799. if (fabs(displayFps - 24) < 0.5) // cover 24Hz, 23.976Hz, and values very close
  800. audioDelaySetting = "audio_delay.24hz";
  801. else if (fabs(displayFps - 25) < 0.5)
  802. audioDelaySetting = "audio_delay.25hz";
  803. else if (fabs(displayFps - 50) < 0.5)
  804. audioDelaySetting = "audio_delay.50hz";
  805. double fixedDelay = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, audioDelaySetting).toFloat();
  806. mpv::qt::set_property(m_mpv, "audio-delay", (fixedDelay + m_playbackAudioDelay) / 1000.0);
  807. }
  808. /////////////////////////////////////////////////////////////////////////////////////////
  809. void PlayerComponent::setSubtitleDelay(qint64 milliseconds)
  810. {
  811. mpv::qt::set_property(m_mpv, "sub-delay", milliseconds / 1000.0);
  812. }
  813. /////////////////////////////////////////////////////////////////////////////////////////
  814. void PlayerComponent::setPlaybackRate(int rate)
  815. {
  816. mpv::qt::set_property(m_mpv, "speed", rate / 1000.0);
  817. }
  818. /////////////////////////////////////////////////////////////////////////////////////////
  819. qint64 PlayerComponent::getPosition()
  820. {
  821. QVariant time = mpv::qt::get_property(m_mpv, "playback-time");
  822. if (time.canConvert(QMetaType::Double))
  823. return time.toDouble();
  824. return 0;
  825. }
  826. /////////////////////////////////////////////////////////////////////////////////////////
  827. qint64 PlayerComponent::getDuration()
  828. {
  829. QVariant time = mpv::qt::get_property(m_mpv, "duration");
  830. if (time.canConvert(QMetaType::Double))
  831. return time.toDouble();
  832. return 0;
  833. }
  834. ///////////////////////////////////////////////////////////////////////////////////////////////////
  835. // This is called with the set of previous audio devices that were detected, and the set of current
  836. // audio devices. From this we guess whether we should reopen the audio device. If the user-selected
  837. // device went away previously, and now comes back, reinitializing the player's audio output will
  838. // force the player and/or the OS to move audio output back to the user-selected device.
  839. void PlayerComponent::checkCurrentAudioDevice(const QSet<QString>& old_devs, const QSet<QString>& new_devs)
  840. {
  841. QString userDevice = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "device").toString();
  842. QSet<QString> removed = old_devs - new_devs;
  843. QSet<QString> added = new_devs - old_devs;
  844. QLOG_DEBUG() << "Audio devices removed:" << removed;
  845. QLOG_DEBUG() << "Audio devices added:" << added;
  846. QLOG_DEBUG() << "Audio device selected:" << userDevice;
  847. if (userDevice.length())
  848. {
  849. if (added.contains(userDevice) || removed.contains(userDevice))
  850. {
  851. // The timer is for debouncing the reload. Several change notifications could
  852. // come in quick succession. Also, it's possible that trying to open the
  853. // reappeared audio device immediately can fail.
  854. m_reloadAudioTimer.start(500);
  855. }
  856. }
  857. }
  858. ///////////////////////////////////////////////////////////////////////////////////////////////////
  859. void PlayerComponent::updateAudioDeviceList()
  860. {
  861. QString userDevice = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "device").toString();
  862. bool userDeviceFound = false;
  863. QVariantList settingList;
  864. QVariant list = getAudioDeviceList();
  865. QSet<QString> devices;
  866. for(const QVariant& d : list.toList())
  867. {
  868. Q_ASSERT(d.type() == QVariant::Map);
  869. QVariantMap dmap = d.toMap();
  870. QString device = dmap["name"].toString();
  871. QString description = dmap["description"].toString();
  872. devices.insert(device);
  873. if (userDevice == device)
  874. userDeviceFound = true;
  875. QVariantMap entry;
  876. entry["value"] = device;
  877. entry["title"] = description;
  878. settingList << entry;
  879. }
  880. if (!userDeviceFound)
  881. {
  882. QVariantMap entry;
  883. entry["value"] = userDevice;
  884. entry["title"] = "[Disconnected device: " + userDevice + "]";
  885. settingList << entry;
  886. }
  887. SettingsComponent::Get().updatePossibleValues(SETTINGS_SECTION_AUDIO, "device", settingList);
  888. checkCurrentAudioDevice(m_audioDevices, devices);
  889. m_audioDevices = devices;
  890. }
  891. ///////////////////////////////////////////////////////////////////////////////////////////////////
  892. void PlayerComponent::updateAudioDevice()
  893. {
  894. QString device = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "device").toString();
  895. if (!m_audioDevices.contains(device))
  896. {
  897. QLOG_WARN() << "Not using audio device" << device << "because it's not present.";
  898. device = "auto";
  899. }
  900. mpv::qt::set_property(m_mpv, "audio-device", device);
  901. }
  902. ///////////////////////////////////////////////////////////////////////////////////////////////////
  903. void PlayerComponent::setAudioConfiguration()
  904. {
  905. QString deviceType = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "devicetype").toString();
  906. mpv::qt::set_property(m_mpv, "audio-exclusive", SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "exclusive").toBool());
  907. updateAudioDevice();
  908. QString resampleOpts = "";
  909. bool normalize = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "normalize").toBool();
  910. resampleOpts += QString(":normalize=") + (normalize ? "yes" : "no");
  911. // Make downmix more similar to PHT.
  912. resampleOpts += ":o=[surround_mix_level=1]";
  913. mpv::qt::set_property(m_mpv, "af-defaults", "lavrresample" + resampleOpts);
  914. m_passthroughCodecs.clear();
  915. // passthrough doesn't make sense with basic type
  916. if (deviceType != AUDIO_DEVICE_TYPE_BASIC)
  917. {
  918. SettingsSection* audioSection = SettingsComponent::Get().getSection(SETTINGS_SECTION_AUDIO);
  919. QStringList codecs;
  920. if (deviceType == AUDIO_DEVICE_TYPE_SPDIF)
  921. codecs = AudioCodecsSPDIF();
  922. else if (deviceType == AUDIO_DEVICE_TYPE_HDMI)
  923. codecs = AudioCodecsAll();
  924. for(const QString& key : codecs)
  925. {
  926. if (audioSection->value("passthrough." + key).toBool())
  927. m_passthroughCodecs << key;
  928. }
  929. // dts-hd includes dts, but listing dts before dts-hd may disable dts-hd.
  930. if (m_passthroughCodecs.indexOf("dts-hd") != -1)
  931. m_passthroughCodecs.removeAll("dts");
  932. }
  933. QString passthroughCodecs = m_passthroughCodecs.join(",");
  934. mpv::qt::set_property(m_mpv, "audio-spdif", passthroughCodecs);
  935. // set the channel layout
  936. QVariant layout = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "channels");
  937. // always force either stereo or transcoding
  938. if (deviceType == AUDIO_DEVICE_TYPE_SPDIF)
  939. layout = "2.0";
  940. mpv::qt::set_property(m_mpv, "audio-channels", layout);
  941. // if the user has indicated that PCM only works for stereo, and that
  942. // the receiver supports AC3, set this extra option that allows us to transcode
  943. // 5.1 audio into a usable format, note that we only support AC3
  944. // here for now. We might need to add support for DTS transcoding
  945. // if we see user requests for it.
  946. //
  947. m_doAc3Transcoding = false;
  948. if (deviceType == AUDIO_DEVICE_TYPE_SPDIF &&
  949. SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "passthrough.ac3").toBool())
  950. {
  951. QString filterArgs = "";
  952. mpv::qt::command(m_mpv, QStringList() << "af" << "add" << ("@ac3:lavcac3enc" + filterArgs));
  953. m_doAc3Transcoding = true;
  954. }
  955. else
  956. {
  957. mpv::qt::command(m_mpv, QStringList() << "af" << "del" << "@ac3");
  958. }
  959. QVariant device = SettingsComponent::Get().value(SETTINGS_SECTION_AUDIO, "device");
  960. // Make a informational log message.
  961. QString audioConfig = QString(QString("Audio Config - device: %1, ") +
  962. "channel layout: %2, " +
  963. "passthrough codecs: %3, " +
  964. "ac3 transcoding: %4").arg(device.toString(),
  965. layout.toString(),
  966. passthroughCodecs.isEmpty() ? "none" : passthroughCodecs,
  967. m_doAc3Transcoding ? "yes" : "no");
  968. QLOG_INFO() << qPrintable(audioConfig);
  969. }
  970. ///////////////////////////////////////////////////////////////////////////////////////////////////
  971. void PlayerComponent::updateSubtitleSettings()
  972. {
  973. QVariant size = SettingsComponent::Get().value(SETTINGS_SECTION_SUBTITLES, "size");
  974. mpv::qt::set_property(m_mpv, "sub-scale", size.toInt() / 32.0);
  975. QVariant colorsString = SettingsComponent::Get().value(SETTINGS_SECTION_SUBTITLES, "color");
  976. auto colors = colorsString.toString().split(",");
  977. if (colors.length() == 2)
  978. {
  979. mpv::qt::set_property(m_mpv, "sub-color", colors[0]);
  980. mpv::qt::set_property(m_mpv, "sub-border-color", colors[1]);
  981. }
  982. QVariant subposString = SettingsComponent::Get().value(SETTINGS_SECTION_SUBTITLES, "placement");
  983. auto subpos = subposString.toString().split(",");
  984. if (subpos.length() == 2)
  985. {
  986. mpv::qt::set_property(m_mpv, "sub-align-x", subpos[0]);
  987. mpv::qt::set_property(m_mpv, "sub-pos", subpos[1] == "bottom" ? 100 : 10);
  988. }
  989. }
  990. ///////////////////////////////////////////////////////////////////////////////////////////////////
  991. void PlayerComponent::updateVideoAspectSettings()
  992. {
  993. QVariant mode = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "aspect").toString();
  994. bool disableScaling = false;
  995. bool keepAspect = true;
  996. QString forceAspect = "-1";
  997. double panScan = 0.0;
  998. if (mode == "custom")
  999. {
  1000. // in particular, do not restore anything - the intention is not to touch the user's mpv.conf settings, or whatever
  1001. return;
  1002. }
  1003. else if (mode == "zoom")
  1004. {
  1005. panScan = 1.0;
  1006. }
  1007. else if (mode == "force_4_3")
  1008. {
  1009. forceAspect = "4:3";
  1010. }
  1011. else if (mode == "force_16_9")
  1012. {
  1013. forceAspect = "16:9";
  1014. }
  1015. else if (mode == "force_16_9_if_4_3")
  1016. {
  1017. auto params = mpv::qt::get_property(m_mpv, "video-dec-params").toMap();
  1018. auto aspect = params["aspect"].toFloat();
  1019. if (fabs(aspect - 4.0/3.0) < 0.1)
  1020. forceAspect = "16:9";
  1021. }
  1022. else if (mode == "stretch")
  1023. {
  1024. keepAspect = false;
  1025. }
  1026. else if (mode == "noscaling")
  1027. {
  1028. disableScaling = true;
  1029. }
  1030. mpv::qt::set_property(m_mpv, "video-unscaled", disableScaling);
  1031. mpv::qt::set_property(m_mpv, "video-aspect", forceAspect);
  1032. mpv::qt::set_property(m_mpv, "keepaspect", keepAspect);
  1033. mpv::qt::set_property(m_mpv, "panscan", panScan);
  1034. }
  1035. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1036. void PlayerComponent::updateVideoSettings()
  1037. {
  1038. if (!m_mpv)
  1039. return;
  1040. QVariant syncMode = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "sync_mode");
  1041. mpv::qt::set_property(m_mpv, "video-sync", syncMode);
  1042. QString hardwareDecodingMode = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "hardwareDecoding").toString();
  1043. QString hwdecMode = "no";
  1044. QString hwdecVTFormat = "nv12";
  1045. if (hardwareDecodingMode == "enabled")
  1046. hwdecMode = "auto";
  1047. else if (hardwareDecodingMode == "osx_compat")
  1048. {
  1049. hwdecMode = "auto";
  1050. hwdecVTFormat = "uyvy422";
  1051. }
  1052. else if (hardwareDecodingMode == "copy")
  1053. {
  1054. hwdecMode = "auto-copy";
  1055. }
  1056. mpv::qt::set_property(m_mpv, "hwdec", hwdecMode);
  1057. mpv::qt::set_property(m_mpv, "videotoolbox-format", hwdecVTFormat);
  1058. QVariant deinterlace = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "deinterlace");
  1059. mpv::qt::set_property(m_mpv, "deinterlace", deinterlace.toBool() ? "yes" : "no");
  1060. #ifndef TARGET_RPI
  1061. double displayFps = DisplayComponent::Get().currentRefreshRate();
  1062. mpv::qt::set_property(m_mpv, "display-fps", displayFps);
  1063. #endif
  1064. setAudioDelay(m_playbackAudioDelay);
  1065. QVariant cache = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "cache");
  1066. mpv::qt::set_property(m_mpv, "cache", cache.toInt() * 1024);
  1067. updateVideoAspectSettings();
  1068. }
  1069. /////////////////////////////////////////////////////////////////////////////////////////
  1070. void PlayerComponent::userCommand(QString command)
  1071. {
  1072. QByteArray cmdUtf8 = command.toUtf8();
  1073. mpv_command_string(m_mpv, cmdUtf8.data());
  1074. }
  1075. /////////////////////////////////////////////////////////////////////////////////////////
  1076. void PlayerComponent::initializeCodecSupport()
  1077. {
  1078. QMap<QString, QString> all = { {"vc1", "WVC1"}, {"mpeg2video", "MPG2"} };
  1079. for (auto name : all.keys())
  1080. {
  1081. bool ok = true;
  1082. #ifdef TARGET_RPI
  1083. char res[100] = "";
  1084. bcm_host_init();
  1085. if (vc_gencmd(res, sizeof(res), "codec_enabled %s", all[name].toUtf8().data()))
  1086. res[0] = '\0'; // error
  1087. ok = !!strstr(res, "=enabled");
  1088. #endif
  1089. m_codecSupport[name] = ok;
  1090. QLOG_INFO() << "Codec" << name << (ok ? "present" : "disabled");
  1091. }
  1092. }
  1093. /////////////////////////////////////////////////////////////////////////////////////////
  1094. bool PlayerComponent::checkCodecSupport(const QString& codec)
  1095. {
  1096. if (m_codecSupport.contains(codec))
  1097. return m_codecSupport[codec];
  1098. return true; // doesn't matter if unknown codecs are reported as "ok"
  1099. }
  1100. /////////////////////////////////////////////////////////////////////////////////////////
  1101. QList<CodecDriver> convertCodecList(QVariant list, CodecType type)
  1102. {
  1103. QList<CodecDriver> codecs;
  1104. foreach (const QVariant& e, list.toList())
  1105. {
  1106. QVariantMap map = e.toMap();
  1107. QString family = map["family"].toString();
  1108. QString codec = map["codec"].toString();
  1109. QString driver = map["driver"].toString();
  1110. // Only include FFmpeg codecs; exclude pseudo-codecs like spdif (on mpv versions where those were exposed).
  1111. if (family != "" && family != "lavc")
  1112. continue;
  1113. CodecDriver ncodec = {};
  1114. ncodec.type = type;
  1115. ncodec.format = codec;
  1116. ncodec.driver = driver;
  1117. ncodec.present = true;
  1118. codecs.append(ncodec);
  1119. }
  1120. return codecs;
  1121. }
  1122. /////////////////////////////////////////////////////////////////////////////////////////
  1123. QList<CodecDriver> PlayerComponent::installedCodecDrivers()
  1124. {
  1125. QList<CodecDriver> codecs;
  1126. codecs.append(convertCodecList(mpv::qt::get_property(m_mpv, "decoder-list"), CodecType::Decoder));
  1127. codecs.append(convertCodecList(mpv::qt::get_property(m_mpv, "encoder-list"), CodecType::Encoder));
  1128. return codecs;
  1129. }
  1130. /////////////////////////////////////////////////////////////////////////////////////////
  1131. QStringList PlayerComponent::installedDecoderCodecs()
  1132. {
  1133. QStringList formats;
  1134. bool hasPcm = false;
  1135. for (auto driver : installedCodecDrivers())
  1136. {
  1137. if (driver.type == CodecType::Decoder && checkCodecSupport(driver.format))
  1138. {
  1139. QString name = Codecs::plexNameFromFF(driver.format);
  1140. if (name.startsWith("pcm_") && name != "pcm_bluray" && name != "pcm_dvd")
  1141. {
  1142. if (hasPcm)
  1143. continue;
  1144. hasPcm = true;
  1145. name = "pcm";
  1146. }
  1147. formats.append(name);
  1148. }
  1149. }
  1150. return formats;
  1151. }
  1152. /////////////////////////////////////////////////////////////////////////////////////////
  1153. PlaybackInfo PlayerComponent::getPlaybackInfo()
  1154. {
  1155. PlaybackInfo info = {};
  1156. for (auto codec : m_passthroughCodecs)
  1157. {
  1158. // Normalize back to canonical codec names.
  1159. if (codec == "dts-hd")
  1160. codec = "dts";
  1161. info.audioPassthroughCodecs.insert(codec);
  1162. }
  1163. info.enableAC3Transcoding = m_doAc3Transcoding;
  1164. auto tracks = mpv::qt::get_property(m_mpv, "track-list");
  1165. for (auto track : tracks.toList())
  1166. {
  1167. QVariantMap map = track.toMap();
  1168. QString type = map["type"].toString();
  1169. StreamInfo stream = {};
  1170. stream.isVideo = type == "video";
  1171. stream.isAudio = type == "audio";
  1172. stream.codec = map["codec"].toString();
  1173. stream.audioChannels = map["demux-channel-count"].toInt();
  1174. stream.audioSampleRate = map["demux-samplerate"].toInt();
  1175. stream.videoResolution = QSize(map["demux-w"].toInt(), map["demux-h"].toInt());
  1176. // Get the profile from the server, because mpv can't determine it yet.
  1177. if (stream.isVideo)
  1178. {
  1179. int index = map["ff-index"].toInt();
  1180. for (auto partInfo : m_serverMediaInfo["Part"].toList())
  1181. {
  1182. for (auto streamInfo : partInfo.toMap()["Stream"].toList())
  1183. {
  1184. auto streamInfoMap = streamInfo.toMap();
  1185. bool ok = false;
  1186. if (streamInfoMap["index"].toInt(&ok) == index && ok)
  1187. {
  1188. stream.profile = streamInfoMap["profile"].toString();
  1189. QLOG_DEBUG() << "h264profile:" << stream.profile;
  1190. }
  1191. }
  1192. }
  1193. }
  1194. info.streams.append(stream);
  1195. }
  1196. // If we're in an early stage where we don't have streams yet, try to get the
  1197. // info from the PMS metadata.
  1198. if (!info.streams.size())
  1199. {
  1200. for (auto partInfo : m_serverMediaInfo["Part"].toList())
  1201. {
  1202. for (auto streamInfo : partInfo.toMap()["Stream"].toList())
  1203. {
  1204. auto streamInfoMap = streamInfo.toMap();
  1205. StreamInfo stream = {};
  1206. stream.isVideo = streamInfoMap["width"].isValid();
  1207. stream.isAudio = streamInfoMap["channels"].isValid();
  1208. stream.codec = Codecs::plexNameToFF(streamInfoMap["codec"].toString());
  1209. stream.audioChannels = streamInfoMap["channels"].toInt();
  1210. stream.videoResolution = QSize(streamInfoMap["width"].toInt(), streamInfoMap["height"].toInt());
  1211. stream.profile = streamInfoMap["profile"].toString();
  1212. info.streams.append(stream);
  1213. }
  1214. }
  1215. }
  1216. return info;
  1217. }
  1218. /////////////////////////////////////////////////////////////////////////////////////////
  1219. void PlayerComponent::setPreferredCodecs(const QList<CodecDriver>& codecs)
  1220. {
  1221. QStringList items;
  1222. for (auto codec : codecs)
  1223. {
  1224. if (codec.type == CodecType::Decoder)
  1225. {
  1226. items << codec.driver;
  1227. }
  1228. }
  1229. QString opt = items.join(",");
  1230. // For simplicity, we don't distinguish between audio and video. The player
  1231. // will ignore entries with mismatching media type.
  1232. mpv::qt::set_property(m_mpv, "ad", opt);
  1233. mpv::qt::set_property(m_mpv, "vd", opt);
  1234. }
  1235. // For QVariant.
  1236. Q_DECLARE_METATYPE(std::function<void()>);
  1237. /////////////////////////////////////////////////////////////////////////////////////////
  1238. void PlayerComponent::startCodecsLoading(std::function<void()> resume)
  1239. {
  1240. auto fetcher = new CodecsFetcher();
  1241. fetcher->userData = QVariant::fromValue(resume);
  1242. connect(fetcher, &CodecsFetcher::done, this, &PlayerComponent::onCodecsLoadingDone);
  1243. Codecs::updateCachedCodecList();
  1244. QList<CodecDriver> codecs = Codecs::determineRequiredCodecs(getPlaybackInfo());
  1245. setPreferredCodecs(codecs);
  1246. fetcher->installCodecs(codecs);
  1247. }
  1248. /////////////////////////////////////////////////////////////////////////////////////////
  1249. void PlayerComponent::onCodecsLoadingDone(CodecsFetcher* sender)
  1250. {
  1251. sender->deleteLater();
  1252. sender->userData.value<std::function<void()>>()();
  1253. }
  1254. /////////////////////////////////////////////////////////////////////////////////////////
  1255. static QString get_mpv_osd(mpv_handle *ctx, const QString& property)
  1256. {
  1257. char *s = mpv_get_property_osd_string(ctx, property.toUtf8().data());
  1258. if (!s)
  1259. return "-";
  1260. QString r = QString::fromUtf8(s);
  1261. mpv_free(s);
  1262. if (r.size() > 400)
  1263. r = r.mid(0, 400) + "...";
  1264. Log::CensorAuthTokens(r);
  1265. return r;
  1266. }
  1267. #define MPV_PROPERTY(p) get_mpv_osd(m_mpv, p)
  1268. #define MPV_PROPERTY_BOOL(p) (mpv::qt::get_property(m_mpv, p).toBool())
  1269. /////////////////////////////////////////////////////////////////////////////////////////
  1270. void PlayerComponent::appendAudioFormat(QTextStream& info, const QString& property) const
  1271. {
  1272. // Guess if it's a passthrough format. Don't show the channel layout in this
  1273. // case, because it's confusing.
  1274. QString audioFormat = MPV_PROPERTY(property + "/format");
  1275. if (audioFormat.startsWith("spdif-"))
  1276. {
  1277. info << "passthrough (" << audioFormat.mid(6) << ")";
  1278. }
  1279. else
  1280. {
  1281. QString hr = MPV_PROPERTY(property + "/hr-channels");
  1282. QString full = MPV_PROPERTY(property + "/channels");
  1283. info << hr;
  1284. if (hr != full)
  1285. info << " (" << full << ")";
  1286. }
  1287. }
  1288. /////////////////////////////////////////////////////////////////////////////////////////
  1289. QString PlayerComponent::videoInformation() const
  1290. {
  1291. QString infoStr;
  1292. QTextStream info(&infoStr);
  1293. // check if video is playing
  1294. if (mpv::qt::get_property(m_mpv, "idle-active").toBool())
  1295. return "";
  1296. info << "File:\n";
  1297. info << "URL: " << MPV_PROPERTY("path") << "\n";
  1298. info << "Container: " << MPV_PROPERTY("file-format") << "\n";
  1299. info << "Native seeking: " << ((MPV_PROPERTY_BOOL("seekable") &&
  1300. !MPV_PROPERTY_BOOL("partially-seekable"))
  1301. ? "yes" : "no") << "\n";
  1302. info << "\n";
  1303. info << "Video:\n";
  1304. info << "Codec: " << MPV_PROPERTY("video-codec") << "\n";
  1305. info << "Size: " << MPV_PROPERTY("video-params/dw") << "x"
  1306. << MPV_PROPERTY("video-params/dh") << "\n";
  1307. info << "FPS (container): " << MPV_PROPERTY("container-fps") << "\n";
  1308. info << "FPS (filters): " << MPV_PROPERTY("estimated-vf-fps") << "\n";
  1309. info << "Aspect: " << MPV_PROPERTY("video-aspect") << "\n";
  1310. info << "Bitrate: " << MPV_PROPERTY("video-bitrate") << "\n";
  1311. double displayFps = DisplayComponent::Get().currentRefreshRate();
  1312. info << "Display FPS: " << MPV_PROPERTY("display-fps")
  1313. << " (" << displayFps << ")" << "\n";
  1314. info << "Hardware Decoding: " << MPV_PROPERTY("hwdec-current")
  1315. << " (" << MPV_PROPERTY("hwdec-interop") << ")\n";
  1316. info << "\n";
  1317. info << "Audio:\n";
  1318. info << "Codec: " << MPV_PROPERTY("audio-codec") << "\n";
  1319. info << "Bitrate: " << MPV_PROPERTY("audio-bitrate") << "\n";
  1320. info << "Channels: ";
  1321. appendAudioFormat(info, "audio-params");
  1322. info << " -> ";
  1323. appendAudioFormat(info, "audio-out-params");
  1324. info << "\n";
  1325. info << "Output driver: " << MPV_PROPERTY("current-ao") << "\n";
  1326. info << "\n";
  1327. info << "Performance:\n";
  1328. info << "A/V: " << MPV_PROPERTY("avsync") << "\n";
  1329. info << "Dropped frames: " << MPV_PROPERTY("vo-drop-frame-count") << "\n";
  1330. bool dispSync = MPV_PROPERTY_BOOL("display-sync-active");
  1331. info << "Display Sync: ";
  1332. if (!dispSync)
  1333. {
  1334. info << "no\n";
  1335. }
  1336. else
  1337. {
  1338. info << "yes (ratio " << MPV_PROPERTY("vsync-ratio") << ")\n";
  1339. info << "Mistimed frames: " << MPV_PROPERTY("mistimed-frame-count")
  1340. << "/" << MPV_PROPERTY("vo-delayed-frame-count") << "\n";
  1341. info << "Measured FPS: " << MPV_PROPERTY("estimated-display-fps")
  1342. << " (" << MPV_PROPERTY("vsync-jitter") << ")\n";
  1343. info << "V. speed corr.: " << MPV_PROPERTY("video-speed-correction") << "\n";
  1344. info << "A. speed corr.: " << MPV_PROPERTY("audio-speed-correction") << "\n";
  1345. }
  1346. info << "\n";
  1347. info << "Cache:\n";
  1348. info << "Seconds: " << MPV_PROPERTY("demuxer-cache-duration") << "\n";
  1349. info << "Extra readahead: " << MPV_PROPERTY("cache-used") << "\n";
  1350. info << "Buffering: " << MPV_PROPERTY("cache-buffering-state") << "\n";
  1351. info << "Speed: " << MPV_PROPERTY("cache-speed") << "\n";
  1352. info << "\n";
  1353. info << "Misc:\n";
  1354. info << "Time: " << MPV_PROPERTY("playback-time") << " / "
  1355. << MPV_PROPERTY("duration")
  1356. << " (" << MPV_PROPERTY("percent-pos") << "%)\n";
  1357. info << "State: " << (MPV_PROPERTY_BOOL("pause") ? "paused " : "")
  1358. << (MPV_PROPERTY_BOOL("paused-for-cache") ? "buffering " : "")
  1359. << (MPV_PROPERTY_BOOL("core-idle") ? "waiting " : "playing ")
  1360. << (MPV_PROPERTY_BOOL("seeking") ? "seeking " : "")
  1361. << "\n";
  1362. info.flush();
  1363. return infoStr;
  1364. }