recording.cpp 59.3 KB
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
/* Webcamoid, webcam capture application.
 * Copyright (C) 2016  Gonzalo Exequiel Pedone
 *
 * Webcamoid is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Webcamoid is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Webcamoid. If not, see <http://www.gnu.org/licenses/>.
 *
 * Web-Site: http://webcamoid.github.io/
 */

#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QImage>
#include <QImageWriter>
#include <QMutex>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlProperty>
#include <QQuickItem>
#include <QSettings>
#include <QStandardPaths>
#include <QThread>
#include <QtConcurrent>
#include <QtGlobal>

#ifdef Q_OS_ANDROID
#include <QJniObject>

#define PERMISSION_GRANTED  0
#define PERMISSION_DENIED  -1
#endif

#include <ak.h>
#include <akaudiocaps.h>
#include <akcaps.h>
#include <akcompressedcaps.h>
#include <akfrac.h>
#include <akpacket.h>
#include <akplugininfo.h>
#include <akpluginmanager.h>
#include <akvideocaps.h>
#include <akvideoconverter.h>
#include <akvideopacket.h>
#include <iak/akelement.h>
#include <iak/akaudioencoder.h>
#include <iak/akvideoencoder.h>
#include <iak/akvideomuxer.h>

#include "recording.h"

#define DEFAULT_AUDIO_BITRATE 128000
#define DEFAULT_VIDEO_BITRATE 1500000
#define DEFAULT_VIDEO_GOP 1000
#define DEFAULT_RECORD_AUDIO true

struct CodecInfo
{
    QString pluginID;
    AkCaps::CapsType type;
    AkCodecID codecID;
    QString name;
    QString description;
    int priority;
};

struct FormatInfo
{
    QString pluginID;
    AkVideoMuxer::FormatID formatID;
    QString name;
    QString description;
    QString extension;
    QStringList audioPluginsID;
    QStringList videoPluginsID;
    QString defaultAudioPluginID;
    QString defaultVideoPluginID;
};

struct PluginPriority
{
    QString pluginID;
    int priority;
};

using ObjectPtr = QSharedPointer<QObject>;

class RecordingPrivate
{
    public:
        Recording *self;
        QQmlApplicationEngine *m_engine {nullptr};
        AkAudioCaps m_audioCaps;
        AkVideoCaps m_videoCaps;
        int m_audioBitrate {DEFAULT_AUDIO_BITRATE};
        int m_videoBitrate {DEFAULT_VIDEO_BITRATE};
        int m_videoGOP {1000};
        QVector<CodecInfo> m_supportedCodecs;
        QVector<FormatInfo> m_supportedFormats;
        QString m_defaultFormat;
        AkVideoMuxerPtr m_muxer;
        QString m_muxerPluginID;
        AkAudioEncoderPtr m_audioEncoder;
        QString m_audioPluginID;
        AkVideoEncoderPtr m_videoEncoder;
        QString m_videoPluginID;
        QString m_imageFormat {"png"};
        QString m_imagesDirectory;
        QString m_videoDirectory;
        QString m_lastVideoPreview;
        QString m_lastVideo;
        QString m_lastPhotoPreview;
        AkElementPtr m_thumbnailer {akPluginManager->create<AkElement>("MultimediaSource/MultiSrc")};
        QMutex m_mutex;
        QReadWriteLock m_thumbnailMutex;
        QMutex m_thumbnailerMutex;
        QThreadPool m_threadPool;
        AkVideoPacket m_curPacket;
        QImage m_photo;
        QImage m_thumbnail;
        QMap<QString, QString> m_imageFormats;
        AkElement::ElementState m_state {AkElement::ElementStateNull};
        int m_imageSaveQuality {-1};
        bool m_recordAudio {DEFAULT_RECORD_AUDIO};
        bool m_isRecording {false};
        bool m_pause {false};
        AkVideoConverter m_videoConverter {{AkVideoCaps::Format_argbpack, 0, 0, {}}};

        explicit RecordingPrivate(Recording *self);
        static bool canAccessStorage();
        inline void initSupportedCodecs();
        inline void initSupportedFormats();
        QString defaultCodec(const QString &format, AkCaps::CapsType type) const;
        void printRecordingParameters();
        bool init();
        void uninit();
        static QString normatizePluginID(const QString &pluginID);
        void loadConfigs();
        void loadFormatOptions();
        void loadCodecOptions(AkCaps::CapsType type);
        void updatePreviews();
        void readThumbnail(const QString &videoFile);
        void thumbnailReady();

        // General options
        void saveAudioCaps(const AkAudioCaps &audioCaps);
        void saveVideoCaps(const AkVideoCaps &videoCaps);

        // Video
        void saveVideoDirectory(const QString &videoDirectory);
        void saveVideoFormat(const QString &videoFormat);
        void saveCodec(AkCaps::CapsType type, const QString &codec);
        void saveVideoFormatOptionValue(const QString &option,
                                        const QVariant &value);
        void saveCodecOptionValue(AkCaps::CapsType type,
                                  const QString &option,
                                  const QVariant &value);
        void saveBitrate(AkCaps::CapsType type, int bitrate);
        void saveVideoGOP(int gop);
        void saveRecordAudio(bool recordAudio);

        // Picture
        void saveImagesDirectory(const QString &imagesDirectory);
        void saveImageFormat(const QString &imageFormat);
        void saveImageSaveQuality(int imageSaveQuality);
};

Recording::Recording(QQmlApplicationEngine *engine, QObject *parent):
    QObject(parent)
{
    this->d = new RecordingPrivate(this);
    this->setQmlEngine(engine);

    if (this->d->m_thumbnailer) {
        QObject::connect(this->d->m_thumbnailer.data(),
                         SIGNAL(oStream(AkPacket)),
                         this,
                         SLOT(thumbnailUpdated(AkPacket)),
                         Qt::DirectConnection);
        QObject::connect(this->d->m_thumbnailer.data(),
                         SIGNAL(mediaLoaded(QString)),
                         this,
                         SLOT(mediaLoaded(QString)));
    }

    this->d->loadConfigs();
    this->d->updatePreviews();
}

Recording::~Recording()
{
    this->setState(AkElement::ElementStateNull);
    delete this->d;
}

AkAudioCaps Recording::audioCaps() const
{
    return this->d->m_audioCaps;
}

AkVideoCaps Recording::videoCaps() const
{
    return this->d->m_videoCaps;
}

AkElement::ElementState Recording::state() const
{
    return this->d->m_state;
}

QString Recording::videoDirectory() const
{
    return this->d->m_videoDirectory;
}

QString Recording::videoFormat() const
{
    if (!this->d->m_muxer)
        return {};

    return this->d->m_muxerPluginID + ':' + this->d->m_muxer->muxer();
}

QStringList Recording::videoFormats() const
{
    QStringList formats;

    for (auto &format: this->d->m_supportedFormats)
        formats << format.pluginID + ':' + format.name;

    return formats;
}

QString Recording::formatDescription(const QString &format) const
{
    auto formatParts = format.split(':');

    if (formatParts.size() < 2)
        return {};

    auto pluginID = formatParts[0];
    auto muxerID = formatParts[1];

    auto it = std::find_if(this->d->m_supportedFormats.begin(),
                           this->d->m_supportedFormats.end(),
                           [&pluginID, &muxerID] (const FormatInfo &formatInfo) -> bool {
        return formatInfo.pluginID == pluginID && formatInfo.name == muxerID;
    });

    if (it == this->d->m_supportedFormats.end())
        return {};

    return it->description;
}

QString Recording::codec(AkCaps::CapsType type) const
{
    switch (type) {
    case AkCaps::CapsAudio:
        if (!this->d->m_audioEncoder)
            return {};

        return this->d->m_audioPluginID + ':' + this->d->m_audioEncoder->codec();

    case AkCaps::CapsVideo:
        if (!this->d->m_videoEncoder)
            return {};

        return this->d->m_videoPluginID + ':' + this->d->m_videoEncoder->codec();

    default:
        break;
    }

    return {};
}

QString Recording::defaultCodec(const QString &format,
                                AkCaps::CapsType type) const
{
    auto formatParts = format.split(':');

    if (formatParts.size() < 2)
        return {};

    auto pluginID = formatParts[0];
    auto muxerID = formatParts[1];

    auto it = std::find_if(this->d->m_supportedFormats.begin(),
                           this->d->m_supportedFormats.end(),
                           [&pluginID, &muxerID] (const FormatInfo &formatInfo) -> bool {
        return formatInfo.pluginID == pluginID && formatInfo.name == muxerID;
    });

    if (it == this->d->m_supportedFormats.end())
        return {};

    switch (type) {
    case AkCaps::CapsAudio:
        return it->defaultAudioPluginID;

    case AkCaps::CapsVideo:
        return it->defaultVideoPluginID;

    default:
        break;
    }

    return {};
}

QStringList Recording::supportedCodecs(const QString &format,
                                       AkCaps::CapsType type) const
{
    auto formatParts = format.split(':');

    if (formatParts.size() < 2)
        return {};

    auto pluginID = formatParts[0];
    auto muxerID = formatParts[1];

    auto it = std::find_if(this->d->m_supportedFormats.begin(),
                           this->d->m_supportedFormats.end(),
                           [&pluginID, &muxerID] (const FormatInfo &formatInfo) -> bool {
        return formatInfo.pluginID == pluginID && formatInfo.name == muxerID;
    });

    if (it == this->d->m_supportedFormats.end())
        return {};

    QStringList codecs;

    if (type == AkCaps::CapsAudio || type == AkCaps::CapsAny)
        for (auto &codec: it->audioPluginsID)
            codecs << codec;

    if (type == AkCaps::CapsVideo || type == AkCaps::CapsAny)
        for (auto &codec: it->videoPluginsID)
            codecs << codec;

    return codecs;
}

QString Recording::codecDescription(const QString &codec) const
{
    auto codecParts = codec.split(':');

    if (codecParts.size() < 2)
        return {};

    auto pluginID = codecParts[0];
    auto codecID = codecParts[1];

    auto it = std::find_if(this->d->m_supportedCodecs.begin(),
                           this->d->m_supportedCodecs.end(),
                           [&pluginID, &codecID] (const CodecInfo &codecInfo) -> bool {
        return codecInfo.pluginID == pluginID && codecInfo.name == codecID;
    });

    if (it == this->d->m_supportedCodecs.end())
        return {};

    return it->description;
}

AkPropertyOptions Recording::videoFormatOptions() const
{
    if (!this->d->m_muxer)
        return {};

    return this->d->m_muxer->options();
}

QVariant Recording::videoFormatOptionValue(const QString &option) const
{
    if (!this->d->m_muxer)
        return {};

    return this->d->m_muxer->optionValue(option);
}

AkPropertyOptions Recording::codecOptions(AkCaps::CapsType type) const
{
    switch (type) {
    case AkCaps::CapsAudio:
        if (!this->d->m_audioEncoder)
            return {};

        return this->d->m_audioEncoder->options();

    case AkCaps::CapsVideo:
        if (!this->d->m_videoEncoder)
            return {};

        return this->d->m_videoEncoder->options();

    default:
        break;
    }

    return {};
}

QVariant Recording::codecOptionValue(AkCaps::CapsType type,
                                     const QString &option) const
{
    switch (type) {
    case AkCaps::CapsAudio:
        if (!this->d->m_audioEncoder)
            return {};

        return this->d->m_audioEncoder->optionValue(option);

    case AkCaps::CapsVideo:
        if (!this->d->m_videoEncoder)
            return {};

        return this->d->m_videoEncoder->optionValue(option);

    default:
        break;
    }

    return {};
}

int Recording::bitrate(AkCaps::CapsType type) const
{
    switch (type) {
    case AkCaps::CapsAudio:
        return this->d->m_audioBitrate;

    case AkCaps::CapsVideo:
        return this->d->m_videoBitrate;

    default:
        break;
    }

    return {};
}

int Recording::defaultBitrate(AkCaps::CapsType type) const
{
    switch (type) {
    case AkCaps::CapsAudio:
        return DEFAULT_AUDIO_BITRATE;

    case AkCaps::CapsVideo:
        return DEFAULT_VIDEO_BITRATE;

    default:
        break;
    }

    return 0;
}

int Recording::videoGOP() const
{
    return this->d->m_videoGOP;
}

int Recording::defaultVideoGOP() const
{
    return DEFAULT_VIDEO_GOP;
}

bool Recording::recordAudio() const
{
    return this->d->m_recordAudio;
}

QString Recording::lastVideoPreview() const
{
    return this->d->m_lastVideoPreview;
}

QString Recording::lastVideo() const
{
    return this->d->m_lastVideo;
}

QString Recording::imagesDirectory() const
{
    return this->d->m_imagesDirectory;
}

QStringList Recording::availableImageFormats() const
{
    return this->d->m_imageFormats.keys();
}

QString Recording::imageFormat() const
{
    return this->d->m_imageFormat;
}

QString Recording::imageFormatDescription(const QString &format) const
{
    return this->d->m_imageFormats.value(format);
}

QString Recording::lastPhotoPreview() const
{
    return this->d->m_lastPhotoPreview;
}

int Recording::imageSaveQuality() const
{
    return this->d->m_imageSaveQuality;
}

void Recording::setAudioCaps(const AkAudioCaps &audioCaps)
{
    if (this->d->m_audioCaps == audioCaps)
        return;

    this->d->m_audioCaps = audioCaps;
    emit this->audioCapsChanged(audioCaps);
    this->d->saveAudioCaps(audioCaps);
}

void Recording::setVideoCaps(const AkVideoCaps &videoCaps)
{
    if (this->d->m_videoCaps == videoCaps)
        return;

    this->d->m_videoCaps = videoCaps;
    emit this->videoCapsChanged(videoCaps);
    this->d->saveVideoCaps(videoCaps);
}

bool Recording::setState(AkElement::ElementState state)
{
    switch (this->d->m_state) {
    case AkElement::ElementStateNull: {
        switch (state) {
        case AkElement::ElementStatePaused:
            this->d->m_pause = true;
            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStatePlaying:
            if (!this->d->init())
                return false;

            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStateNull:
            break;
        }

        break;
    }
    case AkElement::ElementStatePaused: {
        switch (state) {
        case AkElement::ElementStateNull:
            this->d->uninit();
            this->d->m_pause = false;
            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStatePlaying:
            this->d->m_pause = false;
            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStatePaused:
            break;
        }

        break;
    }
    case AkElement::ElementStatePlaying: {
        switch (state) {
        case AkElement::ElementStateNull:
            this->d->uninit();
            this->d->m_pause = false;
            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStatePaused:
            this->d->m_pause = true;
            this->d->m_state = state;
            emit this->stateChanged(state);

            return true;
        case AkElement::ElementStatePlaying:
            break;
        }

        break;
    }
    }

    return false;
}

void Recording::setVideoDirectory(const QString &videoDirectory)
{
    if (this->d->m_videoDirectory == videoDirectory)
        return;

    this->d->m_videoDirectory = videoDirectory;
    emit this->videoDirectoryChanged(this->d->m_videoDirectory);
    this->d->saveVideoDirectory(this->d->m_videoDirectory);
}

void Recording::setVideoFormat(const QString &videoFormat)
{
    auto curFormat =
            this->d->m_muxer?
                this->d->m_muxerPluginID + ':' + this->d->m_muxer->muxer():
                QString();

    if (videoFormat == curFormat)
        return;

    auto formatParts = videoFormat.split(':');
    auto formatPluginID = formatParts.value(0);
    auto formatName = formatParts.value(1);

    auto muxer = akPluginManager->create<AkVideoMuxer>(formatPluginID);

    if (muxer)
        muxer->setMuxer(formatName);
    else
        qCritical() << "Failed to create the muxer:" << formatPluginID;

    this->d->m_muxer = muxer;
    this->d->m_muxerPluginID = formatPluginID;
    emit this->videoFormatChanged(videoFormat);
    this->d->saveVideoFormat(videoFormat);
    this->d->loadFormatOptions();
}

void Recording::setCodec(AkCaps::CapsType type, const QString &codec)
{
    switch (type) {
    case AkCaps::CapsAudio: {
        auto curCodec =
                this->d->m_audioEncoder?
                    this->d->m_audioPluginID + ':' + this->d->m_audioEncoder->codec():
                    QString();

        if (codec == curCodec)
            return;

        auto codecParts = codec.split(':');
        auto codecPluginID = codecParts.value(0);
        auto codecName = codecParts.value(1);

        auto encoder = akPluginManager->create<AkAudioEncoder>(codecPluginID);

        if (encoder)
            encoder->setCodec(codecName);
        else
            qDebug() << "Failed to create the muxer:" << codecPluginID;

        this->d->m_audioEncoder = encoder;
        this->d->m_audioPluginID = codecPluginID;
        emit this->codecChanged(type, codec);
        this->d->saveCodec(type, codec);
        this->d->loadCodecOptions(AkCaps::CapsAudio);

        break;
    }

    case AkCaps::CapsVideo: {
        auto curCodec =
                this->d->m_videoEncoder?
                    this->d->m_videoPluginID + ':' + this->d->m_videoEncoder->codec():
                    QString();

        if (codec == curCodec)
            return;

        auto codecParts = codec.split(':');
        auto codecPluginID = codecParts.value(0);
        auto codecName = codecParts.value(1);

        auto encoder = akPluginManager->create<AkVideoEncoder>(codecPluginID);

        if (encoder)
            encoder->setCodec(codecName);
        else
            qDebug() << "Failed to create the muxer:" << codecPluginID;

        this->d->m_videoEncoder = encoder;
        this->d->m_videoPluginID = codecPluginID;
        emit this->codecChanged(type, codec);
        this->d->saveCodec(type, codec);
        this->d->loadCodecOptions(AkCaps::CapsVideo);

        break;
    }

    default:
        break;
    }
}

void Recording::setVideoFormatOptionValue(const QString &option,
                                          const QVariant &value)
{
    if (!this->d->m_muxer)
        return;

    if (this->d->m_muxer->optionValue(option) == value)
        return;

    this->d->m_muxer->setOptionValue(option, value);
    emit this->videoFormatOptionValueChanged(option, value);
    this->d->saveVideoFormatOptionValue(option, value);
}

void Recording::setCodecOptionValue(AkCaps::CapsType type,
                                    const QString &option,
                                    const QVariant &value)
{
    switch (type) {
    case AkCaps::CapsAudio:
        if (!this->d->m_audioEncoder)
            return;

        if (this->d->m_audioEncoder->optionValue(option) == value)
            return;

        this->d->m_audioEncoder->setOptionValue(option, value);
        emit this->codecOptionValueChanged(type, option, value);
        this->d->saveCodecOptionValue(type, option, value);

        break;

    case AkCaps::CapsVideo:
        if (!this->d->m_videoEncoder)
            return;

        if (this->d->m_videoEncoder->optionValue(option) == value)
            return;

        this->d->m_videoEncoder->setOptionValue(option, value);
        emit this->codecOptionValueChanged(type, option, value);
        this->d->saveCodecOptionValue(type, option, value);

        break;

    default:
        break;
    }
}

void Recording::setBitrate(AkCaps::CapsType type, int bitrate)
{
    switch (type) {
    case AkCaps::CapsAudio:
        if (this->d->m_audioBitrate == bitrate)
            return;

        this->d->m_audioBitrate = bitrate;
        emit this->bitrateChanged(type, bitrate);
        this->d->saveBitrate(type, bitrate);

        break;

    case AkCaps::CapsVideo:
        if (!this->d->m_videoEncoder)
            return;

        if (this->d->m_videoBitrate == bitrate)
            return;

        this->d->m_videoBitrate = bitrate;
        emit this->bitrateChanged(type, bitrate);
        this->d->saveBitrate(type, bitrate);

        break;

    default:
        break;
    }
}

void Recording::setVideoGOP(int gop)
{
    if (this->d->m_videoGOP == gop)
        return;

    this->d->m_videoGOP = gop;
    emit this->videoGOPChanged(gop);
    this->d->saveVideoGOP(gop);
}

void Recording::setRecordAudio(bool recordAudio)
{
    if (this->d->m_recordAudio == recordAudio)
        return;

    this->d->m_recordAudio = recordAudio;
    emit this->recordAudioChanged(recordAudio);
    this->d->saveRecordAudio(recordAudio);
}

void Recording::setImagesDirectory(const QString &imagesDirectory)
{
    if (this->d->m_imagesDirectory == imagesDirectory)
        return;

    this->d->m_imagesDirectory = imagesDirectory;
    emit this->imagesDirectoryChanged(this->d->m_imagesDirectory);
    this->d->saveImagesDirectory(this->d->m_imagesDirectory);
}

void Recording::setImageFormat(const QString &imageFormat)
{
    if (this->d->m_imageFormat == imageFormat)
        return;

    this->d->m_imageFormat = imageFormat;
    emit this->imageFormatChanged(this->d->m_imageFormat);
    this->d->saveImageFormat(this->d->m_imageFormat);
}

void Recording::setImageSaveQuality(int imageSaveQuality)
{
    if (this->d->m_imageSaveQuality == imageSaveQuality)
        return;

    this->d->m_imageSaveQuality = imageSaveQuality;
    emit this->imageSaveQualityChanged(this->d->m_imageSaveQuality);
    this->d->saveImageSaveQuality(this->d->m_imageSaveQuality);
}

void Recording::resetAudioCaps()
{
    this->setAudioCaps({});
}

void Recording::resetVideoCaps()
{
    this->setVideoCaps({});
}

void Recording::resetState()
{
    this->setState(AkElement::ElementStateNull);
}

void Recording::resetVideoDirectory()
{
    auto moviesPaths =
            QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
    auto dir = QDir(moviesPaths.first()).filePath(qApp->applicationName());
    this->setVideoDirectory(dir);
}

void Recording::resetVideoFormat()
{
    this->setVideoFormat(this->d->m_defaultFormat);
}

void Recording::resetCodec(AkCaps::CapsType type)
{
    this->setCodec(type, this->d->defaultCodec(this->videoFormat(), type));
}

void Recording::resetVideoFormatOptionValue(const QString &option)
{
    this->setVideoFormatOptionValue(option, this->videoFormatOptionValue(option));
}

void Recording::resetCodecOptionValue(AkCaps::CapsType type,
                                      const QString &option)
{
    this->setCodecOptionValue(type, option, this->codecOptionValue(type,
                                                                   option));
}

void Recording::resetVideoFormatOptions()
{
    for (auto &option: this->videoFormatOptions())
        this->resetVideoFormatOptionValue(option.name());
}

void Recording::resetCodecOptions(AkCaps::CapsType type)
{
    for (auto &option: this->codecOptions(type))
        this->resetCodecOptionValue(type, option.name());
}

void Recording::resetBitrate(AkCaps::CapsType type)
{
    int bitrate = type == AkCaps::CapsVideo?
                      DEFAULT_VIDEO_BITRATE:
                      DEFAULT_AUDIO_BITRATE;

    this->setBitrate(type, bitrate);
}

void Recording::resetVideoGOP()
{
    this->setVideoGOP(DEFAULT_VIDEO_GOP);
}

void Recording::resetRecordAudio()
{
    this->setRecordAudio(DEFAULT_RECORD_AUDIO);
}

void Recording::resetImagesDirectory()
{
    auto picturesPaths =
            QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
    auto dir = QDir(picturesPaths.first()).filePath(qApp->applicationName());
    this->setImagesDirectory(dir);
}

void Recording::resetImageFormat()
{
    this->setImageFormat("png");
}

void Recording::resetImageSaveQuality()
{
    this->setImageSaveQuality(-1);
}

void Recording::takePhoto()
{
    this->d->m_mutex.lock();

    this->d->m_videoConverter.begin();
    auto src = this->d->m_videoConverter.convert(this->d->m_curPacket);
    this->d->m_videoConverter.end();

    this->d->m_photo = QImage(src.caps().width(),
                              src.caps().height(),
                              QImage::Format_ARGB32);
    auto lineSize =
            qMin<size_t>(src.lineSize(0), this->d->m_photo.bytesPerLine());

    for (int y = 0; y < src.caps().height(); y++) {
        auto srcLine = src.constLine(0, y);
        auto dstLine = this->d->m_photo.scanLine(y);
        memcpy(dstLine, srcLine, lineSize);
    }

    this->d->m_mutex.unlock();
}

void Recording::savePhoto(const QString &fileName)
{
    if (!this->d->canAccessStorage())
        return;

    QString path = fileName;

#ifdef Q_OS_WIN32
    path.replace("file:///", "");
#else
    path.replace("file://", "");
#endif

    if (path.isEmpty())
        return;

    if (QDir().mkpath(this->d->m_imagesDirectory)) {
        this->d->m_photo.save(path, nullptr, this->d->m_imageSaveQuality);
        this->d->m_lastPhotoPreview = path;
        emit this->lastPhotoPreviewChanged(path);
    }
}

bool Recording::copyToClipboard()
{
    if (!this->d->m_photo.isNull()) {
        QApplication::clipboard()->setImage(this->d->m_photo, QClipboard::Clipboard);
        return true;
    }
    return false;
}

AkPacket Recording::iStream(const AkPacket &packet)
{
    if (this->d->m_isRecording) {
        switch (packet.type()) {
        case AkPacket::PacketAudio:
            if (this->d->m_audioEncoder)
                this->d->m_audioEncoder->iStream(packet);

            break;

        case AkPacket::PacketVideo:
            this->d->m_mutex.lock();
            this->d->m_curPacket = packet;
            this->d->m_mutex.unlock();

            if (this->d->m_videoEncoder)
                this->d->m_videoEncoder->iStream(packet);

            break;

        default:
            break;
        }
    }

    return {};
}

void Recording::setQmlEngine(QQmlApplicationEngine *engine)
{
    if (this->d->m_engine == engine)
        return;

    this->d->m_engine = engine;

    if (engine)
        engine->rootContext()->setContextProperty("recording", this);
}

void Recording::thumbnailUpdated(const AkPacket &packet)
{
    this->d->m_videoConverter.begin();
    auto src = this->d->m_videoConverter.convert(packet);
    this->d->m_videoConverter.end();

    if (!src)
        return;

    QImage thumbnail(src.caps().width(),
                     src.caps().height(),
                     QImage::Format_ARGB32);
    auto lineSize =
            qMin<size_t>(src.lineSize(0), thumbnail.bytesPerLine());

    for (int y = 0; y < src.caps().height(); y++) {
        auto srcLine = src.constLine(0, y);
        auto dstLine = thumbnail.scanLine(y);
        memcpy(dstLine, srcLine, lineSize);
    }

    this->d->m_thumbnailMutex.lockForWrite();
    this->d->m_thumbnail = thumbnail;
    this->d->m_thumbnailMutex.unlock();
    auto result =
            QtConcurrent::run(&this->d->m_threadPool,
                              &RecordingPrivate::thumbnailReady,
                              this->d);
    Q_UNUSED(result)
}

void Recording::mediaLoaded(const QString &media)
{
    int videoStream = -1;
    QMetaObject::invokeMethod(this->d->m_thumbnailer.data(),
                              "defaultStream",
                              Q_RETURN_ARG(int, videoStream),
                              Q_ARG(AkCaps::CapsType, AkCaps::CapsVideo));

    if (videoStream < 0)
        return;

    QList<int> streams {videoStream};
    QMetaObject::invokeMethod(this->d->m_thumbnailer.data(),
                              "setStreams",
                              Q_ARG(QList<int>, streams));

    this->d->m_thumbnailMutex.lockForWrite();
    this->d->m_thumbnail = {};
    this->d->m_thumbnailMutex.unlock();
    this->d->m_thumbnailer->setState(AkElement::ElementStatePaused);
    auto duration = this->d->m_thumbnailer->property("durationMSecs").value<qint64>();

    if (duration < 1)
        return;

    QMetaObject::invokeMethod(this->d->m_thumbnailer.data(),
                              "seek",
                              Q_ARG(qint64, qint64(0.1 * duration)));
    this->d->m_thumbnailerMutex.lock();
    this->d->m_thumbnailer->setState(AkElement::ElementStatePlaying);
    this->d->m_thumbnailerMutex.unlock();
}

RecordingPrivate::RecordingPrivate(Recording *self):
    self(self)
{
    static const QMap<QString, QString> formatsDescription {
        {"bmp" , "Windows Bitmap (BMP)"                       },
        {"cur" , "Microsoft Windows Cursor (CUR)"             },
        {"icns", "Apple Icon Image (ICNS)"                    },
        {"ico" , "Microsoft Windows Icon (ICO)"               },
        {"jp2" , "Joint Photographic Experts Group 2000 (JP2)"},
        {"jpg" , "Joint Photographic Experts Group (JPEG)"    },
        {"pbm" , "Portable Bitmap (PBM)"                      },
        {"pgm" , "Portable Graymap (PGM)"                     },
        {"png" , "Portable Network Graphics (PNG)"            },
        {"ppm" , "Portable Pixmap (PPM)"                      },
        {"tiff", "Tagged Image File Format (TIFF)"            },
        {"wbmp", "Wireless Bitmap (WBMP)"                     },
        {"webp", "WebP (WEBP)"                                },
        {"xbm" , "X11 Bitmap (XBM)"                           },
        {"xpm" , "X11 Pixmap (XPM)"                           },
    };

    static const QMap<QString, QString> recordingFormatsMapping {
        {"jpeg", "jpg" },
        {"tif" , "tiff"},
    };

    for (auto &format: QImageWriter::supportedImageFormats()) {
        QString fmt = format;

        if (recordingFormatsMapping.contains(fmt))
            fmt = recordingFormatsMapping[fmt];

        if (this->m_imageFormats.contains(fmt))
            continue;

        if (formatsDescription.contains(fmt))
            this->m_imageFormats[fmt] = formatsDescription[fmt];
        else
            this->m_imageFormats[fmt] = fmt.toUpper();
    }

    this->initSupportedCodecs();
    this->initSupportedFormats();
}

bool RecordingPrivate::canAccessStorage()
{
#ifdef Q_OS_ANDROID
    static bool done = false;
    static bool result = false;

    if (done)
        return result;

    QJniObject context =
        qApp->nativeInterface<QNativeInterface::QAndroidApplication>()->context();

    if (!context.isValid()) {
        done = false;

        return result;
    }

    QStringList permissions {
        "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    QStringList neededPermissions;

    for (auto &permission: permissions) {
        auto permissionStr = QJniObject::fromString(permission);
        auto result =
            context.callMethod<jint>("checkSelfPermission",
                                     "(Ljava/lang/String;)I",
                                     permissionStr.object());

        if (result != PERMISSION_GRANTED)
            neededPermissions << permission;
    }

    if (!neededPermissions.isEmpty()) {
        QJniEnvironment jniEnv;
        jobjectArray permissionsArray =
            jniEnv->NewObjectArray(permissions.size(),
                                   jniEnv->FindClass("java/lang/String"),
                                   nullptr);
        int i = 0;

        for (auto &permission: permissions) {
            auto permissionObject = QJniObject::fromString(permission);
            jniEnv->SetObjectArrayElement(permissionsArray,
                                          i,
                                          permissionObject.object());
            i++;
        }

        context.callMethod<void>("requestPermissions",
                                 "([Ljava/lang/String;I)V",
                                 permissionsArray,
                                 jint(Ak::id()));
        QElapsedTimer timer;
        timer.start();
        static const int timeout = 5000;

        while (timer.elapsed() < timeout) {
            bool permissionsGranted = true;

            for (auto &permission: permissions) {
                auto permissionStr = QJniObject::fromString(permission);
                auto result =
                    context.callMethod<jint>("checkSelfPermission",
                                             "(Ljava/lang/String;)I",
                                             permissionStr.object());

                if (result != PERMISSION_GRANTED) {
                    permissionsGranted = false;

                    break;
                }
            }

            if (permissionsGranted)
                break;

            auto eventDispatcher = QThread::currentThread()->eventDispatcher();

            if (eventDispatcher)
                eventDispatcher->processEvents(QEventLoop::AllEvents);
        }
    }

    done = true;
    result = true;
#endif

    return true;
}

void RecordingPrivate::initSupportedCodecs()
{
    this->m_supportedCodecs.clear();

    auto audioEncoders =
            akPluginManager->listPlugins("^AudioEncoder([/]([0-9a-zA-Z_])+)+$",
                                         {},
                                         AkPluginManager::FilterEnabled
                                         | AkPluginManager::FilterRegexp);

    for (auto &encoder: audioEncoders) {
        auto codecPlugin = akPluginManager->create<AkAudioEncoder>(encoder);
        auto codecInfo = akPluginManager->pluginInfo(encoder);

        for (auto &codec: codecPlugin->codecs())
            this->m_supportedCodecs << CodecInfo {encoder,
                                                  AkCaps::CapsAudio,
                                                  codecPlugin->codecID(codec),
                                                  codec,
                                                  codecPlugin->codecDescription(codec),
                                                  codecInfo.priority()};
    }

    auto videoEncoders =
            akPluginManager->listPlugins("^VideoEncoder([/]([0-9a-zA-Z_])+)+$",
                                         {},
                                         AkPluginManager::FilterEnabled
                                         | AkPluginManager::FilterRegexp);

    for (auto &encoder: videoEncoders) {
        auto codecPlugin = akPluginManager->create<AkVideoEncoder>(encoder);
        auto codecInfo = akPluginManager->pluginInfo(encoder);

        for (auto &codec: codecPlugin->codecs())
            this->m_supportedCodecs << CodecInfo {encoder,
                                                  AkCaps::CapsVideo,
                                                  codecPlugin->codecID(codec),
                                                  codec,
                                                  codecPlugin->codecDescription(codec),
                                                  codecInfo.priority()};
    }

    std::sort(this->m_supportedCodecs.begin(),
              this->m_supportedCodecs.end(),
              [] (const CodecInfo &ci1, const CodecInfo &ci2) {
        return ci1.description < ci2.description;
    });
}

void RecordingPrivate::initSupportedFormats()
{
    this->m_supportedFormats.clear();

    auto muxerPlugins =
            akPluginManager->listPlugins("^VideoMuxer([/]([0-9a-zA-Z_])+)+$",
                                         {},
                                         AkPluginManager::FilterEnabled
                                         | AkPluginManager::FilterRegexp);
    QVector<PluginPriority> formatsPriority;

    for (auto &muxerPluginId: muxerPlugins) {
        auto muxerInfo = akPluginManager->pluginInfo(muxerPluginId);
        auto muxerPlugin = akPluginManager->create<AkVideoMuxer>(muxerPluginId);

        for (auto &muxer: muxerPlugin->muxers()) {
            QVector<PluginPriority> codecsPriority;
            QVector<QString> audioPluginsID;
            auto supportedAudioCodecs =
                    muxerPlugin->supportedCodecs(muxer,
                                                 AkCompressedCaps::CapsType_Audio);
            auto defaultAudioCodec =
                    muxerPlugin->defaultCodec(muxer,
                                              AkCompressedCaps::CapsType_Audio);

            for (auto &codec: this->m_supportedCodecs)
                if (supportedAudioCodecs.contains(codec.codecID)
                    && codec.type == AkCaps::CapsAudio) {
                    auto id = codec.pluginID + ':' + codec.name;
                    audioPluginsID << id;

                    if (codec.codecID == defaultAudioCodec)
                        codecsPriority << PluginPriority {id, codec.priority};
                }

            if (audioPluginsID.isEmpty())
                continue;

            std::sort(codecsPriority.begin(),
                      codecsPriority.end(),
                      [] (const PluginPriority &plugin1,
                          const PluginPriority &pluhgin2) -> bool {
                return plugin1.priority > pluhgin2.priority;
            });
            QString defaultAudioPluginID;

            if (!codecsPriority.isEmpty())
                defaultAudioPluginID = codecsPriority[0].pluginID;

            codecsPriority.clear();
            QVector<QString> videoPluginsID;
            auto supportedVideoCodecs =
                    muxerPlugin->supportedCodecs(muxer,
                                                 AkCompressedCaps::CapsType_Video);
            auto defaultVideoCodec =
                    muxerPlugin->defaultCodec(muxer,
                                              AkCompressedCaps::CapsType_Video);

            for (auto &codec: this->m_supportedCodecs)
                if (supportedVideoCodecs.contains(codec.codecID)
                    && codec.type == AkCaps::CapsVideo) {
                    auto id = codec.pluginID + ':' + codec.name;
                    videoPluginsID << id;

                    if (codec.codecID == defaultVideoCodec)
                        codecsPriority << PluginPriority {id, codec.priority};
                }

            if (videoPluginsID.isEmpty())
                continue;

            std::sort(codecsPriority.begin(),
                      codecsPriority.end(),
                      [] (const PluginPriority &plugin1,
                          const PluginPriority &plugin2) -> bool {
                return plugin1.priority > plugin2.priority;
            });
            auto defaultVideoPluginID = codecsPriority.first().pluginID;

            this->m_supportedFormats << FormatInfo {
                muxerPluginId,
                muxerPlugin->formatID(muxer),
                muxer,
                muxerPlugin->description(muxer),
                muxerPlugin->extension(muxer),
                audioPluginsID,
                videoPluginsID,
                defaultAudioPluginID,
                defaultVideoPluginID
            };

            formatsPriority << PluginPriority {muxerPluginId + ':' + muxer,
                                               muxerInfo.priority()};
        }
    }

    std::sort(this->m_supportedFormats.begin(),
              this->m_supportedFormats.end(),
              [] (const FormatInfo &fi1, const FormatInfo &fi2) {
        return fi1.description < fi2.description;
    });

    if (formatsPriority.isEmpty()) {
        this->m_defaultFormat = {};

        return;
    }

    std::sort(formatsPriority.begin(),
              formatsPriority.end(),
              [] (const PluginPriority &plugin1,
                  const PluginPriority &plugin2) -> bool {
        return plugin1.priority > plugin2.priority;
    });
    this->m_defaultFormat = formatsPriority.first().pluginID;
}

QString RecordingPrivate::defaultCodec(const QString &format, AkCaps::CapsType type) const
{
    auto formatParts = format.split(':');

    if (formatParts.size() < 2)
        return {};

    auto pluginID = formatParts[0];
    auto muxerID = formatParts[1];

    auto it = std::find_if(this->m_supportedFormats.begin(),
                           this->m_supportedFormats.end(),
                           [&pluginID, &muxerID] (const FormatInfo &formatInfo) -> bool {
        return formatInfo.pluginID == pluginID && formatInfo.name == muxerID;
    });

    if (it == this->m_supportedFormats.end())
        return {};

    switch (type) {
    case AkCaps::CapsAudio:
        return it->defaultAudioPluginID;

    case AkCaps::CapsVideo:
        return it->defaultVideoPluginID;

    default:
        break;
    }

    return {};
}

void RecordingPrivate::printRecordingParameters()
{
    qInfo() << "Recording parameters:";
    qInfo() << "    Format:" << self->videoFormat();

    if (this->m_recordAudio) {
        qInfo() << "    Audio:";
        qInfo() << "        sample format:" << this->m_audioCaps.format();
        qInfo() << "        channels:" << this->m_audioCaps.channels();
        qInfo() << "        layout:" << this->m_audioCaps.layout();
        qInfo() << "        sample rate:" << this->m_audioCaps.rate();
        qInfo() << "        codec:" << self->codec(AkCaps::CapsAudio);
        qInfo() << "        bitrate:" << this->m_audioBitrate;
    }

    qInfo() << "    Video:";
    qInfo() << "        pixel format:" << this->m_videoCaps.format();
    qInfo() << "        width:" << this->m_videoCaps.width();
    qInfo() << "        height:" << this->m_videoCaps.height();
    qInfo() << "        frame rate:" << this->m_videoCaps.fps().toString();
    qInfo() << "        codec:" << self->codec(AkCaps::CapsVideo);
    qInfo() << "        bitrate:" << this->m_videoBitrate;
}

bool RecordingPrivate::init()
{
    if (!QDir().mkpath(this->m_videoDirectory))
        return false;

    if (!this->m_muxer) {
        qDebug() << "Muxer not set";

        return false;
    }

    if (!this->m_videoEncoder) {
        qDebug() << "Video codec not set";

        return false;
    }

    auto currentTime =
            QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss");
    auto location =
            QObject::tr("%1/Video %2.%3")
                .arg(this->m_videoDirectory,
                     currentTime,
                     this->m_muxer->extension(this->m_muxer->muxer()));
    this->m_muxer->setLocation(location);

    this->m_videoEncoder->setInputCaps(this->m_videoCaps);
    this->m_videoEncoder->setBitrate(this->m_videoBitrate);
    this->m_videoEncoder->setGop(this->m_videoGOP);
    this->m_videoEncoder->setFillGaps(!this->m_muxer->gapsAllowed(AkCompressedCaps::CapsType_Video));
    this->m_muxer->setStreamCaps(this->m_videoEncoder->outputCaps());
    this->m_muxer->setStreamBitrate(AkCompressedCaps::CapsType_Video,
                                    this->m_videoEncoder->bitrate());
    this->m_videoEncoder->link(this->m_muxer, Qt::DirectConnection);

    if (this->m_audioEncoder) {
        this->m_audioEncoder->setInputCaps(this->m_audioCaps);
        this->m_audioEncoder->setBitrate(this->m_audioBitrate);
        this->m_audioEncoder->setFillGaps(!this->m_muxer->gapsAllowed(AkCompressedCaps::CapsType_Audio));
        this->m_muxer->setStreamCaps(this->m_audioEncoder->outputCaps());
        this->m_muxer->setStreamBitrate(AkCompressedCaps::CapsType_Audio,
                                        this->m_audioEncoder->bitrate());
        this->m_audioEncoder->link(this->m_muxer, Qt::DirectConnection);

        this->m_audioEncoder->setState(AkElement::ElementStatePaused);
        this->m_muxer->setStreamHeaders(AkCompressedCaps::CapsType_Audio,
                                        this->m_audioEncoder->headers());
    }

    this->m_videoEncoder->setState(AkElement::ElementStatePaused);
    this->m_muxer->setStreamHeaders(AkCompressedCaps::CapsType_Video,
                                    this->m_videoEncoder->headers());
    this->m_muxer->setState(AkElement::ElementStatePlaying);

    if (this->m_audioEncoder)
        this->m_audioEncoder->setState(AkElement::ElementStatePlaying);

    this->m_videoEncoder->setState(AkElement::ElementStatePlaying);
    this->printRecordingParameters();
    this->m_isRecording = true;

    return true;
}

void RecordingPrivate::uninit()
{
    if (!this->m_isRecording)
        return;

    qInfo() << "Stopping recording";
    this->m_isRecording = false;
    qint64 videoDuration = 0;
    qreal videoTime = 0.0;

    if (this->m_videoEncoder) {
        this->m_videoEncoder->setState(AkElement::ElementStateNull);
        videoDuration = this->m_videoEncoder->encodedTimePts();
        auto fps = this->m_videoEncoder->outputCaps().rawCaps().fps();
        videoTime = videoDuration / fps.value();
    }

    qint64 audioDuration = 0;
    qreal audioTime = 0.0;

    if (this->m_audioEncoder) {
        this->m_audioEncoder->setState(AkElement::ElementStateNull);
        audioDuration = this->m_audioEncoder->encodedTimePts();
        audioTime = qreal(audioDuration)
                    / this->m_audioEncoder->outputCaps().rawCaps().rate();
    }

    if (this->m_muxer) {
        if (audioDuration > 0)
            this->m_muxer->setStreamDuration(AkCompressedCaps::CapsType_Audio,
                                             audioDuration);

        if (videoDuration > 0)
            this->m_muxer->setStreamDuration(AkCompressedCaps::CapsType_Video,
                                             videoDuration);

        this->m_muxer->setState(AkElement::ElementStateNull);
    }

    auto duration = qMax(audioTime, videoTime);
    qInfo() << QString("Video duration: %1 (a: %2, v: %3)")
               .arg(duration)
               .arg(audioTime)
               .arg(videoTime)
               .toStdString().c_str();
    qInfo() << "Recording stopped";

    auto location = this->m_muxer->location();

    if (this->m_lastVideo != location) {
        this->readThumbnail(location);
        this->m_lastVideo = location;
        emit self->lastVideoChanged(location);
    }
}

QString RecordingPrivate::normatizePluginID(const QString &pluginID)
{
    static char const *videoRecordingValidPluginIDChars =
            "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
    QString normalized;

    for (auto &c: pluginID) {
        auto count =
                std::count(videoRecordingValidPluginIDChars,
                           videoRecordingValidPluginIDChars
                           + strnlen(videoRecordingValidPluginIDChars, 64),
                           c);
        normalized += count > 0? c: '_';
    }

    return normalized;
}

void RecordingPrivate::loadConfigs()
{
    QSettings config;
    config.beginGroup("RecordConfigs");

    auto picturesPaths =
            QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
    QString defaultImagesDirectory =
        picturesPaths.isEmpty()?
            "":
            QDir(picturesPaths.first()).filePath(qApp->applicationName());
    auto moviesPaths =
            QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
    QString defaultVideoDirectory =
        moviesPaths.isEmpty()?
            "":
            QDir(moviesPaths.first()).filePath(qApp->applicationName());
    this->m_imagesDirectory =
            config.value("imagesDirectory", defaultImagesDirectory).toString();
    this->m_videoDirectory =
            config.value("videoDirectory", defaultVideoDirectory).toString();
    this->m_imageFormat = config.value("imageFormat", "png").toString();
    this->m_imageSaveQuality = config.value("imageSaveQuality", -1).toInt();
    this->m_recordAudio =
            config.value("recordAudio", DEFAULT_RECORD_AUDIO).toBool();

    // Configure the recording formats

    auto outputWidth = qMax(config.value("outputWidth", 1280).toInt(), 160);
    auto outputHeight = qMax(config.value("outputHeight", 720).toInt(), 90);
    auto outputFPS = qMax(config.value("outputFPS", 30).toInt(), 1);
    auto audioSampleRate = qMax(config.value("audioSampleRate", 48000).toInt(), 8000);

    this->m_videoCaps = {AkVideoCaps::Format_yuv420p,
                         outputWidth,
                         outputHeight,
                         {outputFPS, 1}};
    this->m_audioCaps = {AkAudioCaps::SampleFormat_s16,
                         AkAudioCaps::Layout_stereo,
                         false,
                         audioSampleRate};

    this->m_audioBitrate = qMax(config.value("audioBitrate", DEFAULT_AUDIO_BITRATE).toInt(), 1000);
    this->m_videoBitrate = qMax(config.value("videoBitrate", DEFAULT_VIDEO_BITRATE).toInt(), 100000);
    this->m_videoGOP = qMax(config.value("videoGOP", DEFAULT_VIDEO_GOP).toInt(), 1);

    // Configure the format

    auto videoFormat =
            config.value("format", this->m_defaultFormat).toString();
    auto formatParts = videoFormat.split(':');
    auto formatPluginID = formatParts.value(0);
    auto formatName = formatParts.value(1);

    if (!formatPluginID.isEmpty() && !formatName.isEmpty()) {
        auto muxer = akPluginManager->create<AkVideoMuxer>(formatPluginID);

        if (muxer && muxer->muxers().contains(formatName)) {
            muxer->setMuxer(formatName);
            this->m_muxer = muxer;
            this->m_muxerPluginID = formatPluginID;
            this->loadFormatOptions();
        }
    }

    config.endGroup();

    // Configure the codecs

    auto videoFormatID = normatizePluginID(videoFormat);
    config.beginGroup("RecordConfigs_FormatCodecs_" + videoFormatID);

    auto audioCodec =
            config.value("audio",
                         this->defaultCodec(videoFormat,
                                            AkCaps::CapsAudio)).toString();
    auto audioCodecParts = audioCodec.split(':');
    auto audioCodecPluginID = audioCodecParts.value(0);
    auto audioCodecName = audioCodecParts.value(1);

    if (!audioCodecPluginID.isEmpty() && !audioCodecName.isEmpty()) {
        auto encoder = akPluginManager->create<AkAudioEncoder>(audioCodecPluginID);

        if (encoder && encoder->codecs().contains(audioCodecName)) {
            encoder->setCodec(audioCodecName);
            this->m_audioEncoder = encoder;
            this->m_audioPluginID = audioCodecPluginID;
            this->loadCodecOptions(AkCaps::CapsAudio);
        }
    }

    auto videoCodec =
            config.value("video",
                         this->defaultCodec(videoFormat,
                                            AkCaps::CapsVideo)).toString();
    auto videoCodecParts = videoCodec.split(':');
    auto videoCodecPluginID = videoCodecParts.value(0);
    auto videoCodecName = videoCodecParts.value(1);

    if (!videoCodecPluginID.isEmpty() && !videoCodecName.isEmpty()) {
        auto encoder = akPluginManager->create<AkVideoEncoder>(videoCodecPluginID);

        if (encoder && encoder->codecs().contains(videoCodecName)) {
            encoder->setCodec(videoCodecName);
            this->m_videoEncoder = encoder;
            this->m_videoPluginID = videoCodecPluginID;
            this->loadCodecOptions(AkCaps::CapsVideo);
        }
    }

    config.endGroup();
}

void RecordingPrivate::loadFormatOptions()
{
    if (!this->m_muxer)
        return;

    emit self->videoFormatOptionsChanged(this->m_muxer->options());

    QSettings config;
    auto pluginID =
            this->normatizePluginID(this->m_muxerPluginID
                                    + ':'
                                    + this->m_muxer->muxer());
    config.beginGroup("RecordConfigs_FormatOptions_" + pluginID);

    for (auto &option: this->m_muxer->options())
        if (config.contains(option.name()))
            this->m_muxer->setOptionValue(option.name(),
                                          config.value(option.name()));

    config.endGroup();
}

void RecordingPrivate::loadCodecOptions(AkCaps::CapsType type)
{
    switch (type) {
    case AkCaps::CapsAudio: {
        if (!this->m_audioEncoder)
            return;

        emit self->codecOptionsChanged(type, this->m_audioEncoder->options());

        QSettings config;
        auto pluginID =
                this->normatizePluginID(this->m_audioPluginID
                                        + ':'
                                        + this->m_audioEncoder->codec());
        config.beginGroup("RecordConfigs_AudioCodecOptions_" + pluginID);

        for (auto &option: this->m_audioEncoder->options())
            if (config.contains(option.name()))
                this->m_audioEncoder->setOptionValue(option.name(),
                                                     config.value(option.name()));

        config.endGroup();

        return;
    }

    case AkCaps::CapsVideo: {
        if (!this->m_videoEncoder)
            return;

        emit self->codecOptionsChanged(type, this->m_videoEncoder->options());

        QSettings config;
        auto pluginID =
                this->normatizePluginID(this->m_videoPluginID
                                        + ':'
                                        + this->m_videoEncoder->codec());
        config.beginGroup("RecordConfigs_VideoCodecOptions_" + pluginID);

        for (auto &option: this->m_videoEncoder->options())
            if (config.contains(option.name()))
                this->m_videoEncoder->setOptionValue(option.name(),
                                                     config.value(option.name()));

        config.endGroup();

        return;
    }

    default:
        break;
    }
}

void RecordingPrivate::updatePreviews()
{
    if (!this->canAccessStorage())
        return;

    // Update photo preview

    QStringList nameFilters;

    for (auto it = this->m_imageFormats.begin();
         it != this->m_imageFormats.end();
         it++) {
        nameFilters += "*." + it.key();
    }

    QDir dir(this->m_imagesDirectory);
    auto photos = dir.entryList(nameFilters,
                                QDir::Files | QDir::Readable,
                                QDir::Time);

    if (!photos.isEmpty())
        this->m_lastPhotoPreview = dir.filePath(photos.first());

    // Update video preview

    nameFilters.clear();

    for (auto &format: this->m_supportedFormats)
        nameFilters += "*." + format.extension;

    dir = QDir(this->m_videoDirectory);
    auto videos = dir.entryList(nameFilters,
                                QDir::Files | QDir::Readable,
                                QDir::Time);

    if (!videos.isEmpty()) {
        this->m_lastVideo = dir.filePath(videos.first());
        this->readThumbnail(this->m_lastVideo);
    }
}

void RecordingPrivate::readThumbnail(const QString &videoFile)
{
    if (!this->m_thumbnailer || videoFile.isEmpty())
        return;

    this->m_thumbnailer->setProperty("media", videoFile);
    this->m_thumbnailer->setProperty("sync", false);
}

void RecordingPrivate::thumbnailReady()
{
    this->m_thumbnailerMutex.lock();
    this->m_thumbnailer->setState(AkElement::ElementStateNull);
    this->m_thumbnailerMutex.unlock();

    auto tempPaths =
            QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    auto thumnailDir =
            QDir(tempPaths.first()).filePath(qApp->applicationName());

    this->m_thumbnailMutex.lockForRead();
    auto thumbnail = this->m_thumbnail;
    this->m_thumbnailMutex.unlock();

    if (thumbnail.isNull() || !QDir().mkpath(thumnailDir))
        return;

    auto media = this->m_thumbnailer->property("media").toString();
    auto baseName = QFileInfo(media).baseName();

    /* NOTE: Saving in formats other than BMP can result in broken files that
     * can cause Qml to crash the whole app.
     */
    auto thumbnailPath = QString("%1/%2.%3")
                         .arg(thumnailDir,
                              baseName,
                              "bmp");

    if (!thumbnail.save(thumbnailPath,
                        nullptr,
                        this->m_imageSaveQuality))
        return;

    this->m_lastVideoPreview = thumbnailPath;
    emit self->lastVideoPreviewChanged(thumbnailPath);
}

void RecordingPrivate::saveAudioCaps(const AkAudioCaps &audioCaps)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("audioSampleRate", audioCaps.rate());
    config.endGroup();
}

void RecordingPrivate::saveVideoCaps(const AkVideoCaps &videoCaps)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("outputWidth", videoCaps.width());
    config.setValue("outputHeight", videoCaps.height());
    config.setValue("outputFPS", qRound(videoCaps.fps().value()));
    config.endGroup();
}

void RecordingPrivate::saveVideoDirectory(const QString &videoDirectory)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("videoDirectory", videoDirectory);
    config.endGroup();
}

void RecordingPrivate::saveVideoFormat(const QString &videoFormat)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("format", videoFormat);
    config.endGroup();
}

void RecordingPrivate::saveCodec(AkCaps::CapsType type, const QString &codec)
{
    QSettings config;
    auto videoFormatID = normatizePluginID(self->videoFormat());
    config.beginGroup("RecordConfigs_FormatCodecs_" + videoFormatID);

    switch (type) {
    case AkCaps::CapsAudio:
        config.setValue("audio", codec);

        break;

    case AkCaps::CapsVideo:
        config.setValue("video", codec);

        break;

    default:
        break;
    }

    config.endGroup();
}

void RecordingPrivate::saveVideoFormatOptionValue(const QString &option,
                                                  const QVariant &value)
{

    QSettings config;
    auto pluginID = normatizePluginID(self->videoFormat());
    config.beginGroup("RecordConfigs_FormatOptions_" + pluginID);
    config.setValue(option, value);
    config.endGroup();
}

void RecordingPrivate::saveCodecOptionValue(AkCaps::CapsType type,
                                            const QString &option,
                                            const QVariant &value)
{
    QSettings config;
    auto pluginID = this->normatizePluginID(self->codec(type));

    switch (type) {
    case AkCaps::CapsAudio: {
        config.beginGroup("RecordConfigs_AudioCodecOptions_" + pluginID);
        config.setValue(option, value);
        config.endGroup();

        return;
    }

    case AkCaps::CapsVideo: {
        QSettings config;
        auto pluginID = this->normatizePluginID(self->codec(type));
        config.beginGroup("RecordConfigs_VideoCodecOptions_" + pluginID);
        config.setValue(option, value);
        config.endGroup();

        return;
    }

    default:
        break;
    }
}

void RecordingPrivate::saveBitrate(AkCaps::CapsType type, int bitrate)
{
    QSettings config;
    config.beginGroup("RecordConfigs");

    switch (type) {
    case AkCaps::CapsAudio:
        config.setValue("audioBitrate", bitrate);
        break;

    case AkCaps::CapsVideo:
        config.setValue("videoBitrate", bitrate);
        break;

    default:
        break;
    }

    config.endGroup();
}

void RecordingPrivate::saveVideoGOP(int gop)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("videoGOP", gop);
    config.endGroup();
}

void RecordingPrivate::saveRecordAudio(bool recordAudio)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("recordAudio", recordAudio);
    config.endGroup();
}

void RecordingPrivate::saveImagesDirectory(const QString &imagesDirectory)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("imagesDirectory", imagesDirectory);
    config.endGroup();
}

void RecordingPrivate::saveImageFormat(const QString &imageFormat)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("imageFormat", imageFormat);
    config.endGroup();
}

void RecordingPrivate::saveImageSaveQuality(int imageSaveQuality)
{
    QSettings config;
    config.beginGroup("RecordConfigs");
    config.setValue("imageSaveQuality", imageSaveQuality);
    config.endGroup();
}

#include "moc_recording.cpp"