CodecsComponent.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. #include "CodecsComponent.h"
  2. #include <QString>
  3. #include <Qt>
  4. #include <QDir>
  5. #include <QDomAttr>
  6. #include <QDomDocument>
  7. #include <QDomNode>
  8. #include <QCoreApplication>
  9. #include <QProcess>
  10. #include <QUuid>
  11. #include <QUrl>
  12. #include <QUrlQuery>
  13. #include <QResource>
  14. #include <QSaveFile>
  15. #include <QStandardPaths>
  16. #include <QSysInfo>
  17. #include <QCryptographicHash>
  18. #include <QTemporaryDir>
  19. #ifdef HAVE_MINIZIP
  20. #include <minizip/unzip.h>
  21. #include <minizip/ioapi.h>
  22. #endif
  23. #include "system/SystemComponent.h"
  24. #include "settings/SettingsComponent.h"
  25. #include "utils/Utils.h"
  26. #include "shared/Paths.h"
  27. #include "PlayerComponent.h"
  28. #include "QsLog.h"
  29. #define countof(x) (sizeof(x) / sizeof((x)[0]))
  30. // For QVariant. Mysteriously makes Qt happy.
  31. Q_DECLARE_METATYPE(CodecDriver);
  32. #ifdef HAVE_CODEC_MANIFEST
  33. #define WITH_CODECS 1
  34. #include "CodecManifest.h"
  35. #else
  36. #define WITH_CODECS 0
  37. #define CODEC_VERSION "dummy"
  38. #define SHLIB_PREFIX ""
  39. #define SHLIB_EXTENSION "dummy"
  40. // Codec.name is the name of the codec implementation, Codec.codecName the name of the codec
  41. struct Codec {const char* name; const char* codecName; const char* profiles; int external;};
  42. static const Codec Decoders[] = {
  43. {"dummy", "dummy", nullptr, 1},
  44. };
  45. static const Codec Encoders[] = {
  46. {"dummy", "dummy", nullptr, 1},
  47. };
  48. #endif
  49. #define STRINGIFY_(x) #x
  50. #define STRINGIFY(x) STRINGIFY_(x)
  51. #ifdef EAE_VERSION
  52. #define HAVE_EAE 1
  53. #else
  54. #define EAE_VERSION unavailable
  55. #define HAVE_EAE 0
  56. #endif
  57. // We might want to use Codec.quality to decide this one day.
  58. // But for now, it's better if we can quickly change these.
  59. static QSet<QString> g_systemVideoDecoderWhitelist = {
  60. // RPI
  61. "h264_mmal",
  62. "mpeg2_mmal",
  63. "mpeg4_mmal",
  64. "vc1_mmal",
  65. };
  66. static QSet<QString> g_systemAudioDecoderWhitelist = {
  67. // OSX
  68. "eac3_at",
  69. // Windows
  70. "eac3_mf",
  71. };
  72. static QSet<QString> g_systemAudioEncoderWhitelist = {
  73. };
  74. static QSize g_mediaFoundationH264MaxResolution;
  75. static QString g_codecVersion;
  76. static QList<CodecDriver> g_cachedCodecList;
  77. static QString g_deviceID;
  78. static QString g_eaeWatchFolder;
  79. static QProcess* g_eaeProcess;
  80. ///////////////////////////////////////////////////////////////////////////////////////////////////
  81. static QString getBuildType()
  82. {
  83. #ifdef Q_OS_MAC
  84. return "darwin-x86_64";
  85. #elif defined(TARGET_RPI)
  86. return "openelec-armv7";
  87. #else
  88. return SystemComponent::Get().getPlatformTypeString() + "-" +
  89. SystemComponent::Get().getPlatformArchString();
  90. #endif
  91. }
  92. ///////////////////////////////////////////////////////////////////////////////////////////////////
  93. static QString getEAEBuildType()
  94. {
  95. #if defined(Q_OS_MAC)
  96. return "darwin-x86_64";
  97. #elif defined(Q_OS_WIN)
  98. return sizeof(void *) > 4 ? "windows-x86_64" : "windows-i386";
  99. #elif defined(TARGET_RPI)
  100. return "linux-raspi2-arm7";
  101. #elif defined(Q_OS_LINUX)
  102. return sizeof(void *) > 4 ? "linux-ubuntu-x86_64" : "linux-ubuntu-i686";
  103. #else
  104. return "unknown";
  105. #endif
  106. }
  107. ///////////////////////////////////////////////////////////////////////////////////////////////////
  108. QString Codecs::plexNameToFF(QString plex)
  109. {
  110. if (plex == "dca")
  111. return "dts";
  112. return plex;
  113. }
  114. ///////////////////////////////////////////////////////////////////////////////////////////////////
  115. QString Codecs::plexNameFromFF(QString ffname)
  116. {
  117. if (ffname == "dts")
  118. return "dca";
  119. return ffname;
  120. }
  121. ///////////////////////////////////////////////////////////////////////////////////////////////////
  122. static QString codecsRootPath()
  123. {
  124. return Paths::dataDir("Codecs") + QDir::separator();
  125. }
  126. ///////////////////////////////////////////////////////////////////////////////////////////////////
  127. static QString codecsPath()
  128. {
  129. return codecsRootPath() + g_codecVersion + "-" + getBuildType() + QDir::separator();
  130. }
  131. ///////////////////////////////////////////////////////////////////////////////////////////////////
  132. static QString eaePrefixPath()
  133. {
  134. // (Keep in sync with PMS paths.)
  135. return codecsRootPath() + "EasyAudioEncoder-" + STRINGIFY(EAE_VERSION) + "-" + getBuildType();
  136. }
  137. ///////////////////////////////////////////////////////////////////////////////////////////////////
  138. static QString eaeBinaryPath()
  139. {
  140. QString exeSuffix = "";
  141. #ifdef Q_OS_WIN
  142. exeSuffix = ".exe";
  143. #endif
  144. return eaePrefixPath() + "/EasyAudioEncoder/EasyAudioEncoder" + exeSuffix;
  145. }
  146. ///////////////////////////////////////////////////////////////////////////////////////////////////
  147. static bool eaeIsPresent()
  148. {
  149. return QFile(eaeBinaryPath()).exists();
  150. }
  151. ///////////////////////////////////////////////////////////////////////////////////////////////////
  152. static int indexOfCodecInList(const QList<CodecDriver>& list, const CodecDriver& codec)
  153. {
  154. for (int n = 0; n < list.size(); n++)
  155. {
  156. if (Codecs::sameCodec(list[n], codec))
  157. return n;
  158. }
  159. return -1;
  160. }
  161. ///////////////////////////////////////////////////////////////////////////////////////////////////
  162. void Codecs::updateCachedCodecList()
  163. {
  164. g_cachedCodecList.clear();
  165. for (CodecType type : {CodecType::Decoder, CodecType::Encoder})
  166. {
  167. const Codec* list = (type == CodecType::Decoder) ? Decoders : Encoders;
  168. size_t count = (type == CodecType::Decoder) ? countof(Decoders) : countof(Encoders);
  169. for (size_t i = 0; i < count; i++)
  170. {
  171. CodecDriver codec = {};
  172. codec.type = type;
  173. codec.format = Codecs::plexNameToFF(list[i].codecName);
  174. codec.driver = list[i].name;
  175. codec.external = list[i].external;
  176. if (!codec.isSystemCodec())
  177. g_cachedCodecList.append(codec);
  178. }
  179. }
  180. // Set present flag for the installed codecs. Also, there could be codecs not
  181. // on the CodecManifest.h list (system codecs, or when compiled without
  182. // codec loading).
  183. QList<CodecDriver> installed = PlayerComponent::Get().installedCodecDrivers();
  184. // Surely O(n^2) won't be causing trouble, right?
  185. for (const CodecDriver& installedCodec : installed)
  186. {
  187. int index = indexOfCodecInList(g_cachedCodecList, installedCodec);
  188. if (index >= 0)
  189. g_cachedCodecList[index].present = true;
  190. else
  191. g_cachedCodecList.append(installedCodec);
  192. }
  193. }
  194. ///////////////////////////////////////////////////////////////////////////////////////////////////
  195. const QList<CodecDriver>& Codecs::getCachedCodecList()
  196. {
  197. return g_cachedCodecList;
  198. }
  199. ///////////////////////////////////////////////////////////////////////////////////////////////////
  200. QList<CodecDriver> Codecs::findCodecsByFormat(const QList<CodecDriver>& list, CodecType type, const QString& format)
  201. {
  202. QList<CodecDriver> result;
  203. for (const CodecDriver& codec : list)
  204. {
  205. if (codec.type == type && codec.format == format)
  206. result.append(codec);
  207. }
  208. return result;
  209. }
  210. ///////////////////////////////////////////////////////////////////////////////////////////////////
  211. QString CodecDriver::getMangledName() const
  212. {
  213. return driver + (type == CodecType::Decoder ? "_decoder" : "_encoder");
  214. }
  215. ///////////////////////////////////////////////////////////////////////////////////////////////////
  216. QString CodecDriver::getFileName() const
  217. {
  218. return SHLIB_PREFIX + getMangledName() + "." + SHLIB_EXTENSION;
  219. }
  220. ///////////////////////////////////////////////////////////////////////////////////////////////////
  221. QString CodecDriver::getPath() const
  222. {
  223. return QDir(codecsPath()).absoluteFilePath(getFileName());
  224. }
  225. ///////////////////////////////////////////////////////////////////////////////////////////////////
  226. bool CodecDriver::isSystemCodec() const
  227. {
  228. // MS Windows
  229. if (driver.endsWith("_mf"))
  230. return true;
  231. // OSX
  232. if (driver.endsWith("_at"))
  233. return true;
  234. // Linux on RPI
  235. if (driver.endsWith("_mmal"))
  236. return true;
  237. // Not really a system codec, but treated as such for convenience
  238. if (driver.endsWith("_eae"))
  239. return true;
  240. if (driver.endsWith("_cuvid"))
  241. return true;
  242. return false;
  243. }
  244. ///////////////////////////////////////////////////////////////////////////////////////////////////
  245. QString CodecDriver::getSystemCodecType() const
  246. {
  247. if (!isSystemCodec())
  248. return "";
  249. int splitAt = driver.indexOf("_");
  250. if (splitAt < 0)
  251. return "";
  252. return driver.mid(splitAt + 1);
  253. }
  254. ///////////////////////////////////////////////////////////////////////////////////////////////////
  255. bool CodecDriver::isWhitelistedSystemAudioCodec() const
  256. {
  257. if (type == CodecType::Decoder)
  258. return g_systemAudioDecoderWhitelist.contains(driver);
  259. else
  260. return g_systemAudioEncoderWhitelist.contains(driver);
  261. }
  262. ///////////////////////////////////////////////////////////////////////////////////////////////////
  263. bool CodecDriver::isWhitelistedSystemVideoCodec() const
  264. {
  265. if (type == CodecType::Decoder)
  266. return g_systemVideoDecoderWhitelist.contains(driver);
  267. return false;
  268. }
  269. ///////////////////////////////////////////////////////////////////////////////////////////////////
  270. static bool useSystemAudioDecoders()
  271. {
  272. return true;
  273. }
  274. ///////////////////////////////////////////////////////////////////////////////////////////////////
  275. static bool useSystemVideoDecoders()
  276. {
  277. return SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "useSystemVideoCodecs").toBool();
  278. }
  279. /////////////////////////////////////////////////////////////////////////////////////////
  280. // Load the device ID, do some minimal verification, return "" on error.
  281. static QString loadDeviceID(QString filename)
  282. {
  283. QFile path(filename);
  284. if (!path.open(QFile::ReadOnly))
  285. return "";
  286. auto res = QString::fromLatin1(path.readAll());
  287. if (res.size() < 32 || res.size() > 512)
  288. res = ""; // mark as invalid
  289. return res;
  290. }
  291. /////////////////////////////////////////////////////////////////////////////////////////
  292. static QString findOldDeviceID()
  293. {
  294. // First we try to reuse the ID from other Plex products (i.e. PMS) or older paths.
  295. QStringList candidates = {
  296. #ifdef Q_OS_MAC
  297. QDir::home().path() + "/Library/Application Support/Plex/Codecs/.device-id",
  298. QDir::home().path() + "/Library/Application Support/Plex Media Server/Codecs/.device-id",
  299. QDir::home().path() + "/Library/Application Support/Plex/Plex Media Server/Codecs/.device-id",
  300. #endif
  301. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex/Codecs/.device-id",
  302. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex/codecs/.device-id",
  303. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex Media Server/Codecs/.device-id",
  304. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex/Plex Media Server/Codecs/.device-id",
  305. Paths::dataDir() + "/codecs/.device-id",
  306. };
  307. for (auto candidate : candidates)
  308. {
  309. auto id = loadDeviceID(candidate);
  310. if (!id.isEmpty())
  311. return id;
  312. }
  313. return "";
  314. }
  315. ///////////////////////////////////////////////////////////////////////////////////////////////////
  316. // Returns "" on error.
  317. static QString loadDeviceID()
  318. {
  319. QString deviceIDFilename = QDir(codecsRootPath()).absoluteFilePath(".device-id");
  320. QString id = loadDeviceID(deviceIDFilename);
  321. if (id.isEmpty())
  322. {
  323. id = findOldDeviceID();
  324. if (id.isEmpty())
  325. {
  326. id = QUuid::createUuid().toString();
  327. // The UUID should be e.g. "8f6ad954-0cb9-4dbb-a5e5-e0b085f07cf8"
  328. if (id.startsWith("{"))
  329. id = id.mid(1);
  330. if (id.endsWith("}"))
  331. id = id.mid(0, id.size() - 1);
  332. }
  333. Utils::safelyWriteFile(deviceIDFilename, id.toLatin1());
  334. // We load it again to make sure writing it succeeded. If it doesn't, we'll
  335. // error out at a later point.
  336. id = loadDeviceID(deviceIDFilename);
  337. }
  338. return id;
  339. }
  340. ///////////////////////////////////////////////////////////////////////////////////////////////////
  341. static QString getFFmpegVersion()
  342. {
  343. auto mpv = mpv::qt::Handle::FromRawHandle(mpv_create());
  344. if (!mpv || mpv_initialize(mpv) < 0)
  345. return "";
  346. return mpv::qt::get_property(mpv, "ffmpeg-version").toString();
  347. }
  348. ///////////////////////////////////////////////////////////////////////////////////////////////////
  349. static void setEnv(QString var, QString val)
  350. {
  351. #ifdef Q_OS_WIN
  352. SetEnvironmentVariableW(var.toStdWString().c_str(), val.toStdWString().c_str());
  353. #else
  354. qputenv(var.toUtf8().data(), val.toUtf8().data());
  355. #endif
  356. }
  357. ///////////////////////////////////////////////////////////////////////////////////////////////////
  358. void Codecs::preinitCodecs()
  359. {
  360. // Extract the CI codecs version we set with --extra-version when compiling FFmpeg.
  361. QString ffmpegVersion = getFFmpegVersion();
  362. int sep = ffmpegVersion.indexOf(',');
  363. if (sep >= 0)
  364. g_codecVersion = ffmpegVersion.mid(sep + 1);
  365. else
  366. g_codecVersion = CODEC_VERSION;
  367. QString path = codecsPath();
  368. QDir("").mkpath(path);
  369. // Follows the convention used by av_get_token().
  370. QString escapedPath = path.replace("\\", "\\\\").replace(":", "\\:").replace("'", "\\'");
  371. // This must be run before any threads are started etc. (for safety).
  372. setEnv("FFMPEG_EXTERNAL_LIBS", escapedPath);
  373. QTemporaryDir d(QDir::tempPath() + "/pmp-eae-XXXXXX");
  374. d.setAutoRemove(false);
  375. g_eaeWatchFolder = d.path();
  376. setEnv("EAE_ROOT", g_eaeWatchFolder);
  377. g_deviceID = loadDeviceID();
  378. }
  379. #if 0
  380. ///////////////////////////////////////////////////////////////////////////////////////////////////
  381. static bool probeDecoder(QString decoder, QString resourceName)
  382. {
  383. QResource resource(resourceName);
  384. QLOG_DEBUG() << "Testing decoding of" << resource.fileName();
  385. if (!resource.isValid())
  386. return false;
  387. auto mpv = mpv::qt::Handle::FromRawHandle(mpv_create());
  388. if (!mpv || mpv_initialize(mpv) < 0)
  389. return false;
  390. // Disable any output.
  391. mpv::qt::set_property(mpv, "vo", "null");
  392. // Force the decoder. The ",-" means that if the first entry fails, the next codec in the global
  393. // codec list will not be tried, and decoding fails.
  394. mpv::qt::set_property(mpv, "vd", "lavc:" + decoder + ",-");
  395. // Attempt decoding, and return success.
  396. auto data = QByteArray::fromRawData((const char *)resource.data(), resource.size());
  397. if (resource.isCompressed())
  398. data = qUncompress(data);
  399. auto hex = data.toHex();
  400. mpv::qt::command(mpv, QVariantList{"loadfile", "hex://" + QString::fromLatin1(hex)});
  401. bool result = false;
  402. while (1) {
  403. mpv_event *event = mpv_wait_event(mpv, 0);
  404. if (event->event_id == MPV_EVENT_SHUTDOWN)
  405. break;
  406. if (event->event_id == MPV_EVENT_END_FILE)
  407. {
  408. mpv_event_end_file *endFile = (mpv_event_end_file *)event->data;
  409. result = endFile->reason == MPV_END_FILE_REASON_EOF;
  410. break;
  411. }
  412. }
  413. QLOG_DEBUG() << "Result:" << result;
  414. return result;
  415. }
  416. #endif
  417. ///////////////////////////////////////////////////////////////////////////////////////////////////
  418. static void probeCodecs()
  419. {
  420. #if 0
  421. if (useSystemVideoDecoders())
  422. {
  423. if (probeDecoder("h264_mf", ":/testmedia/high_4096x2304.h264"))
  424. g_mediaFoundationH264MaxResolution = QSize(4096, 2304);
  425. else if (probeDecoder("h264_mf", ":/testmedia/high_4096x2160.h264"))
  426. g_mediaFoundationH264MaxResolution = QSize(4096, 2160);
  427. else if (probeDecoder("h264_mf", ":/testmedia/high_4096x1080.h264"))
  428. g_mediaFoundationH264MaxResolution = QSize(4096, 1080);
  429. else
  430. g_systemVideoDecoderWhitelist.remove("h264_mf");
  431. QLOG_DEBUG() << "h264_mf max. resolution:" << g_mediaFoundationH264MaxResolution;
  432. }
  433. #endif
  434. #ifdef Q_OS_MAC
  435. // Unsupported, but avoid picking up broken Perian decoders.
  436. if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_10)
  437. g_systemAudioDecoderWhitelist.remove("ac3_at");
  438. // Unknown Apple crashes
  439. if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_11)
  440. g_systemAudioDecoderWhitelist.remove("aac_at");
  441. #endif
  442. }
  443. ///////////////////////////////////////////////////////////////////////////////////////////////////
  444. static void updateCodecs()
  445. {
  446. QStringList candidates = {
  447. codecsRootPath(),
  448. #ifdef Q_OS_MAC
  449. QDir::home().path() + "/Library/Application Support/Plex/Codecs/",
  450. QDir::home().path() + "/Library/Application Support/Plex Media Server/Codecs/",
  451. #endif
  452. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex/Codecs/",
  453. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex/codecs/",
  454. QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Plex Media Server/Codecs/",
  455. Paths::dataDir() + "/codecs/",
  456. };
  457. QSet<QString> codecFiles;
  458. bool needEAE = false;
  459. for (auto dir : candidates)
  460. {
  461. QDir qdir(dir);
  462. if (!qdir.exists())
  463. continue;
  464. for (auto entry : qdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
  465. {
  466. QDir entryDir = qdir;
  467. if (!entryDir.cd(entry))
  468. continue;
  469. for (auto codecdirEntry : entryDir.entryList(QDir::Files))
  470. codecFiles.insert(codecdirEntry);
  471. // NOTE: PMS also uses this prefix
  472. if (entry.startsWith("EasyAudioEncoder-") && !eaeIsPresent())
  473. needEAE = true;
  474. }
  475. }
  476. QList<CodecDriver> install;
  477. for (CodecDriver& codec : g_cachedCodecList)
  478. {
  479. if ((codecFiles.contains(codec.getFileName()) && codec.external && !codec.present) ||
  480. (codec.getSystemCodecType() == "eae" && needEAE))
  481. install.append(codec);
  482. }
  483. if (!install.empty())
  484. {
  485. QStringList codecs;
  486. for (auto codec : install)
  487. codecs.append(codec.getMangledName());
  488. QLOG_INFO() << "Updating some codecs: " + codecs.join(", ");
  489. auto fetcher = new CodecsFetcher();
  490. QObject::connect(fetcher, &CodecsFetcher::done, [](CodecsFetcher* sender)
  491. {
  492. QLOG_INFO() << "Codec update finished.";
  493. sender->deleteLater();
  494. });
  495. fetcher->startCodecs = false;
  496. fetcher->installCodecs(install);
  497. }
  498. }
  499. ///////////////////////////////////////////////////////////////////////////////////////////////////
  500. static void deleteOldCodecs()
  501. {
  502. QStringList neededPaths = {
  503. codecsPath(),
  504. };
  505. for (auto entry : QDir(codecsRootPath()).entryList(QDir::Dirs | QDir::NoDotAndDotDot))
  506. {
  507. QDir entryPath = codecsRootPath();
  508. if (!entryPath.cd(entry))
  509. continue;
  510. bool needed = false;
  511. for (auto neededPath : neededPaths)
  512. {
  513. if (entryPath.absolutePath() == QDir(neededPath).absolutePath())
  514. {
  515. needed = true;
  516. break;
  517. }
  518. }
  519. if (needed)
  520. continue;
  521. // Same version, but different platform -> just keep it.
  522. if (entry.startsWith(g_codecVersion + "-"))
  523. continue;
  524. // EAE is "special"
  525. if (entry.startsWith(QString("EasyAudioEncoder-") + STRINGIFY(EAE_VERSION) + "-"))
  526. continue;
  527. QLOG_DEBUG() << "Deleting old directory: " << entryPath.absolutePath();
  528. entryPath.removeRecursively();
  529. }
  530. }
  531. ///////////////////////////////////////////////////////////////////////////////////////////////////
  532. void Codecs::initCodecs()
  533. {
  534. if (g_deviceID.isEmpty())
  535. throw FatalException("Could not read device-id.");
  536. if (g_eaeWatchFolder.isEmpty())
  537. throw FatalException("Could not create EAE working directory.");
  538. Codecs::updateCachedCodecList();
  539. updateCodecs();
  540. deleteOldCodecs();
  541. probeCodecs();
  542. }
  543. ///////////////////////////////////////////////////////////////////////////////////////////////////
  544. bool CodecsFetcher::codecNeedsDownload(const CodecDriver& codec)
  545. {
  546. if (codec.present)
  547. return false;
  548. if (!codec.external)
  549. {
  550. QLOG_ERROR() << "Codec" << codec.driver << "does not exist and is not downloadable.";
  551. return false;
  552. }
  553. for (int n = 0; n < m_Codecs.size(); n++)
  554. {
  555. if (Codecs::sameCodec(codec, m_Codecs[n]))
  556. return false;
  557. }
  558. QFile codecFile(codec.getPath());
  559. if (codecFile.exists())
  560. {
  561. QLOG_ERROR() << "Codec" << codec.driver << "exists on disk as" << codec.getPath()
  562. << "but is not known as installed - broken codec?";
  563. if (!codecFile.remove())
  564. return false;
  565. QLOG_ERROR() << "Retrying download.";
  566. }
  567. return true;
  568. }
  569. ///////////////////////////////////////////////////////////////////////////////////////////////////
  570. void CodecsFetcher::installCodecs(const QList<CodecDriver>& codecs)
  571. {
  572. foreach (CodecDriver codec, codecs)
  573. {
  574. if (codecNeedsDownload(codec))
  575. m_Codecs.enqueue(codec);
  576. if (codec.getSystemCodecType() == "eae")
  577. {
  578. m_eaeNeeded = true;
  579. if (!eaeIsPresent())
  580. m_fetchEAE = true;
  581. }
  582. }
  583. startNext();
  584. }
  585. ///////////////////////////////////////////////////////////////////////////////////////////////////
  586. static Downloader::HeaderList getPlexHeaders()
  587. {
  588. Downloader::HeaderList headers;
  589. QString auth = SystemComponent::Get().authenticationToken();
  590. if (auth.size())
  591. headers.append({"X-Plex-Token", auth});
  592. headers.append({"X-Plex-Product", WITH_CODECS ? "Plex Media Player" : "openpmp"});
  593. headers.append({"X-Plex-Platform", "Konvergo"});
  594. return headers;
  595. }
  596. static QUrl buildCodecQuery(QString version, QString name, QString build)
  597. {
  598. QString host = "https://plex.tv";
  599. QUrl url = QUrl(host + "/api/codecs/" + name);
  600. QUrlQuery query;
  601. query.addQueryItem("deviceId", g_deviceID);
  602. query.addQueryItem("version", version);
  603. query.addQueryItem("build", build);
  604. query.addQueryItem("oldestPreviousVersion", SettingsComponent::Get().oldestPreviousVersion());
  605. url.setQuery(query);
  606. return url;
  607. }
  608. ///////////////////////////////////////////////////////////////////////////////////////////////////
  609. void CodecsFetcher::startNext()
  610. {
  611. if (m_fetchEAE)
  612. {
  613. m_fetchEAE = false;
  614. QUrl url = buildCodecQuery(STRINGIFY(EAE_VERSION), "easyaudioencoder", getEAEBuildType());
  615. Downloader *downloader = new Downloader(QVariant("eae"), url, getPlexHeaders(), this);
  616. connect(downloader, &Downloader::done, this, &CodecsFetcher::codecInfoDownloadDone);
  617. return;
  618. }
  619. if (m_Codecs.isEmpty())
  620. {
  621. // Do final initializations.
  622. if (m_eaeNeeded && startCodecs)
  623. startEAE();
  624. emit done(this);
  625. return;
  626. }
  627. CodecDriver codec = m_Codecs.dequeue();
  628. QUrl url = buildCodecQuery(g_codecVersion, codec.getMangledName(), getBuildType());
  629. Downloader *downloader = new Downloader(QVariant::fromValue(codec), url, getPlexHeaders(), this);
  630. connect(downloader, &Downloader::done, this, &CodecsFetcher::codecInfoDownloadDone);
  631. }
  632. ///////////////////////////////////////////////////////////////////////////////////////////////////
  633. bool CodecsFetcher::processCodecInfoReply(const QVariant& context, const QByteArray& data)
  634. {
  635. QLOG_INFO() << "Got reply:" << QString::fromUtf8(data);
  636. QDomDocument dom;
  637. if (!dom.setContent(data))
  638. {
  639. QLOG_ERROR() << "XML parsing error.";
  640. return false;
  641. }
  642. QDomNodeList list = dom.elementsByTagName("MediaContainer");
  643. if (list.count() != 1)
  644. {
  645. QLOG_ERROR() << "MediaContainer XML element not found.";
  646. return false;
  647. }
  648. list = dom.elementsByTagName("Codec");
  649. if (list.count() != 1)
  650. {
  651. QLOG_ERROR() << "Codec XML element not found.";
  652. return false;
  653. }
  654. QDomNamedNodeMap attrs = list.at(0).attributes();
  655. QString url = attrs.namedItem("url").toAttr().value();
  656. if (!url.size())
  657. {
  658. QLOG_ERROR() << "No URL found.";
  659. return false;
  660. }
  661. QString hash = attrs.namedItem("fileSha").toAttr().value();
  662. m_currentHash = QByteArray::fromHex(hash.toUtf8());
  663. // it's hardcoded to SHA-1
  664. if (!m_currentHash.size()) {
  665. QLOG_ERROR() << "Hash value in unexpected format or missing:" << hash;
  666. return false;
  667. }
  668. Downloader *downloader = new Downloader(context, url, getPlexHeaders(), this);
  669. connect(downloader, &Downloader::done, this, &CodecsFetcher::codecDownloadDone);
  670. return true;
  671. }
  672. ///////////////////////////////////////////////////////////////////////////////////////////////////
  673. void CodecsFetcher::codecInfoDownloadDone(QVariant userData, bool success, const QByteArray& data)
  674. {
  675. if (!success || !processCodecInfoReply(userData, data))
  676. {
  677. QLOG_ERROR() << "Codec download failed.";
  678. startNext();
  679. }
  680. }
  681. #ifdef HAVE_MINIZIP
  682. static voidpf unz_open_file(voidpf opaque, const char* filename, int mode)
  683. {
  684. #ifdef Q_OS_WIN32
  685. return _wfopen(QString::fromUtf8(filename).toStdWString().c_str(), L"rb");
  686. #else
  687. return fopen(filename, "rb");
  688. #endif
  689. }
  690. static uLong unz_read_file(voidpf opaque, voidpf stream, void* buf, uLong size)
  691. {
  692. return fread(buf, 1, size, (FILE *)stream);
  693. }
  694. static uLong unz_write_file(voidpf opaque, voidpf stream, const void* buf, uLong size)
  695. {
  696. return 0;
  697. }
  698. static int unz_close_file(voidpf opaque, voidpf stream)
  699. {
  700. return fclose((FILE *)stream);
  701. }
  702. static int unz_error_file(voidpf opaque, voidpf stream)
  703. {
  704. return ferror((FILE *)stream);
  705. }
  706. static long unz_tell_file(voidpf opaque, voidpf stream)
  707. {
  708. return ftell((FILE *)stream);
  709. }
  710. long unz_seek_file(voidpf opaque, voidpf stream, uLong offset, int origin)
  711. {
  712. int whence = -1;
  713. switch (origin)
  714. {
  715. case ZLIB_FILEFUNC_SEEK_CUR:
  716. whence = SEEK_CUR;
  717. break;
  718. case ZLIB_FILEFUNC_SEEK_END:
  719. whence = SEEK_END;
  720. break;
  721. case ZLIB_FILEFUNC_SEEK_SET:
  722. whence = SEEK_SET;
  723. break;
  724. }
  725. return fseek((FILE *)stream, offset, whence);
  726. }
  727. ///////////////////////////////////////////////////////////////////////////////////////////////////
  728. static bool extractZip(QString zip, QString dest)
  729. {
  730. bool success = false;
  731. zlib_filefunc_def unzfilefuncs = {};
  732. unzfilefuncs.zopen_file = unz_open_file;
  733. unzfilefuncs.zread_file = unz_read_file;
  734. unzfilefuncs.zwrite_file = unz_write_file;
  735. unzfilefuncs.ztell_file = unz_tell_file;
  736. unzfilefuncs.zseek_file = unz_seek_file;
  737. unzfilefuncs.zclose_file = unz_close_file;
  738. unzfilefuncs.zerror_file = unz_error_file;
  739. unzFile file = unzOpen2(zip.toUtf8().data(), &unzfilefuncs);
  740. if (!file)
  741. {
  742. QLOG_ERROR() << "could not open .zip file.";
  743. goto fail;
  744. }
  745. unz_global_info info;
  746. int unzerr;
  747. if ((unzerr = unzGetGlobalInfo(file, &info)) != UNZ_OK)
  748. {
  749. QLOG_ERROR() << "unzGlobalInfo() failed with" << unzerr;
  750. goto fail;
  751. }
  752. if ((unzerr = unzGoToFirstFile(file)) != UNZ_OK)
  753. {
  754. QLOG_ERROR() << "unzGoToFirstFile() failed with" << unzerr;
  755. goto fail;
  756. }
  757. for (ZPOS64_T n = 0; n < info.number_entry; n++)
  758. {
  759. if (n > 0 && (unzerr = unzGoToNextFile(file)) != UNZ_OK)
  760. {
  761. QLOG_ERROR() << "unzGoToNextFile() failed with" << unzerr;
  762. goto fail;
  763. }
  764. char filename[256];
  765. unz_file_info finfo;
  766. if ((unzerr = unzGetCurrentFileInfo(file, &finfo, filename, sizeof(filename), 0, 0, 0, 0)) != UNZ_OK)
  767. {
  768. QLOG_ERROR() << "unzGetCurrentFileInfo() failed with" << unzerr;
  769. goto fail;
  770. }
  771. if ((unzerr = unzOpenCurrentFile(file)) != UNZ_OK)
  772. {
  773. QLOG_ERROR() << "unzOpenCurrentFile() failed with" << unzerr;
  774. goto fail;
  775. }
  776. char *pathpart = strrchr(filename, '/');
  777. if (pathpart)
  778. {
  779. // This part sucks especially: temporarily cut off the string.
  780. *pathpart = '\0';
  781. QDir dir(dest + "/" + filename);
  782. if (!dir.mkpath("."))
  783. {
  784. QLOG_ERROR() << "could not create zip sub directory";
  785. goto fail;
  786. }
  787. *pathpart = '/';
  788. }
  789. // Directory (probably)
  790. if (QString(filename).endsWith("/"))
  791. continue;
  792. QString writepath = dest + "/" + filename;
  793. QSaveFile out(writepath);
  794. if (!out.open(QIODevice::WriteOnly))
  795. {
  796. QLOG_ERROR() << "could not open output file" << filename;
  797. goto fail;
  798. }
  799. while (true)
  800. {
  801. char buf[4096];
  802. int read = unzReadCurrentFile(file, buf, sizeof(buf));
  803. if (read == 0)
  804. break;
  805. if (read < 0)
  806. {
  807. QLOG_ERROR() << "error decompressing zip entry" << filename;
  808. goto fail;
  809. }
  810. if (out.write(buf, read) != read)
  811. {
  812. QLOG_ERROR() << "error writing output file" << filename;
  813. goto fail;
  814. }
  815. }
  816. if (!out.commit())
  817. {
  818. QLOG_ERROR() << "error closing output file" << filename;
  819. goto fail;
  820. }
  821. #ifndef _WIN32
  822. // Set the executable bit.
  823. // We could try setting the full permissions as stored in the file, but why bother.
  824. if (finfo.external_fa & 0x400000)
  825. {
  826. if (!QFile::setPermissions(writepath, QFileDevice::Permissions(0x5145)))
  827. {
  828. QLOG_ERROR() << "could not set output executable bit on extracted file";
  829. goto fail;
  830. }
  831. }
  832. #endif
  833. }
  834. success = true;
  835. fail:
  836. unzClose(file);
  837. return success;
  838. }
  839. #else /* ifdef HAVE_MINIZIP */
  840. ///////////////////////////////////////////////////////////////////////////////////////////////////
  841. static bool extractZip(QString zip, QString dest)
  842. {
  843. return false;
  844. }
  845. #endif
  846. ///////////////////////////////////////////////////////////////////////////////////////////////////
  847. void CodecsFetcher::processCodecDownloadDone(const QVariant& context, const QByteArray& data)
  848. {
  849. QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha1);
  850. if (hash != m_currentHash)
  851. {
  852. QLOG_ERROR() << "Checksum mismatch: got" << hash.toHex() << "expected" << m_currentHash.toHex();
  853. return;
  854. }
  855. if (context == QVariant("eae"))
  856. {
  857. QString dest = eaePrefixPath() + ".zip";
  858. QLOG_INFO() << "Storing EAE as" << dest;
  859. if (!Utils::safelyWriteFile(dest, data))
  860. {
  861. QLOG_ERROR() << "Writing codec file failed.";
  862. return;
  863. }
  864. QDir dir(dest);
  865. dir.removeRecursively();
  866. if (!extractZip(dest, eaePrefixPath()))
  867. {
  868. QLOG_ERROR() << "Could not extract zip.";
  869. dir.removeRecursively();
  870. return;
  871. }
  872. QFile::remove(dest);
  873. }
  874. else
  875. {
  876. CodecDriver codec = context.value<CodecDriver>();
  877. QLOG_INFO() << "Storing codec as" << codec.getPath();
  878. if (!Utils::safelyWriteFile(codec.getPath(), data))
  879. {
  880. QLOG_ERROR() << "Writing codec file failed.";
  881. return;
  882. }
  883. // This causes libmpv and eventually libavcodec to rescan and load new codecs.
  884. Codecs::updateCachedCodecList();
  885. for (const CodecDriver& item : Codecs::getCachedCodecList())
  886. {
  887. if (Codecs::sameCodec(item, codec) && !item.present)
  888. {
  889. QLOG_ERROR() << "Codec could not be loaded after installing it.";
  890. return;
  891. }
  892. }
  893. }
  894. QLOG_INFO() << "Codec download and installation succeeded.";
  895. }
  896. ///////////////////////////////////////////////////////////////////////////////////////////////////
  897. void CodecsFetcher::codecDownloadDone(QVariant userData, bool success, const QByteArray& data)
  898. {
  899. QLOG_INFO() << "Codec request finished.";
  900. if (success)
  901. {
  902. processCodecDownloadDone(userData, data);
  903. }
  904. else
  905. {
  906. QLOG_ERROR() << "Codec download HTTP request failed.";
  907. }
  908. startNext();
  909. }
  910. ///////////////////////////////////////////////////////////////////////////////////////////////////
  911. void CodecsFetcher::startEAE()
  912. {
  913. if (!g_eaeProcess)
  914. {
  915. g_eaeProcess = new QProcess();
  916. g_eaeProcess->setProcessChannelMode(QProcess::ForwardedChannels);
  917. connect(g_eaeProcess, &QProcess::stateChanged,
  918. [](QProcess::ProcessState s)
  919. {
  920. QLOG_INFO() << "EAE process state:" << s;
  921. }
  922. );
  923. connect(g_eaeProcess, &QProcess::errorOccurred,
  924. [](QProcess::ProcessError e)
  925. {
  926. QLOG_INFO() << "EAE process error:" << e;
  927. }
  928. );
  929. connect(g_eaeProcess, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
  930. [](int exitCode, QProcess::ExitStatus exitStatus)
  931. {
  932. QLOG_INFO() << "EAE process finished:" << exitCode << exitStatus;
  933. }
  934. );
  935. }
  936. if (g_eaeProcess->state() == QProcess::NotRunning)
  937. {
  938. if (g_eaeProcess->program().size())
  939. {
  940. int exitCode = g_eaeProcess->exitStatus() == QProcess::NormalExit ? g_eaeProcess->exitCode() : -1;
  941. QLOG_ERROR() << "EAE died with exit code" << exitCode;
  942. }
  943. QLOG_INFO() << "Starting EAE.";
  944. g_eaeProcess->setProgram(eaeBinaryPath());
  945. g_eaeProcess->setWorkingDirectory(g_eaeWatchFolder);
  946. QDir dir(g_eaeWatchFolder);
  947. dir.removeRecursively();
  948. dir.mkpath(".");
  949. static const QStringList watchfolder_names =
  950. {
  951. "Convert to WAV (to 2ch or less)",
  952. "Convert to WAV (to 8ch or less)",
  953. "Convert to Dolby Digital (Low Quality - 384 kbps)",
  954. "Convert to Dolby Digital (High Quality - 640 kbps)",
  955. "Convert to Dolby Digital Plus (High Quality - 384 kbps)",
  956. "Convert to Dolby Digital Plus (Max Quality - 1024 kbps)",
  957. };
  958. for (auto folder : watchfolder_names)
  959. {
  960. if (!dir.mkpath(folder))
  961. {
  962. QLOG_ERROR() << "Could not create watch folder";
  963. }
  964. }
  965. g_eaeProcess->start();
  966. }
  967. }
  968. ///////////////////////////////////////////////////////////////////////////////////////////////////
  969. Downloader::Downloader(QVariant userData, const QUrl& url, const HeaderList& headers, QObject* parent)
  970. : QObject(parent), m_userData(userData), m_lastProgress(-1)
  971. {
  972. QLOG_INFO() << "HTTP request:" << url.toDisplayString();
  973. m_currentStartTime.start();
  974. connect(&m_WebCtrl, &QNetworkAccessManager::finished, this, &Downloader::networkFinished);
  975. QNetworkRequest request(url);
  976. for (int n = 0; n < headers.size(); n++)
  977. request.setRawHeader(headers[n].first.toUtf8(), headers[n].second.toUtf8());
  978. QNetworkReply *reply = m_WebCtrl.get(request);
  979. if (reply)
  980. {
  981. connect(reply, &QNetworkReply::downloadProgress, this, &Downloader::downloadProgress);
  982. }
  983. }
  984. ///////////////////////////////////////////////////////////////////////////////////////////////////
  985. void Downloader::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
  986. {
  987. if (bytesTotal > 0)
  988. {
  989. int progress = (int)(bytesReceived * 100 / bytesTotal);
  990. if (m_lastProgress < 0 || progress > m_lastProgress + 10)
  991. {
  992. m_lastProgress = progress;
  993. QLOG_INFO() << "HTTP request at" << progress << "% (" << bytesReceived << "/" << bytesTotal << ")";
  994. }
  995. }
  996. }
  997. ///////////////////////////////////////////////////////////////////////////////////////////////////
  998. void Downloader::networkFinished(QNetworkReply* pReply)
  999. {
  1000. QLOG_INFO() << "HTTP finished after" << (m_currentStartTime.elapsed() + 500) / 1000
  1001. << "seconds for a request of" << pReply->size() << "bytes.";
  1002. if (pReply->error() == QNetworkReply::NoError)
  1003. {
  1004. emit done(m_userData, true, pReply->readAll());
  1005. }
  1006. else
  1007. {
  1008. QLOG_ERROR() << "HTTP download error:" << pReply->errorString();
  1009. emit done(m_userData, false, QByteArray());
  1010. }
  1011. pReply->deleteLater();
  1012. m_WebCtrl.clearAccessCache(); // make sure the TCP connection is closed
  1013. }
  1014. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1015. static CodecDriver selectBestDecoder(const StreamInfo& stream)
  1016. {
  1017. QList<CodecDriver> codecs = Codecs::findCodecsByFormat(Codecs::getCachedCodecList(), CodecType::Decoder, stream.codec);
  1018. CodecDriver best = {};
  1019. int bestScore = -1;
  1020. for (auto codec : codecs)
  1021. {
  1022. int score = -1;
  1023. if (codec.isSystemCodec())
  1024. {
  1025. // we always want to avoid using non-whitelisted system codecs
  1026. // on the other hand, always prefer whitelisted system codecs
  1027. if ((codec.isWhitelistedSystemAudioCodec() && useSystemAudioDecoders()) ||
  1028. (codec.isWhitelistedSystemVideoCodec() && useSystemVideoDecoders()))
  1029. score = 10;
  1030. if (codec.format == "h264")
  1031. {
  1032. // Avoid using system video decoders for h264 profiles usually not supported.
  1033. if (stream.profile != "" && stream.profile != "main" && stream.profile != "baseline" && stream.profile != "high")
  1034. score = 1;
  1035. }
  1036. if (codec.driver == "h264_mf")
  1037. {
  1038. if (!stream.videoResolution.isEmpty())
  1039. {
  1040. QSize res = stream.videoResolution;
  1041. if (res.width() > g_mediaFoundationH264MaxResolution.width() ||
  1042. res.height() > g_mediaFoundationH264MaxResolution.height())
  1043. score = 1;
  1044. }
  1045. }
  1046. if (codec.driver == "aac_mf")
  1047. {
  1048. // Arbitrary but documented and enforced 6 channel limit by MS.
  1049. if (stream.audioChannels > 6)
  1050. score = 1;
  1051. // Another arbitrary limit.
  1052. if (stream.audioSampleRate > 0 && (stream.audioSampleRate < 8000 || stream.audioSampleRate > 48000))
  1053. score = 1;
  1054. }
  1055. if (codec.getSystemCodecType() == "eae")
  1056. score = HAVE_EAE ? 2 : -1;
  1057. }
  1058. else
  1059. {
  1060. // prefer codecs which do not have to be downloaded over others
  1061. if (codec.present)
  1062. score = 15;
  1063. else
  1064. score = 5;
  1065. }
  1066. if (score > bestScore && score >= 0)
  1067. {
  1068. best = codec;
  1069. bestScore = score;
  1070. }
  1071. }
  1072. return best;
  1073. }
  1074. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1075. QList<CodecDriver> Codecs::determineRequiredCodecs(const PlaybackInfo& info)
  1076. {
  1077. QList<CodecDriver> result;
  1078. bool needAC3Encoder = false;
  1079. QLOG_INFO() << "Using system audio decoders:" << useSystemAudioDecoders();
  1080. QLOG_INFO() << "Using system video decoders:" << useSystemVideoDecoders();
  1081. #if !defined(HAVE_CODEC_MANIFEST)
  1082. QLOG_INFO() << "Not using on-demand codecs.";
  1083. #endif
  1084. for (auto stream : info.streams)
  1085. {
  1086. if (!stream.isVideo && !stream.isAudio)
  1087. continue;
  1088. if (!stream.codec.size())
  1089. {
  1090. QLOG_ERROR() << "unidentified codec";
  1091. continue;
  1092. }
  1093. // We could do this if we'd find a nice way to enable passthrough by default:
  1094. #if 0
  1095. // Can passthrough be used? If so, don't request a codec.
  1096. if (info.audioPassthroughCodecs.contains(stream.codec))
  1097. continue;
  1098. #endif
  1099. // (Would be nice to check audioChannels here to not request the encoder
  1100. // when playing stereo - but unfortunately, the ac3 encoder is loaded first,
  1101. // and only removed when detecting stereo input)
  1102. if (info.enableAC3Transcoding)
  1103. needAC3Encoder = true;
  1104. CodecDriver best = selectBestDecoder(stream);
  1105. if (best.valid())
  1106. {
  1107. result.append(best);
  1108. }
  1109. else
  1110. {
  1111. QLOG_ERROR() << "no decoder for" << stream.codec;
  1112. }
  1113. }
  1114. if (needAC3Encoder)
  1115. {
  1116. QList<CodecDriver> codecs = Codecs::findCodecsByFormat(Codecs::getCachedCodecList(), CodecType::Encoder, "ac3");
  1117. CodecDriver encoder = {};
  1118. for (auto codec : codecs)
  1119. {
  1120. if (codec.present && (!codec.isSystemCodec() || codec.isWhitelistedSystemAudioCodec()))
  1121. {
  1122. encoder = codec;
  1123. break;
  1124. }
  1125. if (codec.external)
  1126. encoder = codec; // fallback
  1127. }
  1128. if (encoder.valid())
  1129. {
  1130. result.append(encoder);
  1131. }
  1132. else
  1133. {
  1134. QLOG_ERROR() << "no AC3 encoder available";
  1135. }
  1136. }
  1137. return result;
  1138. }
  1139. void Codecs::Uninit()
  1140. {
  1141. if (g_eaeProcess)
  1142. {
  1143. delete g_eaeProcess;
  1144. g_eaeProcess = nullptr;
  1145. }
  1146. if (!g_eaeWatchFolder.isEmpty())
  1147. {
  1148. QDir dir(g_eaeWatchFolder);
  1149. dir.removeRecursively();
  1150. }
  1151. }