PlayerComponent.cpp 49 KB

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