PlayerComponent.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. mpv::qt::set_property(m_mpv, "tls-verify", "yes");
  104. #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
  105. QList<QByteArray> list;
  106. list << "/etc/ssl/certs/ca-certificates.crt"
  107. << "/etc/pki/tls/certs/ca-bundle.crt"
  108. << "/usr/share/ssl/certs/ca-bundle.crt"
  109. << "/usr/local/share/certs/ca-root-nss.crt"
  110. << "/etc/ssl/cert.pem"
  111. << "/usr/share/curl/curl-ca-bundle.crt"
  112. << "/usr/local/share/curl/curl-ca-bundle.crt"
  113. << "/var/lib/ca-certificates/ca-bundle.pem";
  114. bool success = false;
  115. for (auto path : list)
  116. {
  117. if (access(path.data(), R_OK) == 0) {
  118. mpv::qt::set_property(m_mpv, "tls-ca-file", path.data());
  119. success = true;
  120. break;
  121. }
  122. }
  123. if (!success)
  124. throw FatalException(tr("Failed to locate CA bundle."));
  125. #endif
  126. // Apply some low-memory settings on RPI, which is relatively memory-constrained.
  127. #ifdef TARGET_RPI
  128. // The backbuffer makes seeking back faster (without having to do a HTTP-level seek)
  129. mpv::qt::set_property(m_mpv, "cache-backbuffer", 10 * 1024); // KB
  130. // The demuxer queue is used for the readahead, and also for dealing with badly
  131. // interlaved audio/video. Setting it too low increases sensitivity to network
  132. // issues, and could cause playback failure with "bad" files.
  133. mpv::qt::set_property(m_mpv, "demuxer-max-bytes", 50 * 1024 * 1024); // bytes
  134. // Specifically for enabling mpeg4.
  135. mpv::qt::set_property(m_mpv, "hwdec-codecs", "all");
  136. // Do not use exact seeks by default. (This affects the start position in the "loadfile"
  137. // command in particular. We override the seek mode for normal "seek" commands.)
  138. mpv::qt::set_property(m_mpv, "hr-seek", "no");
  139. // Force vo_rpi to fullscreen.
  140. mpv::qt::set_property(m_mpv, "fullscreen", true);
  141. #endif
  142. if (mpv_initialize(m_mpv) < 0)
  143. throw FatalException(tr("Failed to initialize mpv."));
  144. mpv_observe_property(m_mpv, 0, "pause", MPV_FORMAT_FLAG);
  145. mpv_observe_property(m_mpv, 0, "core-idle", MPV_FORMAT_FLAG);
  146. mpv_observe_property(m_mpv, 0, "cache-buffering-state", MPV_FORMAT_INT64);
  147. mpv_observe_property(m_mpv, 0, "playback-time", MPV_FORMAT_DOUBLE);
  148. mpv_observe_property(m_mpv, 0, "vo-configured", MPV_FORMAT_FLAG);
  149. mpv_observe_property(m_mpv, 0, "duration", MPV_FORMAT_DOUBLE);
  150. mpv_observe_property(m_mpv, 0, "audio-device-list", MPV_FORMAT_NODE);
  151. mpv_observe_property(m_mpv, 0, "video-dec-params", MPV_FORMAT_NODE);
  152. // Setup a hook with the ID 1, which is run during the file is loaded.
  153. // Used to delay playback start for display framerate switching.
  154. // (See handler in handleMpvEvent() for details.)
  155. // Setup a hook with the ID 2, which is run at a certain stage during loading.
  156. // We use it to initialize stream selections and to probe the codecs.
  157. #if MPV_CLIENT_API_VERSION < MPV_MAKE_VERSION(1, 100)
  158. mpv::qt::command(m_mpv, QStringList() << "hook-add" << "on_load" << "1" << "0");
  159. mpv::qt::command(m_mpv, QStringList() << "hook-add" << "on_preloaded" << "2" << "0");
  160. #else
  161. mpv_hook_add(m_mpv, 1, "on_load", 0);
  162. mpv_hook_add(m_mpv, 2, "on_preloaded", 0);
  163. #endif
  164. updateAudioDeviceList();
  165. setAudioConfiguration();
  166. updateSubtitleSettings();
  167. updateVideoSettings();
  168. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_VIDEO), &SettingsSection::valuesUpdated,
  169. this, &PlayerComponent::updateVideoSettings);
  170. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_SUBTITLES), &SettingsSection::valuesUpdated,
  171. this, &PlayerComponent::updateSubtitleSettings);
  172. connect(SettingsComponent::Get().getSection(SETTINGS_SECTION_AUDIO), &SettingsSection::valuesUpdated,
  173. this, &PlayerComponent::setAudioConfiguration);
  174. initializeCodecSupport();
  175. Codecs::initCodecs();
  176. QString codecInfo;
  177. for (auto codec : Codecs::getCachedCodecList())
  178. {
  179. if (codec.present)
  180. {
  181. if (codecInfo.size())
  182. codecInfo += " ";
  183. codecInfo += codec.driver;
  184. if (codec.type == CodecType::Encoder)
  185. codecInfo += "(enc)";
  186. }
  187. }
  188. QLOG_INFO() << "Present codecs:" << qPrintable(codecInfo);
  189. connect(this, &PlayerComponent::onMpvEvents, this, &PlayerComponent::handleMpvEvents, Qt::QueuedConnection);
  190. emit onMpvEvents();
  191. return true;
  192. }
  193. ///////////////////////////////////////////////////////////////////////////////////////////////////
  194. void PlayerComponent::setVideoRectangle(int x, int y, int w, int h)
  195. {
  196. QRect rc(x, y, w, h);
  197. if (rc != m_videoRectangle)
  198. {
  199. m_videoRectangle = rc;
  200. emit onVideoRecangleChanged();
  201. }
  202. }
  203. ///////////////////////////////////////////////////////////////////////////////////////////////////
  204. void PlayerComponent::setQtQuickWindow(QQuickWindow* window)
  205. {
  206. PlayerQuickItem* video = window->findChild<PlayerQuickItem*>("video");
  207. if (!video)
  208. throw FatalException(tr("Failed to load video element."));
  209. video->initMpv(this);
  210. }
  211. ///////////////////////////////////////////////////////////////////////////////////////////////////
  212. void PlayerComponent::setWindow(QQuickWindow* window)
  213. {
  214. QString vo = "libmpv";
  215. #ifdef TARGET_RPI
  216. window->setFlags(Qt::FramelessWindowHint);
  217. vo = "rpi";
  218. #endif
  219. m_window = window;
  220. if (!window)
  221. return;
  222. QString forceVo = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "debug.force_vo").toString();
  223. if (forceVo.size())
  224. vo = forceVo;
  225. mpv::qt::set_property(m_mpv, "vo", vo);
  226. if (vo == "libmpv")
  227. setQtQuickWindow(window);
  228. }
  229. ///////////////////////////////////////////////////////////////////////////////////////////////////
  230. bool PlayerComponent::load(const QString& url, const QVariantMap& options, const QVariantMap &metadata, const QString& audioStream , const QString& subtitleStream)
  231. {
  232. stop();
  233. queueMedia(url, options, metadata, audioStream, subtitleStream);
  234. return true;
  235. }
  236. ///////////////////////////////////////////////////////////////////////////////////////////////////
  237. static bool IsPlexDirectURL(const QString& host)
  238. {
  239. return host.endsWith(".plex.direct");
  240. }
  241. ///////////////////////////////////////////////////////////////////////////////////////////////////
  242. static QString ConvertPlexDirectURL(const QString& host)
  243. {
  244. if (!IsPlexDirectURL(host))
  245. return host;
  246. QString substr = host.left(host.indexOf('.'));
  247. substr.replace('-', '.');
  248. return substr;
  249. }
  250. ///////////////////////////////////////////////////////////////////////////////////////////////////
  251. void PlayerComponent::queueMedia(const QString& url, const QVariantMap& options, const QVariantMap &metadata, const QString& audioStream, const QString& subtitleStream)
  252. {
  253. InputComponent::Get().cancelAutoRepeat();
  254. m_mediaFrameRate = metadata["frameRate"].toFloat(); // returns 0 on failure
  255. m_serverMediaInfo = metadata["media"].toMap();
  256. updateVideoSettings();
  257. QUrl qurl = url;
  258. QString host = qurl.host();
  259. if (IsPlexDirectURL(host))
  260. qurl.setHost(ConvertPlexDirectURL(host));
  261. QVariantList command;
  262. command << "loadfile" << qurl.toString(QUrl::FullyEncoded);
  263. command << "append-play"; // if nothing is playing, play it now, otherwise just enqueue it
  264. QVariantMap extraArgs;
  265. quint64 startMilliseconds = options["startMilliseconds"].toLongLong();
  266. if (startMilliseconds != 0)
  267. extraArgs.insert("start", "+" + QString::number(startMilliseconds / 1000.0));
  268. // we're going to select these streams later, in the preloaded hook
  269. extraArgs.insert("aid", "no");
  270. extraArgs.insert("sid", "no");
  271. m_currentSubtitleStream = subtitleStream;
  272. m_currentAudioStream = audioStream;
  273. if (metadata["type"] == "music")
  274. extraArgs.insert("vid", "no");
  275. extraArgs.insert("pause", options["autoplay"].toBool() ? "no" : "yes");
  276. QString userAgent = metadata["headers"].toMap()["User-Agent"].toString();
  277. if (userAgent.size())
  278. extraArgs.insert("user-agent", userAgent);
  279. // Make sure the list of requested codecs is reset.
  280. extraArgs.insert("ad", "");
  281. extraArgs.insert("vd", "");
  282. if (IsPlexDirectURL(host))
  283. extraArgs.insert("stream-lavf-o", "verifyhost=" + host);
  284. command << extraArgs;
  285. mpv::qt::command(m_mpv, command);
  286. }
  287. /////////////////////////////////////////////////////////////////////////////////////////
  288. void PlayerComponent::streamSwitch()
  289. {
  290. m_streamSwitchImminent = true;
  291. }
  292. ///////////////////////////////////////////////////////////////////////////////////////////////////
  293. bool PlayerComponent::switchDisplayFrameRate()
  294. {
  295. QLOG_DEBUG() << "Video framerate:" << m_mediaFrameRate << "fps";
  296. if (!SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.auto_switch").toBool())
  297. {
  298. QLOG_DEBUG() << "Not switching refresh-rate (disabled by settings).";
  299. return false;
  300. }
  301. bool fs = SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "fullscreen").toBool();
  302. #if KONVERGO_OPENELEC
  303. fs = true;
  304. #endif
  305. if (!fs)
  306. {
  307. QLOG_DEBUG() << "Not switching refresh-rate (not in fullscreen mode).";
  308. return false;
  309. }
  310. if (m_mediaFrameRate < 1)
  311. {
  312. QLOG_DEBUG() << "Not switching refresh-rate (no known video framerate).";
  313. return false;
  314. }
  315. // Make sure a timer started by the previous file ending isn't accidentally
  316. // still in-flight. It could switch the display back after we've switched.
  317. m_restoreDisplayTimer.stop();
  318. DisplayComponent* display = &DisplayComponent::Get();
  319. if (!display->switchToBestVideoMode(m_mediaFrameRate))
  320. {
  321. QLOG_DEBUG() << "Switching refresh-rate failed or unnecessary.";
  322. return false;
  323. }
  324. // Make sure settings dependent on the display refresh rate are updated properly.
  325. updateVideoSettings();
  326. return true;
  327. }
  328. ///////////////////////////////////////////////////////////////////////////////////////////////////
  329. void PlayerComponent::onRestoreDisplay()
  330. {
  331. // If the player will in fact start another file (or is playing one), don't restore.
  332. if (mpv::qt::get_property(m_mpv, "idle-active").toBool())
  333. DisplayComponent::Get().restorePreviousVideoMode();
  334. }
  335. ///////////////////////////////////////////////////////////////////////////////////////////////////
  336. void PlayerComponent::onRefreshRateChange()
  337. {
  338. // Make sure settings dependent on the display refresh rate are updated properly.
  339. updateVideoSettings();
  340. }
  341. ///////////////////////////////////////////////////////////////////////////////////////////////////
  342. void PlayerComponent::updatePlaybackState()
  343. {
  344. State newState = m_state;
  345. if (m_inPlayback) {
  346. if (m_paused)
  347. {
  348. newState = State::paused;
  349. }
  350. else if (m_playbackActive)
  351. {
  352. newState = State::playing;
  353. }
  354. else
  355. {
  356. // Playback not active, but also not buffering means we're in some "other"
  357. // waiting state. Pretend to web-client that we're buffering.
  358. if (m_bufferingPercentage == 100)
  359. m_bufferingPercentage = 0;
  360. newState = State::buffering;
  361. }
  362. }
  363. else
  364. {
  365. if (!m_playbackError.isEmpty())
  366. newState = State::error;
  367. else if (m_playbackCanceled)
  368. newState = State::canceled;
  369. else
  370. newState = State::finished;
  371. }
  372. if (newState != m_state)
  373. {
  374. switch (newState) {
  375. case State::paused:
  376. QLOG_INFO() << "Entering state: paused";
  377. emit paused();
  378. break;
  379. case State::playing:
  380. QLOG_INFO() << "Entering state: playing";
  381. emit playing();
  382. break;
  383. case State::buffering:
  384. QLOG_INFO() << "Entering state: buffering";
  385. m_lastBufferingPercentage = -1; /* force update below */
  386. break;
  387. case State::finished:
  388. QLOG_INFO() << "Entering state: finished";
  389. emit finished();
  390. emit stopped();
  391. break;
  392. case State::canceled:
  393. QLOG_INFO() << "Entering state: canceled";
  394. emit canceled();
  395. emit stopped();
  396. break;
  397. case State::error:
  398. QLOG_INFO() << ("Entering state: error (" + m_playbackError + ")");
  399. emit error(m_playbackError);
  400. break;
  401. }
  402. emit stateChanged(newState, m_state);
  403. m_state = newState;
  404. }
  405. if (m_state == State::buffering && m_lastBufferingPercentage != m_bufferingPercentage)
  406. emit buffering(m_bufferingPercentage);
  407. m_lastBufferingPercentage = m_bufferingPercentage;
  408. bool is_videoPlaybackActive = m_state == State::playing && m_windowVisible;
  409. if (m_videoPlaybackActive != is_videoPlaybackActive)
  410. {
  411. m_videoPlaybackActive = is_videoPlaybackActive;
  412. emit videoPlaybackActive(m_videoPlaybackActive);
  413. }
  414. }
  415. ///////////////////////////////////////////////////////////////////////////////////////////////////
  416. void PlayerComponent::handleMpvEvent(mpv_event *event)
  417. {
  418. switch (event->event_id)
  419. {
  420. case MPV_EVENT_START_FILE:
  421. {
  422. m_inPlayback = true;
  423. break;
  424. }
  425. case MPV_EVENT_END_FILE:
  426. {
  427. mpv_event_end_file *endFile = (mpv_event_end_file *)event->data;
  428. m_inPlayback = false;
  429. m_playbackCanceled = false;
  430. m_playbackError = "";
  431. switch (endFile->reason)
  432. {
  433. case MPV_END_FILE_REASON_ERROR:
  434. {
  435. m_playbackError = mpv_error_string(endFile->error);
  436. break;
  437. }
  438. case MPV_END_FILE_REASON_STOP:
  439. {
  440. m_playbackCanceled = true;
  441. break;
  442. }
  443. }
  444. if (!m_streamSwitchImminent)
  445. m_restoreDisplayTimer.start(0);
  446. m_streamSwitchImminent = false;
  447. break;
  448. }
  449. case MPV_EVENT_PROPERTY_CHANGE:
  450. {
  451. mpv_event_property *prop = (mpv_event_property *)event->data;
  452. if (strcmp(prop->name, "pause") == 0 && prop->format == MPV_FORMAT_FLAG)
  453. {
  454. m_paused = !!*(int *)prop->data;
  455. }
  456. else if (strcmp(prop->name, "core-idle") == 0 && prop->format == MPV_FORMAT_FLAG)
  457. {
  458. m_playbackActive = !*(int *)prop->data;
  459. }
  460. else if (strcmp(prop->name, "cache-buffering-state") == 0)
  461. {
  462. m_bufferingPercentage = prop->format == MPV_FORMAT_INT64 ? (int)*(int64_t *)prop->data : 100;
  463. }
  464. else if (strcmp(prop->name, "playback-time") == 0 && prop->format == MPV_FORMAT_DOUBLE)
  465. {
  466. double pos = *(double*)prop->data;
  467. if (fabs(pos - m_lastPositionUpdate) > 0.015)
  468. {
  469. quint64 ms = (quint64)(qMax(pos * 1000.0, 0.0));
  470. emit positionUpdate(ms);
  471. m_lastPositionUpdate = pos;
  472. }
  473. }
  474. else if (strcmp(prop->name, "vo-configured") == 0)
  475. {
  476. int state = prop->format == MPV_FORMAT_FLAG ? *(int *)prop->data : 0;
  477. m_windowVisible = state;
  478. emit windowVisible(m_windowVisible);
  479. }
  480. else if (strcmp(prop->name, "duration") == 0)
  481. {
  482. if (prop->format == MPV_FORMAT_DOUBLE)
  483. emit updateDuration(*(double *)prop->data * 1000.0);
  484. }
  485. else if (strcmp(prop->name, "audio-device-list") == 0)
  486. {
  487. updateAudioDeviceList();
  488. }
  489. else if (strcmp(prop->name, "video-dec-params") == 0)
  490. {
  491. // Aspect might be known now (or it changed during playback), so update settings
  492. // dependent on the aspect ratio.
  493. updateVideoAspectSettings();
  494. }
  495. break;
  496. }
  497. case MPV_EVENT_LOG_MESSAGE:
  498. {
  499. mpv_event_log_message *msg = (mpv_event_log_message *)event->data;
  500. // Strip the trailing '\n'
  501. size_t len = strlen(msg->text);
  502. if (len > 0 && msg->text[len - 1] == '\n')
  503. len -= 1;
  504. QString logline = QString::fromUtf8(msg->prefix) + ": " + QString::fromUtf8(msg->text, (int)len);
  505. if (msg->log_level >= MPV_LOG_LEVEL_V)
  506. QLOG_DEBUG() << qPrintable(logline);
  507. else if (msg->log_level >= MPV_LOG_LEVEL_INFO)
  508. QLOG_INFO() << qPrintable(logline);
  509. else if (msg->log_level >= MPV_LOG_LEVEL_WARN)
  510. QLOG_WARN() << qPrintable(logline);
  511. else
  512. QLOG_ERROR() << qPrintable(logline);
  513. break;
  514. }
  515. case MPV_EVENT_CLIENT_MESSAGE:
  516. {
  517. mpv_event_client_message *msg = (mpv_event_client_message *)event->data;
  518. if (msg->num_args < 3 || strcmp(msg->args[0], "hook_run") != 0)
  519. break;
  520. QString resumeId = QString::fromUtf8(msg->args[2]);
  521. // Start "on_load" hook.
  522. // This happens when the player is about to load the file, but no actual loading has taken part yet.
  523. // We use this to block loading until we explicitly tell it to continue.
  524. if (!strcmp(msg->args[1], "1"))
  525. {
  526. // Calling this lambda will instruct mpv to continue loading the file.
  527. auto resume = [=] {
  528. QLOG_INFO() << "checking codecs";
  529. startCodecsLoading([=] {
  530. QLOG_INFO() << "resuming loading";
  531. mpv::qt::command(m_mpv, QStringList() << "hook-ack" << resumeId);
  532. });
  533. };
  534. if (switchDisplayFrameRate())
  535. {
  536. // Now wait for some time for mode change - this is needed because mode changing can take some
  537. // time, during which the screen is black, and initializing hardware decoding could fail due
  538. // to various strange OS-related reasons.
  539. // (Better hope the user doesn't try to exit Konvergo during mode change.)
  540. int pause = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.delay").toInt() * 1000;
  541. QLOG_INFO() << "waiting" << pause << "msec after rate switch before loading";
  542. QTimer::singleShot(pause, resume);
  543. }
  544. else
  545. {
  546. resume();
  547. }
  548. break;
  549. }
  550. // Start "on_preloaded" hook.
  551. // Used initialize stream selections and to probe codecs.
  552. if (!strcmp(msg->args[1], "2"))
  553. {
  554. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  555. reselectStream(m_currentAudioStream, MediaType::Audio);
  556. startCodecsLoading([=] {
  557. mpv::qt::command(m_mpv, QStringList() << "hook-ack" << resumeId);
  558. });
  559. break;
  560. }
  561. break;
  562. }
  563. #if MPV_CLIENT_API_VERSION >= MPV_MAKE_VERSION(1, 100)
  564. case MPV_EVENT_HOOK:
  565. {
  566. mpv_event_hook *hook = (mpv_event_hook *)event->data;
  567. uint64_t id = hook->id;
  568. if (!strcmp(hook->name, "on_load"))
  569. {
  570. // Calling this lambda will instruct mpv to continue loading the file.
  571. auto resume = [=] {
  572. QLOG_INFO() << "checking codecs";
  573. startCodecsLoading([=] {
  574. QLOG_INFO() << "resuming loading";
  575. mpv_hook_continue(m_mpv, id);
  576. });
  577. };
  578. if (switchDisplayFrameRate())
  579. {
  580. // Now wait for some time for mode change - this is needed because mode changing can take some
  581. // time, during which the screen is black, and initializing hardware decoding could fail due
  582. // to various strange OS-related reasons.
  583. // (Better hope the user doesn't try to exit Konvergo during mode change.)
  584. int pause = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.delay").toInt() * 1000;
  585. QLOG_INFO() << "waiting" << pause << "msec after rate switch before loading";
  586. QTimer::singleShot(pause, resume);
  587. }
  588. else
  589. {
  590. resume();
  591. }
  592. break;
  593. }
  594. if (!strcmp(hook->name, "on_preloaded"))
  595. {
  596. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  597. reselectStream(m_currentAudioStream, MediaType::Audio);
  598. startCodecsLoading([=] {
  599. mpv_hook_continue(m_mpv, id);
  600. });
  601. break;
  602. }
  603. break;
  604. }
  605. #endif
  606. default:; /* ignore */
  607. }
  608. }
  609. ///////////////////////////////////////////////////////////////////////////////////////////////////
  610. void PlayerComponent::handleMpvEvents()
  611. {
  612. // Process all events, until the event queue is empty.
  613. while (1)
  614. {
  615. mpv_event *event = mpv_wait_event(m_mpv, 0);
  616. if (event->event_id == MPV_EVENT_NONE)
  617. break;
  618. handleMpvEvent(event);
  619. }
  620. // Once we got all status updates, determine the new canonical state.
  621. updatePlaybackState();
  622. }
  623. ///////////////////////////////////////////////////////////////////////////////////////////////////
  624. void PlayerComponent::setVideoOnlyMode(bool enable)
  625. {
  626. if (m_window)
  627. {
  628. QQuickItem *web = m_window->findChild<QQuickItem *>("web");
  629. if (web)
  630. web->setVisible(!enable);
  631. }
  632. }
  633. ///////////////////////////////////////////////////////////////////////////////////////////////////
  634. void PlayerComponent::play()
  635. {
  636. QStringList args = (QStringList() << "set" << "pause" << "no");
  637. mpv::qt::command(m_mpv, args);
  638. }
  639. ///////////////////////////////////////////////////////////////////////////////////////////////////
  640. void PlayerComponent::stop()
  641. {
  642. QStringList args("stop");
  643. mpv::qt::command(m_mpv, args);
  644. }
  645. ///////////////////////////////////////////////////////////////////////////////////////////////////
  646. void PlayerComponent::clearQueue()
  647. {
  648. QStringList args("playlist_clear");
  649. mpv::qt::command(m_mpv, args);
  650. }
  651. ///////////////////////////////////////////////////////////////////////////////////////////////////
  652. void PlayerComponent::pause()
  653. {
  654. QStringList args = (QStringList() << "set" << "pause" << "yes");
  655. mpv::qt::command(m_mpv, args);
  656. }
  657. ///////////////////////////////////////////////////////////////////////////////////////////////////
  658. void PlayerComponent::seekTo(qint64 ms)
  659. {
  660. double timeSecs = ms / 1000.0;
  661. QVariantList args = (QVariantList() << "seek" << timeSecs << "absolute+exact");
  662. mpv::qt::command(m_mpv, args);
  663. }
  664. ///////////////////////////////////////////////////////////////////////////////////////////////////
  665. QVariant PlayerComponent::getAudioDeviceList()
  666. {
  667. return mpv::qt::get_property(m_mpv, "audio-device-list");
  668. }
  669. ///////////////////////////////////////////////////////////////////////////////////////////////////
  670. void PlayerComponent::setAudioDevice(const QString& name)
  671. {
  672. mpv::qt::set_property(m_mpv, "audio-device", name);
  673. }
  674. ///////////////////////////////////////////////////////////////////////////////////////////////////
  675. void PlayerComponent::setVolume(int volume)
  676. {
  677. // Will fail if no audio output opened (i.e. no file playing)
  678. mpv::qt::set_property(m_mpv, "volume", volume);
  679. }
  680. ///////////////////////////////////////////////////////////////////////////////////////////////////
  681. int PlayerComponent::volume()
  682. {
  683. QVariant volume = mpv::qt::get_property(m_mpv, "volume");
  684. if (volume.isValid())
  685. return volume.toInt();
  686. return 0;
  687. }
  688. ///////////////////////////////////////////////////////////////////////////////////////////////////
  689. void PlayerComponent::setMuted(bool muted)
  690. {
  691. // Will fail if no audio output opened (i.e. no file playing)
  692. mpv::qt::set_property(m_mpv, "mute", muted);
  693. }
  694. ///////////////////////////////////////////////////////////////////////////////////////////////////
  695. bool PlayerComponent::muted()
  696. {
  697. QVariant mute = mpv::qt::get_property(m_mpv, "mute");
  698. if (mute.isValid())
  699. return mute.toBool();
  700. return false;
  701. }
  702. ///////////////////////////////////////////////////////////////////////////////////////////////////
  703. QVariantList PlayerComponent::findStreamsForURL(const QString &url)
  704. {
  705. bool isExternal = !url.isEmpty();
  706. QVariantList res;
  707. auto tracks = mpv::qt::get_property(m_mpv, "track-list");
  708. for (auto track : tracks.toList())
  709. {
  710. QVariantMap map = track.toMap();
  711. if (map["external"].toBool() != isExternal)
  712. continue;
  713. if (!isExternal || map["external-filename"].toString() == url)
  714. res += map;
  715. }
  716. return res;
  717. }
  718. ///////////////////////////////////////////////////////////////////////////////////////////////////
  719. void PlayerComponent::reselectStream(const QString &streamSelection, MediaType target)
  720. {
  721. QString streamIdPropertyName;
  722. QString streamAddCommandName;
  723. QString mpvStreamTypeName;
  724. switch (target)
  725. {
  726. case MediaType::Subtitle:
  727. mpvStreamTypeName = "sub";
  728. streamIdPropertyName = "sid";
  729. streamAddCommandName = "sub-add";
  730. break;
  731. case MediaType::Audio:
  732. mpvStreamTypeName = "audio";
  733. streamIdPropertyName = "aid";
  734. streamAddCommandName = "audio-add";
  735. break;
  736. }
  737. QString streamName;
  738. QString streamID;
  739. if (streamSelection.startsWith("#"))
  740. {
  741. int splitPos = streamSelection.indexOf(",");
  742. if (splitPos < 0)
  743. {
  744. // Stream from the main file
  745. streamID = streamSelection.mid(1);
  746. streamName = "";
  747. }
  748. else
  749. {
  750. // Stream from an external file
  751. streamID = streamSelection.mid(1, splitPos - 1);
  752. streamName = streamSelection.mid(splitPos + 1);
  753. }
  754. }
  755. else if (!streamSelection.isEmpty())
  756. {
  757. if (target == MediaType::Audio)
  758. {
  759. // For some reason, audio stream selections never start with '#'.
  760. streamID = streamSelection;
  761. streamName = "";
  762. }
  763. else
  764. {
  765. // Legacy web-client single external subtitle
  766. streamID = "0";
  767. streamName = streamSelection;
  768. }
  769. }
  770. if (!streamName.isEmpty())
  771. {
  772. if (streamName.startsWith("https://")) {
  773. QUrl qurl = streamName;
  774. qurl.setHost(ConvertPlexDirectURL(qurl.host()));
  775. streamName = qurl.toString();
  776. }
  777. auto streams = findStreamsForURL(streamName);
  778. if (streams.isEmpty())
  779. {
  780. QStringList args = (QStringList() << streamAddCommandName << streamName);
  781. mpv::qt::command(m_mpv, args);
  782. }
  783. }
  784. QString selection = "no";
  785. for (auto stream : findStreamsForURL(streamName))
  786. {
  787. auto map = stream.toMap();
  788. if (map["type"].toString() != mpvStreamTypeName)
  789. continue;
  790. if (!streamID.isEmpty() && map["ff-index"].toString() == streamID)
  791. {
  792. selection = map["id"].toString();
  793. break;
  794. }
  795. }
  796. // Fallback to the first stream if none could be found.
  797. // Useful if web-client uses wrong stream IDs when e.g. transcoding.
  798. if ((target == MediaType::Audio || !streamID.isEmpty()) && selection == "no")
  799. selection = "1";
  800. mpv::qt::set_property(m_mpv, streamIdPropertyName, selection);
  801. }
  802. ///////////////////////////////////////////////////////////////////////////////////////////////////
  803. void PlayerComponent::setSubtitleStream(const QString &subtitleStream)
  804. {
  805. m_currentSubtitleStream = subtitleStream;
  806. reselectStream(m_currentSubtitleStream, MediaType::Subtitle);
  807. }
  808. ///////////////////////////////////////////////////////////////////////////////////////////////////
  809. void PlayerComponent::setAudioStream(const QString &audioStream)
  810. {
  811. m_currentAudioStream = audioStream;
  812. reselectStream(m_currentAudioStream, MediaType::Audio);
  813. }
  814. /////////////////////////////////////////////////////////////////////////////////////////
  815. void PlayerComponent::setAudioDelay(qint64 milliseconds)
  816. {
  817. m_playbackAudioDelay = milliseconds;
  818. double displayFps = DisplayComponent::Get().currentRefreshRate();
  819. const char *audioDelaySetting = "audio_delay.normal";
  820. if (fabs(displayFps - 24) < 0.5) // cover 24Hz, 23.976Hz, and values very close
  821. audioDelaySetting = "audio_delay.24hz";
  822. else if (fabs(displayFps - 25) < 0.5)
  823. audioDelaySetting = "audio_delay.25hz";
  824. else if (fabs(displayFps - 50) < 0.5)
  825. audioDelaySetting = "audio_delay.50hz";
  826. double fixedDelay = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, audioDelaySetting).toFloat();
  827. mpv::qt::set_property(m_mpv, "audio-delay", (fixedDelay + m_playbackAudioDelay) / 1000.0);
  828. }
  829. /////////////////////////////////////////////////////////////////////////////////////////
  830. void PlayerComponent::setSubtitleDelay(qint64 milliseconds)
  831. {
  832. mpv::qt::set_property(m_mpv, "sub-delay", milliseconds / 1000.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-text-font-size", size);
  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-text-color", colors[0]);
  980. mpv::qt::set_property(m_mpv, "sub-text-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-text-align-x", subpos[0]);
  987. mpv::qt::set_property(m_mpv, "sub-text-align-y", subpos[1]);
  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:" << endl;
  1297. info << "URL: " << MPV_PROPERTY("path") << endl;
  1298. info << "Container: " << MPV_PROPERTY("file-format") << endl;
  1299. info << "Native seeking: " << ((MPV_PROPERTY_BOOL("seekable") &&
  1300. !MPV_PROPERTY_BOOL("partially-seekable"))
  1301. ? "yes" : "no") << endl;
  1302. info << endl;
  1303. info << "Video:" << endl;
  1304. info << "Codec: " << MPV_PROPERTY("video-codec") << endl;
  1305. info << "Size: " << MPV_PROPERTY("video-params/dw") << "x"
  1306. << MPV_PROPERTY("video-params/dh") << endl;
  1307. info << "FPS (container): " << MPV_PROPERTY("container-fps") << endl;
  1308. info << "FPS (filters): " << MPV_PROPERTY("estimated-vf-fps") << endl;
  1309. info << "Aspect: " << MPV_PROPERTY("video-aspect") << endl;
  1310. info << "Bitrate: " << MPV_PROPERTY("video-bitrate") << endl;
  1311. double displayFps = DisplayComponent::Get().currentRefreshRate();
  1312. info << "Display FPS: " << MPV_PROPERTY("display-fps")
  1313. << " (" << displayFps << ")" << endl;
  1314. info << "Hardware Decoding: " << MPV_PROPERTY("hwdec-current")
  1315. << " (" << MPV_PROPERTY("hwdec-interop") << ")" << endl;
  1316. info << endl;
  1317. info << "Audio: " << endl;
  1318. info << "Codec: " << MPV_PROPERTY("audio-codec") << endl;
  1319. info << "Bitrate: " << MPV_PROPERTY("audio-bitrate") << endl;
  1320. info << "Channels: ";
  1321. appendAudioFormat(info, "audio-params");
  1322. info << " -> ";
  1323. appendAudioFormat(info, "audio-out-params");
  1324. info << endl;
  1325. info << "Output driver: " << MPV_PROPERTY("current-ao") << endl;
  1326. info << endl;
  1327. info << "Performance: " << endl;
  1328. info << "A/V: " << MPV_PROPERTY("avsync") << endl;
  1329. info << "Dropped frames: " << MPV_PROPERTY("vo-drop-frame-count") << endl;
  1330. bool dispSync = MPV_PROPERTY_BOOL("display-sync-active");
  1331. info << "Display Sync: ";
  1332. if (!dispSync)
  1333. {
  1334. info << "no" << endl;
  1335. }
  1336. else
  1337. {
  1338. info << "yes (ratio " << MPV_PROPERTY("vsync-ratio") << ")" << endl;
  1339. info << "Mistimed frames: " << MPV_PROPERTY("mistimed-frame-count")
  1340. << "/" << MPV_PROPERTY("vo-delayed-frame-count") << endl;
  1341. info << "Measured FPS: " << MPV_PROPERTY("estimated-display-fps")
  1342. << " (" << MPV_PROPERTY("vsync-jitter") << ")" << endl;
  1343. info << "V. speed corr.: " << MPV_PROPERTY("video-speed-correction") << endl;
  1344. info << "A. speed corr.: " << MPV_PROPERTY("audio-speed-correction") << endl;
  1345. }
  1346. info << endl;
  1347. info << "Cache:" << endl;
  1348. info << "Seconds: " << MPV_PROPERTY("demuxer-cache-duration") << endl;
  1349. info << "Extra readahead: " << MPV_PROPERTY("cache-used") << endl;
  1350. info << "Buffering: " << MPV_PROPERTY("cache-buffering-state") << endl;
  1351. info << "Speed: " << MPV_PROPERTY("cache-speed") << endl;
  1352. info << endl;
  1353. info << "Misc: " << endl;
  1354. info << "Time: " << MPV_PROPERTY("playback-time") << " / "
  1355. << MPV_PROPERTY("duration")
  1356. << " (" << MPV_PROPERTY("percent-pos") << "%)" << endl;
  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. << endl;
  1362. info << flush;
  1363. return infoStr;
  1364. }