PlayerComponent.cpp 53 KB

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