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