File: DVDInputStreamNavigator.cpp

package info (click to toggle)
kodi 2%3A20.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 143,820 kB
  • sloc: cpp: 664,925; xml: 68,398; ansic: 37,223; python: 6,903; sh: 4,209; javascript: 2,325; makefile: 1,754; perl: 969; java: 513; cs: 390; objc: 340
file content (1582 lines) | stat: -rw-r--r-- 45,556 bytes parent folder | download
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
/*
 *  Copyright (C) 2005-2022 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "DVDInputStreamNavigator.h"
#include "filesystem/IFileTypes.h"
#include "filesystem/DvdCallback.h"
#include "utils/LangCodeExpander.h"
#include "../DVDDemuxSPU.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "LangInfo.h"
#include "ServiceBroker.h"
#include "utils/Geometry.h"
#include "utils/log.h"
#include "utils/URIUtils.h"
#include "utils/StringUtils.h"
#include "guilib/LocalizeStrings.h"
#if defined(TARGET_DARWIN_OSX)
#include "platform/darwin/osx/CocoaInterface.h"
#endif
#if defined(TARGET_WINDOWS_STORE)
#include "filesystem/SpecialProtocol.h"
#include "platform/Environment.h"
#endif

//FIXME
#ifdef TARGET_WINDOWS
#include "platform/win32/dirent.h"
#else
#include <dirent.h>
#endif

#ifdef TARGET_WINDOWS
struct iovec
{
  void* iov_base; /* Pointer to data. */
  size_t iov_len; /* Length of data.  */
};
#else
#include <sys/uio.h> /* struct iovec */
#endif

namespace
{
constexpr int HOLDMODE_NONE = 0;
/* set internally when we wish to flush demuxer */
constexpr int HOLDMODE_HELD = 1;
/* set by inputstream user, when they wish to skip the held mode */
constexpr int HOLDMODE_SKIP = 2;
/* set after hold mode has been exited, and action that inited it has been executed */
constexpr int HOLDMODE_DATA = 3;

// DVD Subpicture types
constexpr int DVD_SUBPICTURE_TYPE_NOTSPECIFIED = 0;
constexpr int DVD_SUBPICTURE_TYPE_LANGUAGE = 1;

// DVD Subpicture language extensions
constexpr int DVD_SUBPICTURE_LANG_EXT_NOTSPECIFIED = 0;
constexpr int DVD_SUBPICTURE_LANG_EXT_NORMALCAPTIONS = 1;
constexpr int DVD_SUBPICTURE_LANG_EXT_BIGCAPTIONS = 2;
constexpr int DVD_SUBPICTURE_LANG_EXT_CHILDRENSCAPTIONS = 3;
constexpr int DVD_SUBPICTURE_LANG_EXT_NORMALCC = 5;
constexpr int DVD_SUBPICTURE_LANG_EXT_BIGCC = 6;
constexpr int DVD_SUBPICTURE_LANG_EXT_CHILDRENSCC = 7;
constexpr int DVD_SUBPICTURE_LANG_EXT_FORCED = 9;
constexpr int DVD_SUBPICTURE_LANG_EXT_NORMALDIRECTORSCOMMENTS = 13;
constexpr int DVD_SUBPICTURE_LANG_EXT_BIGDIRECTORSCOMMENTS = 14;
constexpr int DVD_SUBPICTURE_LANG_EXT_CHILDRENDIRECTORSCOMMENTS = 15;

// DVD Audio language extensions
constexpr int DVD_AUDIO_LANG_EXT_NOTSPECIFIED = 0;
constexpr int DVD_AUDIO_LANG_EXT_NORMALCAPTIONS = 1;
constexpr int DVD_AUDIO_LANG_EXT_VISUALLYIMPAIRED = 2;
constexpr int DVD_AUDIO_LANG_EXT_DIRECTORSCOMMENTS1 = 3;
constexpr int DVD_AUDIO_LANG_EXT_DIRECTORSCOMMENTS2 = 4;
} // namespace

static int dvd_inputstreamnavigator_cb_seek(void * p_stream, uint64_t i_pos);
static int dvd_inputstreamnavigator_cb_read(void * p_stream, void * buffer, int i_read);
static int dvd_inputstreamnavigator_cb_readv(void * p_stream, void * p_iovec, int i_blocks);

static dvdnav_filesystem_h kodiDvdFilesystem;

CDVDInputStreamNavigator::CDVDInputStreamNavigator(IVideoPlayer* player, const CFileItem& fileitem)
  : CDVDInputStream(DVDSTREAM_TYPE_DVD, fileitem), m_pstream(nullptr)
{
  m_dvdnav = 0;
  m_pVideoPlayer = player;
  m_bCheckButtons = false;
  m_iCellStart = 0;
  m_iVobUnitStart = 0LL;
  m_iVobUnitStop = 0LL;
  m_iVobUnitCorrection = 0LL;
  m_bInMenu = false;
  m_holdmode = HOLDMODE_NONE;
  m_iTitle = m_iTitleCount = 0;
  m_iPart = m_iPartCount = 0;
  m_iTime = m_iTotalTime = 0;
  m_bEOF = false;
  m_lastevent = DVDNAV_NOP;
  m_dvdnav_stream_cb.pf_read = dvd_inputstreamnavigator_cb_read;
  m_dvdnav_stream_cb.pf_readv = dvd_inputstreamnavigator_cb_readv;
  m_dvdnav_stream_cb.pf_seek = dvd_inputstreamnavigator_cb_seek;

  memset(m_lastblock, 0, sizeof(m_lastblock));
}

CDVDInputStreamNavigator::~CDVDInputStreamNavigator()
{
  Close();
}

bool CDVDInputStreamNavigator::Open()
{
  m_item.SetMimeType("video/x-dvd-mpeg");
  if (!CDVDInputStream::Open())
    return false;

#if defined(TARGET_WINDOWS_STORE)
  // libdvdcss
  CEnvironment::putenv("DVDCSS_METHOD=key");
  CEnvironment::putenv("DVDCSS_VERBOSE=3");
  CEnvironment::putenv("DVDCSS_CACHE=" + CSpecialProtocol::TranslatePath("special://masterprofile/cache"));
#endif


  // load the dvd language codes
  // g_LangCodeExpander.LoadStandardCodes();

  // libdvdcss fails if the file path contains VIDEO_TS.IFO or VIDEO_TS/VIDEO_TS.IFO
  // libdvdnav is still able to play without, so strip them.

  std::string path = m_item.GetDynPath();
  if(URIUtils::GetFileName(path) == "VIDEO_TS.IFO")
    path = URIUtils::GetParentPath(path);
  URIUtils::RemoveSlashAtEnd(path);
  if(URIUtils::GetFileName(path) == "VIDEO_TS")
    path = URIUtils::GetParentPath(path);
  URIUtils::RemoveSlashAtEnd(path);

#if defined(TARGET_DARWIN_OSX)
  // if physical DVDs, libdvdnav wants "/dev/rdiskN" device name for OSX,
  // strDVDFile will get realloc'ed and replaced IF this is a physical DVD.
  char* strDVDFile = Cocoa_MountPoint2DeviceName(strdup(path.c_str()));
  path = strDVDFile;
  free(strDVDFile);
#endif

#if DVDNAV_VERSION >= 60100
  dvdnav_logger_cb loggerCallback;
  loggerCallback.pf_log = CDVDCallback::dvd_logger;
#endif

  // open up the DVD device
  if (m_item.IsDiscImage())
  {
    // if dvd image file (ISO or alike) open using libdvdnav stream callback functions
    m_pstream.reset(new CDVDInputStreamFile(m_item, XFILE::READ_TRUNCATED | XFILE::READ_BITRATE | XFILE::READ_CHUNKED));
#if DVDNAV_VERSION >= 60100
    if (!m_pstream->Open() || dvdnav_open_stream2(&m_dvdnav, m_pstream.get(), &loggerCallback,
                                                        &m_dvdnav_stream_cb) != DVDNAV_STATUS_OK)
#else
    if (!m_pstream->Open() || dvdnav_open_stream(&m_dvdnav, m_pstream.get(), &m_dvdnav_stream_cb) != DVDNAV_STATUS_OK)
#endif
    {
      CLog::Log(LOGERROR, "Error opening image file or Error on dvdnav_open_stream");
      Close();
      return false;
    }
  }
#if DVDNAV_VERSION >= 60100
  else if (URIUtils::IsNetworkFilesystem(path))
  {
    kodiDvdFilesystem.dir_open = CDVDCallback::dir_open;
    kodiDvdFilesystem.file_open = CDVDCallback::file_open;
    kodiDvdFilesystem.stat = CDVDCallback::stat;
    kodiDvdFilesystem.close = CDVDCallback::close;
    if (dvdnav_open_files(&m_dvdnav, nullptr, &loggerCallback, path.c_str(), &kodiDvdFilesystem) != DVDNAV_STATUS_OK)
    {
      CLog::Log(LOGERROR, "Error on dvdnav_open_files");
      Close();
      return false;
    }
  }
  else if (dvdnav_open2(&m_dvdnav, nullptr, &loggerCallback, path.c_str()) !=
           DVDNAV_STATUS_OK)
#else
  else if (dvdnav_open(&m_dvdnav, path.c_str()) != DVDNAV_STATUS_OK)
#endif
  {
    CLog::Log(LOGERROR, "Error on dvdnav_open");
    Close();
    return false;
  }

  int region = CServiceBroker::GetSettingsComponent()->GetSettings()->GetInt(CSettings::SETTING_DVDS_PLAYERREGION);
  int mask = 0;
  if(region > 0)
    mask = 1 << (region-1);
  else
  {
    // find out what region dvd reports itself to be from, and use that as mask if available
    if (dvdnav_get_disk_region_mask(m_dvdnav, &mask) == DVDNAV_STATUS_ERR)
    {
      CLog::LogF(LOGERROR, "Error getting DVD region code: {}",
                 dvdnav_err_to_string(m_dvdnav));
      mask = 0xff;
    }
  }

  CLog::Log(LOGDEBUG, "{} - Setting region mask {:02x}", __FUNCTION__, mask);
  dvdnav_set_region_mask(m_dvdnav, mask);

  // get default language settings
  char language_menu[3];
  strncpy(language_menu, g_langInfo.GetDVDMenuLanguage().c_str(), sizeof(language_menu)-1);
  language_menu[2] = '\0';

  char language_audio[3];
  strncpy(language_audio, g_langInfo.GetDVDAudioLanguage().c_str(), sizeof(language_audio)-1);
  language_audio[2] = '\0';

  char language_subtitle[3];
  strncpy(language_subtitle, g_langInfo.GetDVDSubtitleLanguage().c_str(), sizeof(language_subtitle)-1);
  language_subtitle[2] = '\0';

  // set language settings in case they are not set in xbmc's configuration
  if (language_menu[0] == '\0') strcpy(language_menu, "en");
  if (language_audio[0] == '\0') strcpy(language_audio, "en");
  if (language_subtitle[0] == '\0') strcpy(language_subtitle, "en");

  // set default language settings
  if (dvdnav_menu_language_select(m_dvdnav, (char*)language_menu) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on setting default menu language: {}",
              dvdnav_err_to_string(m_dvdnav));
    CLog::Log(LOGERROR, "Defaulting to \"en\"");
    //! @bug libdvdnav isn't const correct
    dvdnav_menu_language_select(m_dvdnav, const_cast<char*>("en"));
  }

  if (dvdnav_audio_language_select(m_dvdnav, (char*)language_audio) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on setting default audio language: {}",
              dvdnav_err_to_string(m_dvdnav));
    CLog::Log(LOGERROR, "Defaulting to \"en\"");
    //! @bug libdvdnav isn't const correct
    dvdnav_audio_language_select(m_dvdnav, const_cast<char*>("en"));
  }

  if (dvdnav_spu_language_select(m_dvdnav, (char*)language_subtitle) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on setting default subtitle language: {}",
              dvdnav_err_to_string(m_dvdnav));
    CLog::Log(LOGERROR, "Defaulting to \"en\"");
    //! @bug libdvdnav isn't const correct
    dvdnav_spu_language_select(m_dvdnav, const_cast<char*>("en"));
  }

  // set read ahead cache usage
  if (dvdnav_set_readahead_flag(m_dvdnav, 1) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on dvdnav_set_readahead_flag: {}",
              dvdnav_err_to_string(m_dvdnav));
    Close();
    return false;
  }

  // set the PGC positioning flag to have position information relatively to the
  // whole feature instead of just relatively to the current chapter
  if (dvdnav_set_PGC_positioning_flag(m_dvdnav, 1) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on dvdnav_set_PGC_positioning_flag: {}",
              dvdnav_err_to_string(m_dvdnav));
    Close();
    return false;
  }

  // jump directly to title menu
  if(CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(CSettings::SETTING_DVDS_AUTOMENU))
  {
    int len, event;
    uint8_t buf[2048];
    uint8_t* buf_ptr = buf;

    // must startup vm and pgc
    dvdnav_get_next_cache_block(m_dvdnav,&buf_ptr,&event,&len);
    dvdnav_sector_search(m_dvdnav, 0, SEEK_SET);

    // first try title menu
    if(dvdnav_menu_call(m_dvdnav, DVD_MENU_Title) != DVDNAV_STATUS_OK)
    {
      CLog::Log(LOGERROR, "Error on dvdnav_menu_call(Title): {}",
                dvdnav_err_to_string(m_dvdnav));
      // next try root menu
      if(dvdnav_menu_call(m_dvdnav, DVD_MENU_Root) != DVDNAV_STATUS_OK )
        CLog::Log(LOGERROR, "Error on dvdnav_menu_call(Root): {}",
                  dvdnav_err_to_string(m_dvdnav));
    }
  }

  m_bEOF = false;
  m_bCheckButtons = false;
  m_iCellStart = 0;
  m_iVobUnitStart = 0LL;
  m_iVobUnitStop = 0LL;
  m_iVobUnitCorrection = 0LL;
  m_bInMenu = false;
  m_holdmode = HOLDMODE_NONE;
  m_iTitle = m_iTitleCount = 0;
  m_iPart = m_iPartCount = 0;
  m_iTime = m_iTotalTime = 0;

  return true;
}

void CDVDInputStreamNavigator::Close()
{
  if (!m_dvdnav) return;

  // finish off by closing the dvdnav device
  if (dvdnav_close(m_dvdnav) != DVDNAV_STATUS_OK)
  {
    CLog::Log(LOGERROR, "Error on dvdnav_close: {}", dvdnav_err_to_string(m_dvdnav));
    return ;
  }

  CDVDInputStream::Close();
  m_dvdnav = NULL;
  m_bEOF = true;

  if (m_pstream != nullptr)
  {
    m_pstream->Close();
    m_pstream.reset();
  }
}

int CDVDInputStreamNavigator::Read(uint8_t* buf, int buf_size)
{
  if (!m_dvdnav || m_bEOF) return 0;
  if (buf_size < DVD_VIDEO_BLOCKSIZE)
  {
    CLog::Log(LOGERROR,
              "CDVDInputStreamNavigator: buffer size is to small, {} bytes, should be 2048 bytes",
              buf_size);
    return -1;
  }

  int iBytesRead = 0;

  int NOPcount = 0;
  while (true)
  {
    int navresult = ProcessBlock(buf, &iBytesRead);

    if (navresult == NAVRESULT_HOLD)
      return 0; // return 0 bytes read;
    else if (navresult == NAVRESULT_ERROR)
      return -1;
    else if (navresult == NAVRESULT_DATA)
      return iBytesRead;
    else if (navresult == NAVRESULT_NOP)
    {
      NOPcount++;
      if (NOPcount == 1000)
      {
        m_bEOF = true;
        CLog::Log(LOGERROR,"CDVDInputStreamNavigator: Stopping playback due to infinite loop, caused by badly authored DVD navigation structure. Try enabling 'Attempt to skip introduction before DVD menu'.");
        m_pVideoPlayer->OnDiscNavResult(nullptr, DVDNAV_ERROR);
        return -1; // fail and stop playback.
      }
    }
  }

  return iBytesRead;
}

// not working yet, but it is the recommended way for seeking
int64_t CDVDInputStreamNavigator::Seek(int64_t offset, int whence)
{
  if(whence == SEEK_POSSIBLE)
    return 0;
  else
    return -1;
}

int CDVDInputStreamNavigator::ProcessBlock(uint8_t* dest_buffer, int* read)
{
  if (!m_dvdnav)
    return -1;

  int result;
  int len = 2048;

  // m_tempbuffer will be used for anything that isn't a normal data block
  uint8_t* buf = m_lastblock;
  int iNavresult = -1;

  if (m_holdmode == HOLDMODE_HELD)
    return NAVRESULT_HOLD;

  // the main reading function
  if(m_holdmode == HOLDMODE_SKIP)
  { /* we where holding data, return the data held */
    m_holdmode = HOLDMODE_DATA;
    result = DVDNAV_STATUS_OK;
  }
  else
    result = dvdnav_get_next_cache_block(m_dvdnav, &buf, &m_lastevent, &len);

  if (result == DVDNAV_STATUS_ERR)
  {
    CLog::Log(LOGERROR, "Error getting next block: {}", dvdnav_err_to_string(m_dvdnav));
    m_bEOF = true;
    return NAVRESULT_ERROR;
  }

    switch (m_lastevent)
    {
    case DVDNAV_BLOCK_OK:
      {
        // We have received a regular block of the currently playing MPEG stream.
        // buf contains the data and len its length (obviously!) (which is always 2048 bytes btw)
        m_holdmode = HOLDMODE_NONE;
        memcpy(dest_buffer, buf, len);
        *read = len;
        iNavresult = NAVRESULT_DATA;
      }
      break;

    case DVDNAV_NOP:
      // Nothing to do here.
      break;

    case DVDNAV_STILL_FRAME:
      {
        // We have reached a still frame. A real player application would wait
        // the amount of time specified by the still's length while still handling
        // user input to make menus and other interactive stills work.
        // A length of 0xff means an indefinite still which has to be skipped
        // indirectly by some user interaction.
        m_holdmode = HOLDMODE_NONE;
        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_STILL_FRAME);
      }
      break;

    case DVDNAV_WAIT:
      {
        // We have reached a point in DVD playback, where timing is critical.
        // Player application with internal fifos can introduce state
        // inconsistencies, because libdvdnav is always the fifo's length
        // ahead in the stream compared to what the application sees.
        // Such applications should wait until their fifos are empty
        // when they receive this type of event.
        if(m_holdmode == HOLDMODE_NONE)
        {
          CLog::Log(LOGDEBUG, " - DVDNAV_WAIT (HOLDING)");
          m_holdmode = HOLDMODE_HELD;
          iNavresult = NAVRESULT_HOLD;
        }
        else
          iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_WAIT);

        /* if user didn't care for action, just skip it */
        if(iNavresult == NAVRESULT_NOP)
          SkipWait();
      }
      break;

    case DVDNAV_SPU_CLUT_CHANGE:
      // Player applications should pass the new colour lookup table to their
      // SPU decoder. The CLUT is given as 16 uint32_t's in the buffer.
      {
        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_SPU_CLUT_CHANGE);
      }
      break;

    case DVDNAV_SPU_STREAM_CHANGE:
      // Player applications should inform their SPU decoder to switch channels
      {
        m_bCheckButtons = true;
        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_SPU_STREAM_CHANGE);
      }
      break;

    case DVDNAV_AUDIO_STREAM_CHANGE:
      // Player applications should inform their audio decoder to switch channels
      {
        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_AUDIO_STREAM_CHANGE);
      }

      break;

    case DVDNAV_HIGHLIGHT:
      {
        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_HIGHLIGHT);
      }
      break;

    case DVDNAV_VTS_CHANGE:
      // Some status information like video aspect and video scale permissions do
      // not change inside a VTS. Therefore this event can be used to query such
      // information only when necessary and update the decoding/displaying
      // accordingly.
      {
        if(m_holdmode == HOLDMODE_NONE)
        {
          CLog::Log(LOGDEBUG, " - DVDNAV_VTS_CHANGE (HOLDING)");
          m_holdmode = HOLDMODE_HELD;
          iNavresult = NAVRESULT_HOLD;
        }
        else
        {
          bool menu = (0 == dvdnav_is_domain_vts(m_dvdnav));
          if (menu != m_bInMenu)
          {
            m_bInMenu = menu;
          }
          iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_VTS_CHANGE);
        }
      }
      break;

    case DVDNAV_CELL_CHANGE:
      {
        // Some status information like the current Title and Part numbers do not
        // change inside a cell. Therefore this event can be used to query such
        // information only when necessary and update the decoding/displaying
        // accordingly.

        uint32_t pos = 0;
        uint32_t len = 0;

        dvdnav_current_title_info(m_dvdnav, &m_iTitle, &m_iPart);
        dvdnav_get_number_of_titles(m_dvdnav, &m_iTitleCount);
        if(m_iTitle > 0)
          dvdnav_get_number_of_parts(m_dvdnav, m_iTitle, &m_iPartCount);
        else
          m_iPartCount = 0;
        dvdnav_get_position(m_dvdnav, &pos, &len);

        // get chapters' timestamps if we have not cached them yet
        if (m_mapTitleChapters.find(m_iTitle) == m_mapTitleChapters.end())
        {
          uint64_t* times = NULL;
          uint64_t duration;
          //dvdnav_describe_title_chapters returns 0 on failure and NULL for times
          int entries = dvdnav_describe_title_chapters(m_dvdnav, m_iTitle, &times, &duration);

          if (entries != m_iPartCount)
            CLog::Log(LOGDEBUG,
                      "{} - Number of chapters/positions differ: Chapters {}, positions {}",
                      __FUNCTION__, m_iPartCount, entries);

          if (times)
          {
            // the times array stores the end timestamps of the chapters, e.g., times[0] stores the position/beginning of chapter 2
            m_mapTitleChapters[m_iTitle][1] = 0;
            for (int i = 0; i < entries - 1; ++i)
            {
              m_mapTitleChapters[m_iTitle][i + 2] = times[i] / 90000;
            }
            free(times);
          }
        }
        CLog::Log(LOGDEBUG, "{} - Cell change: Title {}, Chapter {}", __FUNCTION__, m_iTitle,
                  m_iPart);
        CLog::Log(LOGDEBUG, "{} - At position {:.0f}% inside the feature", __FUNCTION__,
                  100 * (double)pos / (double)len);
        //Get total segment time

        dvdnav_cell_change_event_t* cell_change_event = reinterpret_cast<dvdnav_cell_change_event_t*>(buf);
        m_iCellStart = cell_change_event->cell_start; // store cell time as we need that for time later
        m_iTime      = (int) (m_iCellStart / 90);
        m_iTotalTime = (int) (cell_change_event->pgc_length / 90);

        iNavresult = m_pVideoPlayer->OnDiscNavResult(buf, DVDNAV_CELL_CHANGE);
      }
      break;

    case DVDNAV_NAV_PACKET:
      {
        // A NAV packet provides PTS discontinuity information, angle linking information and
        // button definitions for DVD menus. Angles are handled completely inside libdvdnav.
        // For the menus to work, the NAV packet information has to be passed to the overlay
        // engine of the player so that it knows the dimensions of the button areas.

        // Applications with fifos should not use these functions to retrieve NAV packets,
        // they should implement their own NAV handling, because the packet you get from these
        // functions will already be ahead in the stream which can cause state inconsistencies.
        // Applications with fifos should therefore pass the NAV packet through the fifo
        // and decoding pipeline just like any other data.

        // Calculate current time
        //unsigned int pos, len;
        //dvdnav_get_position(m_dvdnav, &pos, &len);
        //m_iTime = (int)(((int64_t)m_iTotalTime * pos) / len);

        pci_t* pci = dvdnav_get_current_nav_pci(m_dvdnav);
        dvdnav_get_current_nav_dsi(m_dvdnav);

        if(!pci)
        {
          iNavresult = NAVRESULT_NOP;
          break;
        }

        /* if we have any buttons or are not in vts domain we assume we are in menu */
        bool menu = pci->hli.hl_gi.hli_ss || (0 == dvdnav_is_domain_vts(m_dvdnav));
        if (menu != m_bInMenu)
        {
          m_bInMenu = menu;
        }

        /* check for any gap in the stream, this is likely a discontinuity */
        int64_t gap = (int64_t)pci->pci_gi.vobu_s_ptm - m_iVobUnitStop;
        if(gap)
        {
          /* make sure demuxer is flushed before we change any correction */
          if(m_holdmode == HOLDMODE_NONE)
          {
            CLog::Log(LOGDEBUG, "DVDNAV_NAV_PACKET (HOLDING)");
            m_holdmode = HOLDMODE_HELD;
            iNavresult = NAVRESULT_HOLD;
            break;
          }
          m_iVobUnitCorrection += gap;

          CLog::Log(LOGDEBUG, "DVDNAV_NAV_PACKET - DISCONTINUITY FROM:{} TO:{} DIFF:{}",
                    (m_iVobUnitStop * 1000) / 90, ((int64_t)pci->pci_gi.vobu_s_ptm * 1000) / 90,
                    (gap * 1000) / 90);
        }

        m_iVobUnitStart = pci->pci_gi.vobu_s_ptm;
        m_iVobUnitStop = pci->pci_gi.vobu_e_ptm;

        m_iTime = (int) ( dvdnav_get_current_time(m_dvdnav)  / 90 );

        iNavresult = m_pVideoPlayer->OnDiscNavResult((void*)pci, DVDNAV_NAV_PACKET);
      }
      break;

    case DVDNAV_HOP_CHANNEL:
      // This event is issued whenever a non-seamless operation has been executed.
      // Applications with fifos should drop the fifos content to speed up responsiveness.
      {
        iNavresult = m_pVideoPlayer->OnDiscNavResult(NULL, DVDNAV_HOP_CHANNEL);
      }
      break;

    case DVDNAV_STOP:
      {
        // Playback should end here.

        // don't read any further, it could be libdvdnav had some problems reading
        // the disc. reading further results in a crash
        m_bEOF = true;

        m_pVideoPlayer->OnDiscNavResult(NULL, DVDNAV_STOP);
        iNavresult = NAVRESULT_ERROR;
      }
      break;

    default:
      {
        CLog::Log(LOGDEBUG, "CDVDInputStreamNavigator: Unknown event ({})", m_lastevent);
      }
      break;

    }

    // check if libdvdnav gave us some other buffer to work with
    // probably not needed since function will check if buf
    // is part of the internal cache, but do it for good measure
    if( buf != m_lastblock )
      dvdnav_free_cache_block(m_dvdnav, buf);

  return iNavresult;
}

bool CDVDInputStreamNavigator::SetActiveAudioStream(int iId)
{
  CLog::Log(LOGDEBUG, "Setting active audio stream id: {}", iId);

  if (!m_dvdnav)
    return false;

  dvdnav_status_t ret = dvdnav_set_active_stream(m_dvdnav, iId, DVD_AUDIO_STREAM);
  if (ret == DVDNAV_STATUS_ERR)
  {
    CLog::LogF(LOGERROR, "dvdnav_set_active_stream (audio) failed: {}",
               dvdnav_err_to_string(m_dvdnav));
  }

  return ret == DVDNAV_STATUS_OK;
}

bool CDVDInputStreamNavigator::SetActiveSubtitleStream(int iId)
{
  CLog::LogF(LOGDEBUG, "Setting active subtitle stream id: {}", iId);

  if (!m_dvdnav)
    return false;

  dvdnav_status_t ret = dvdnav_set_active_stream(m_dvdnav, iId, DVD_SUBTITLE_STREAM);
  if (ret == DVDNAV_STATUS_ERR)
  {
    CLog::LogF(LOGERROR, "dvdnav_set_active_stream (subtitles) failed: {}",
               dvdnav_err_to_string(m_dvdnav));
  }

  return ret == DVDNAV_STATUS_OK;
}

void CDVDInputStreamNavigator::ActivateButton()
{
  if (m_dvdnav)
  {
    dvdnav_button_activate(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav));
  }
}

void CDVDInputStreamNavigator::SelectButton(int iButton)
{
  if (!m_dvdnav) return;
  dvdnav_button_select(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav), iButton);
}

int CDVDInputStreamNavigator::GetCurrentButton()
{
  if (!m_dvdnav)
  {
    return -1;
  }

  int button = 0;
  if (dvdnav_get_current_highlight(m_dvdnav, &button) == DVDNAV_STATUS_ERR)
  {
    CLog::LogF(LOGERROR, "dvdnav_get_current_highlight failed: {}",
               dvdnav_err_to_string(m_dvdnav));
    return -1;
  }
  return button;
}

void CDVDInputStreamNavigator::CheckButtons()
{
  if (m_dvdnav && m_bCheckButtons)
  {
    m_bCheckButtons = false;
    pci_t* pci = dvdnav_get_current_nav_pci(m_dvdnav);
    int iCurrentButton = GetCurrentButton();

    if( iCurrentButton > 0 && iCurrentButton < 37 )
    {
      btni_t* button = &(pci->hli.btnit[iCurrentButton-1]);

      // menu buttons are always cropped overlays, so if there is no such information
      // we assume the button is invalid
      if ((button->x_start || button->x_end || button->y_start || button->y_end))
      {
        // button has info, it's valid
        return;
      }
    }

    // select first valid button.
    for (int i = 0; i < 36; i++)
    {
      if (pci->hli.btnit[i].x_start ||
          pci->hli.btnit[i].x_end ||
          pci->hli.btnit[i].y_start ||
          pci->hli.btnit[i].y_end)
      {
        CLog::Log(LOGWARNING, "CDVDInputStreamNavigator: found invalid button({})", iCurrentButton);
        CLog::Log(LOGWARNING, "CDVDInputStreamNavigator: switching to button({}) instead", i + 1);
        dvdnav_button_select(m_dvdnav, pci, i + 1);
        break;
      }
    }
  }
}

int CDVDInputStreamNavigator::GetTotalButtons()
{
  if (!m_dvdnav) return 0;

  pci_t* pci = dvdnav_get_current_nav_pci(m_dvdnav);

  int counter = 0;
  for (const btni_t& buttonInfo : pci->hli.btnit)
  {
    if (buttonInfo.x_start ||
        buttonInfo.x_end ||
        buttonInfo.y_start ||
        buttonInfo.y_end)
    {
      counter++;
    }
  }
  return counter;
}

void CDVDInputStreamNavigator::OnUp()
{
  if (m_dvdnav) dvdnav_upper_button_select(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav));
}

void CDVDInputStreamNavigator::OnDown()
{
  if (m_dvdnav) dvdnav_lower_button_select(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav));
}

void CDVDInputStreamNavigator::OnLeft()
{
  if (m_dvdnav) dvdnav_left_button_select(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav));
}

void CDVDInputStreamNavigator::OnRight()
{
  if (m_dvdnav) dvdnav_right_button_select(m_dvdnav, dvdnav_get_current_nav_pci(m_dvdnav));
}

bool CDVDInputStreamNavigator::OnMouseMove(const CPoint &point)
{
  if (m_dvdnav)
  {
    pci_t* pci = dvdnav_get_current_nav_pci(m_dvdnav);
    return (DVDNAV_STATUS_OK == dvdnav_mouse_select(m_dvdnav, pci, (int32_t)point.x, (int32_t)point.y));
  }
  return false;
}

bool CDVDInputStreamNavigator::OnMouseClick(const CPoint &point)
{
  if (m_dvdnav)
  {
    pci_t* pci = dvdnav_get_current_nav_pci(m_dvdnav);
    return (DVDNAV_STATUS_OK == dvdnav_mouse_activate(m_dvdnav, pci, (int32_t)point.x, (int32_t)point.y));
  }
  return false;
}

bool CDVDInputStreamNavigator::OnMenu()
{
  if (!m_dvdnav)
  {
    return false;
  }

  return dvdnav_menu_call(m_dvdnav, DVD_MENU_Escape) == DVDNAV_STATUS_OK;
}

void CDVDInputStreamNavigator::OnBack()
{
  if (m_dvdnav) dvdnav_go_up(m_dvdnav);
}

// we don't allow skipping in menu's cause it will remove menu overlays
void CDVDInputStreamNavigator::OnNext()
{
  if (m_dvdnav && !(IsInMenu() && GetTotalButtons() > 0))
  {
    dvdnav_next_pg_search(m_dvdnav);
  }
}

// we don't allow skipping in menu's cause it will remove menu overlays
void CDVDInputStreamNavigator::OnPrevious()
{
  if (m_dvdnav && !(IsInMenu() && GetTotalButtons() > 0))
  {
    dvdnav_prev_pg_search(m_dvdnav);
  }
}

void CDVDInputStreamNavigator::SkipStill()
{
  if (!m_dvdnav)
    return ;
  dvdnav_still_skip(m_dvdnav);
}

void CDVDInputStreamNavigator::SkipWait()
{
  if (!m_dvdnav) return ;
  dvdnav_wait_skip(m_dvdnav);
}

CDVDInputStream::ENextStream CDVDInputStreamNavigator::NextStream()
{
  if(m_holdmode == HOLDMODE_HELD)
    m_holdmode = HOLDMODE_SKIP;

  if(m_bEOF)
    return NEXTSTREAM_NONE;
  else if(m_lastevent == DVDNAV_VTS_CHANGE)
    return NEXTSTREAM_OPEN;
  else
    return NEXTSTREAM_RETRY;
}

int CDVDInputStreamNavigator::GetActiveSubtitleStream()
{
  int activeStream = 0;

  if (!m_dvdnav)
  {
    return activeStream;
  }

  const int8_t logicalSubStreamId = dvdnav_get_active_spu_stream(m_dvdnav);
  if (logicalSubStreamId < 0)
  {
    return activeStream;
  }

  int subStreamCount = GetSubTitleStreamCount();
  for (int subpN = 0; subpN < subStreamCount; subpN++)
  {
    if (dvdnav_get_spu_logical_stream(m_dvdnav, subpN) == logicalSubStreamId)
    {
      activeStream = subpN;
      break;
    }
  }

  return activeStream;
}

SubtitleStreamInfo CDVDInputStreamNavigator::GetSubtitleStreamInfo(const int iId)
{
  SubtitleStreamInfo info;
  if (!m_dvdnav)
    return info;

  subp_attr_t subp_attributes;

  if (dvdnav_get_spu_attr(m_dvdnav, iId, &subp_attributes) == DVDNAV_STATUS_OK)
  {
    SetSubtitleStreamName(info, subp_attributes);

    char lang[3];
    lang[2] = 0;
    lang[1] = (subp_attributes.lang_code & 255);
    lang[0] = (subp_attributes.lang_code >> 8) & 255;

    info.language = g_LangCodeExpander.ConvertToISO6392B(lang);
  }

  return info;
}

void CDVDInputStreamNavigator::SetSubtitleStreamName(SubtitleStreamInfo &info, const subp_attr_t &subp_attributes)
{
  if (subp_attributes.type == DVD_SUBPICTURE_TYPE_LANGUAGE ||
      subp_attributes.type == DVD_SUBPICTURE_TYPE_NOTSPECIFIED)
  {
    switch (subp_attributes.code_extension)
    {
      case DVD_SUBPICTURE_LANG_EXT_NOTSPECIFIED:
      case DVD_SUBPICTURE_LANG_EXT_CHILDRENSCAPTIONS:
        break;

      case DVD_SUBPICTURE_LANG_EXT_NORMALCAPTIONS:
      case DVD_SUBPICTURE_LANG_EXT_NORMALCC:
      case DVD_SUBPICTURE_LANG_EXT_BIGCAPTIONS:
      case DVD_SUBPICTURE_LANG_EXT_BIGCC:
      case DVD_SUBPICTURE_LANG_EXT_CHILDRENSCC:
        info.flags = StreamFlags::FLAG_HEARING_IMPAIRED;
        break;
      case DVD_SUBPICTURE_LANG_EXT_FORCED:
        info.flags = StreamFlags::FLAG_FORCED;
        break;
      case DVD_SUBPICTURE_LANG_EXT_NORMALDIRECTORSCOMMENTS:
      case DVD_SUBPICTURE_LANG_EXT_BIGDIRECTORSCOMMENTS:
      case DVD_SUBPICTURE_LANG_EXT_CHILDRENDIRECTORSCOMMENTS:
        info.name = g_localizeStrings.Get(37001);
        break;
      default:
        break;
    }
  }
}

int CDVDInputStreamNavigator::GetSubTitleStreamCount()
{
  if (!m_dvdnav)
  {
    return 0;
  }
  return dvdnav_get_number_of_streams(m_dvdnav, DVD_SUBTITLE_STREAM);
}

int CDVDInputStreamNavigator::GetActiveAudioStream()
{
  if (!m_dvdnav)
  {
    return -1;
  }

  const int8_t logicalAudioStreamId = dvdnav_get_active_audio_stream(m_dvdnav);
  if (logicalAudioStreamId < 0)
  {
    return -1;
  }

  int activeStream = -1;
  int audioStreamCount = GetAudioStreamCount();
  for (int audioN = 0; audioN < audioStreamCount; audioN++)
  {
    if (dvdnav_get_audio_logical_stream(m_dvdnav, audioN) == logicalAudioStreamId)
    {
      activeStream = audioN;
      break;
    }
  }

  return activeStream;
}

void CDVDInputStreamNavigator::SetAudioStreamName(AudioStreamInfo &info, const audio_attr_t &audio_attributes)
{
  switch( audio_attributes.code_extension )
  {
    case DVD_AUDIO_LANG_EXT_VISUALLYIMPAIRED:
      info.name = g_localizeStrings.Get(37000);
      info.flags = StreamFlags::FLAG_VISUAL_IMPAIRED;
      break;
    case DVD_AUDIO_LANG_EXT_DIRECTORSCOMMENTS1:
      info.name = g_localizeStrings.Get(37001);
      break;
    case DVD_AUDIO_LANG_EXT_DIRECTORSCOMMENTS2:
      info.name = g_localizeStrings.Get(37002);
      break;
    case DVD_AUDIO_LANG_EXT_NOTSPECIFIED:
    case DVD_AUDIO_LANG_EXT_NORMALCAPTIONS:
    default:
      break;
  }

  switch(audio_attributes.audio_format)
  {
  case DVD_AUDIO_FORMAT_AC3:
    info.name += " AC3";
    info.codecName = "ac3";
    break;
  case DVD_AUDIO_FORMAT_UNKNOWN_1:
    info.name += " UNKNOWN #1";
    break;
  case DVD_AUDIO_FORMAT_MPEG:
    info.name += " MPEG AUDIO";
    info.codecName = "mp1";
    break;
  case DVD_AUDIO_FORMAT_MPEG2_EXT:
    info.name += " MP2 Ext.";
    info.codecName = "mp2";
    break;
  case DVD_AUDIO_FORMAT_LPCM:
    info.name += " LPCM";
    info.codecName = "pcm";
    break;
  case DVD_AUDIO_FORMAT_UNKNOWN_5:
    info.name += " UNKNOWN #5";
    break;
  case DVD_AUDIO_FORMAT_DTS:
    info.name += " DTS";
    info.codecName = "dts";
    break;
  case DVD_AUDIO_FORMAT_SDDS:
    info.name += " SDDS";
    break;
  default:
    info.name += " Other";
    break;
  }

  switch(audio_attributes.channels + 1)
  {
  case 1:
    info.name += " Mono";
    break;
  case 2:
    info.name += " Stereo";
    break;
  case 6:
    info.name += " 5.1";
    break;
  case 7:
    info.name += " 6.1";
    break;
  default:
    char temp[32];
    sprintf(temp, " %d-chs", audio_attributes.channels + 1);
    info.name += temp;
  }

  StringUtils::TrimLeft(info.name);
}

AudioStreamInfo CDVDInputStreamNavigator::GetAudioStreamInfo(const int iId)
{
  AudioStreamInfo info;
  if (!m_dvdnav)
    return info;

  audio_attr_t audio_attributes;

  if (dvdnav_get_audio_attr(m_dvdnav, iId, &audio_attributes) == DVDNAV_STATUS_OK)
  {
    SetAudioStreamName(info, audio_attributes);

    char lang[3];
    lang[2] = 0;
    lang[1] = (audio_attributes.lang_code & 255);
    lang[0] = (audio_attributes.lang_code >> 8) & 255;

    info.language = g_LangCodeExpander.ConvertToISO6392B(lang);
    info.channels = audio_attributes.channels + 1;
  }

  return info;
}

int CDVDInputStreamNavigator::GetAudioStreamCount()
{
  if (!m_dvdnav)
  {
    return 0;
  }
  return dvdnav_get_number_of_streams(m_dvdnav, DVD_AUDIO_STREAM);
}

int CDVDInputStreamNavigator::GetAngleCount()
{
  if (!m_dvdnav)
    return -1;

  int number_of_angles;
  int current_angle;
  dvdnav_status_t status = dvdnav_get_angle_info(m_dvdnav, &current_angle, &number_of_angles);

  if (status == DVDNAV_STATUS_OK)
    return number_of_angles;
  else
    return -1;
}

int CDVDInputStreamNavigator::GetActiveAngle()
{
  if (!m_dvdnav)
    return -1;

  int number_of_angles;
  int current_angle;
  if (dvdnav_get_angle_info(m_dvdnav, &current_angle, &number_of_angles) == DVDNAV_STATUS_ERR)
  {
    CLog::LogF(LOGERROR, "Failed to get current angle: {}", dvdnav_err_to_string(m_dvdnav));
    return -1;
  }
  return current_angle;
}

bool CDVDInputStreamNavigator::SetAngle(int angle)
{
  if (!m_dvdnav)
    return false;

  dvdnav_status_t status = dvdnav_angle_change(m_dvdnav, angle);

  return (status == DVDNAV_STATUS_OK);
}

bool CDVDInputStreamNavigator::GetCurrentButtonInfo(CDVDOverlaySpu* pOverlayPicture, CDVDDemuxSPU* pSPU, int iButtonType)
{
  int colorAndAlpha[4][4];
  dvdnav_highlight_area_t hl;

  if (!m_dvdnav)
  {
    return false;
  }

  int button = GetCurrentButton();
  if (button < 0)
  {
    return false;
  }

  if (DVDNAV_STATUS_OK == dvdnav_get_highlight_area(
                              dvdnav_get_current_nav_pci(m_dvdnav), button, iButtonType, &hl))
  {
    // button cropping information
    pOverlayPicture->crop_i_x_start = hl.sx;
    pOverlayPicture->crop_i_x_end = hl.ex;
    pOverlayPicture->crop_i_y_start = hl.sy;
    pOverlayPicture->crop_i_y_end = hl.ey;
  }

  if (pSPU->m_bHasClut)
  {
    // get color stored in the highlight area palete using the previously stored clut
    for (unsigned i = 0; i < 4; i++)
    {
      uint8_t* yuvColor = pSPU->m_clut[(hl.palette >> (16 + i * 4)) & 0x0f];
      uint8_t alpha = (((hl.palette >> (i * 4)) & 0x0f));

      colorAndAlpha[i][0] = yuvColor[0];
      colorAndAlpha[i][1] = yuvColor[1];
      colorAndAlpha[i][2] = yuvColor[2];
      colorAndAlpha[i][3] = alpha;
    }

    for (int i = 0; i < 4; i++)
    {
      pOverlayPicture->highlight_alpha[i] = colorAndAlpha[i][3];
      for (int j = 0; j < 3; j++)
        pOverlayPicture->highlight_color[i][j] = colorAndAlpha[i][j];
    }
  }

  return true;
}

int CDVDInputStreamNavigator::GetTotalTime()
{
  //We use buffers of this as they can get called from multiple threads, and could block if we are currently reading data
  return m_iTotalTime;
}

int CDVDInputStreamNavigator::GetTime()
{
  //We use buffers of this as they can get called from multiple threads, and could block if we are currently reading data
  return m_iTime;
}

bool CDVDInputStreamNavigator::PosTime(int iTimeInMsec)
{
  if( dvdnav_jump_to_sector_by_time(m_dvdnav, iTimeInMsec * 90, 0) == DVDNAV_STATUS_ERR )
  {
    CLog::Log(LOGDEBUG, "dvdnav: dvdnav_jump_to_sector_by_time failed( {} )",
              dvdnav_err_to_string(m_dvdnav));
    return false;
  }
  m_iTime = iTimeInMsec;
  return true;
}

bool CDVDInputStreamNavigator::SeekChapter(int iChapter)
{
  if (!m_dvdnav)
    return false;

  // cannot allow to return true in case of buttons (overlays) because otherwise back in VideoPlayer FlushBuffers will remove menu overlays
  // therefore we just skip the request in case there are buttons and return false
  if (IsInMenu() && GetTotalButtons() > 0)
  {
    CLog::Log(LOGDEBUG, "{} - Seeking chapter is not allowed in menu set with buttons",
              __FUNCTION__);
    return false;
  }

  bool enabled = IsSubtitleStreamEnabled();
  int audio    = GetActiveAudioStream();
  int subtitle = GetActiveSubtitleStream();

  if (iChapter == (m_iPart + 1))
  {
    if (dvdnav_next_pg_search(m_dvdnav) == DVDNAV_STATUS_ERR)
    {
      CLog::Log(LOGERROR, "dvdnav: dvdnav_next_pg_search( {} )",
                dvdnav_err_to_string(m_dvdnav));
      return false;
    }
  }
  else if (iChapter == (m_iPart - 1))
  {
    if (dvdnav_prev_pg_search(m_dvdnav) == DVDNAV_STATUS_ERR)
    {
      CLog::Log(LOGERROR, "dvdnav: dvdnav_prev_pg_search( {} )",
                dvdnav_err_to_string(m_dvdnav));
      return false;
    }
  }
  else if (dvdnav_part_play(m_dvdnav, m_iTitle, iChapter) == DVDNAV_STATUS_ERR)
  {
    CLog::Log(LOGERROR, "dvdnav: dvdnav_part_play failed( {} )",
              dvdnav_err_to_string(m_dvdnav));
    return false;
  }

  SetActiveSubtitleStream(subtitle);
  SetActiveAudioStream(audio);
  EnableSubtitleStream(enabled);
  return true;
}

float CDVDInputStreamNavigator::GetVideoAspectRatio()
{
  int iAspect = dvdnav_get_video_aspect(m_dvdnav);
  int iPerm = dvdnav_get_video_scale_permission(m_dvdnav);

  //The video scale permissions should give if the source is letterboxed
  //and such. should be able to give us info that we can zoom in automatically
  //not sure what to do with it currently

  CLog::Log(LOGINFO, "{} - Aspect wanted: {}, Scale permissions: {}", __FUNCTION__, iAspect, iPerm);
  switch(iAspect)
  {
    case 0: //4:3
      return 4.0f / 3.0f;
    case 3: //16:9
      return 16.0f / 9.0f;
    default: //Unknown, use libmpeg2
      return 0.0f;
  }
}

void CDVDInputStreamNavigator::EnableSubtitleStream(bool bEnable)
{
  if (!m_dvdnav)
    return;

  dvdnav_toggle_spu_stream(m_dvdnav, static_cast<uint8_t>(bEnable));
}

bool CDVDInputStreamNavigator::IsSubtitleStreamEnabled()
{
  if (!m_dvdnav)
    return false;

  return dvdnav_get_active_spu_stream(m_dvdnav) >= 0;
}

bool CDVDInputStreamNavigator::FillDVDState(DVDState& dvdState)
{
  if (!m_dvdnav)
  {
    return false;
  }

  if (dvdnav_current_title_program(m_dvdnav, &dvdState.title, &dvdState.pgcn,
                                         &dvdState.pgn) == DVDNAV_STATUS_ERR)
  {
    CLog::LogF(LOGERROR, "Failed to get current title info ({})",
               dvdnav_err_to_string(m_dvdnav));
    return false;
  }

  int current_angle = GetActiveAngle();
  if (current_angle == -1)
  {
    CLog::LogF(LOGERROR, "Could not detect current angle, ignoring saved state");
    return false;
  }
  dvdState.current_angle = current_angle;
  dvdState.audio_num = GetActiveAudioStream();
  dvdState.subp_num = GetActiveSubtitleStream();
  dvdState.sub_enabled = IsSubtitleStreamEnabled();

  return true;
}

bool CDVDInputStreamNavigator::GetState(std::string& xmlstate)
{
  if( !m_dvdnav )
  {
    return false;
  }

  // do not save state if we are not playing a title stream (e.g. if we are in menus)
  if (!dvdnav_is_domain_vts(m_dvdnav))
  {
    return false;
  }

  DVDState dvdState;
  if (!FillDVDState(dvdState))
  {
    CLog::LogF(LOGWARNING, "Failed to obtain current dvdnav state");
    return false;
  }

  if (!m_dvdStateSerializer.DVDStateToXML(xmlstate, dvdState))
  {
    CLog::Log(LOGWARNING,
              "CDVDInputStreamNavigator::SetNavigatorState - Failed to serialize state");
    return false;
  }

  return true;
}

bool CDVDInputStreamNavigator::SetState(const std::string& xmlstate)
{
  if (!m_dvdnav)
    return false;

  DVDState dvdState;
  if (!m_dvdStateSerializer.XMLToDVDState(dvdState, xmlstate))
  {
    CLog::LogF(LOGWARNING, "Failed to deserialize state");
    return false;
  }

  dvdnav_program_play(m_dvdnav, dvdState.title, dvdState.pgcn, dvdState.pgn);
  dvdnav_angle_change(m_dvdnav, dvdState.current_angle);
  SetActiveSubtitleStream(dvdState.subp_num);
  SetActiveAudioStream(dvdState.audio_num);
  EnableSubtitleStream(dvdState.sub_enabled);
  return true;
}

std::string CDVDInputStreamNavigator::GetDVDTitleString()
{
  if (!m_dvdnav)
    return "";

  const char* str = NULL;
  if (dvdnav_get_title_string(m_dvdnav, &str) == DVDNAV_STATUS_OK)
    return str;
  else
    return "";
}

std::string CDVDInputStreamNavigator::GetDVDSerialString()
{
  if (!m_dvdnav)
    return "";

  const char* str = NULL;
  if (dvdnav_get_serial_string(m_dvdnav, &str) == DVDNAV_STATUS_OK)
    return str;
  else
    return "";
}

std::string CDVDInputStreamNavigator::GetDVDVolIdString()
{
  if (!m_dvdnav)
    return "";

  const char* volIdTmp = dvdnav_get_volid_string(m_dvdnav);
  if (volIdTmp)
  {
    std::string volId{volIdTmp};
    free(const_cast<char*>(volIdTmp));
    return volId;
  }
  return "";
}

int64_t CDVDInputStreamNavigator::GetChapterPos(int ch)
{
  if (ch == -1 || ch > GetChapterCount())
    ch = GetChapter();

  std::map<int, std::map<int, int64_t>>::iterator title = m_mapTitleChapters.find(m_iTitle);
  if (title != m_mapTitleChapters.end())
  {
    std::map<int, int64_t>::iterator chapter = title->second.find(ch);
    if (chapter != title->second.end())
      return chapter->second;
  }
  return 0;
}

void CDVDInputStreamNavigator::GetVideoResolution(uint32_t* width, uint32_t* height)
{
  if (!m_dvdnav) return;

  // for version <= 5.0.3 this functions returns 0 instead of DVDNAV_STATUS_OK and -1 instead of DVDNAV_STATUS_ERR
  int status = dvdnav_get_video_resolution(m_dvdnav, width, height);
  if (status == -1)
  {
    CLog::Log(LOGWARNING,
              "CDVDInputStreamNavigator::GetVideoResolution - Failed to get resolution ({})",
              dvdnav_err_to_string(m_dvdnav));
    *width = 0;
    *height = 0;
  }
}

VideoStreamInfo CDVDInputStreamNavigator::GetVideoStreamInfo()
{
  VideoStreamInfo info;
  if (!m_dvdnav)
    return info;

  info.angles = GetAngleCount();
  info.videoAspectRatio = GetVideoAspectRatio();
  uint32_t width = 0;
  uint32_t height = 0;
  GetVideoResolution(&width, &height);

  info.width = static_cast<int>(width);
  info.height = static_cast<int>(height);

  // Until we add get_video_attr or get_video_codec we can't distinguish MPEG-1 (h261)
  // from MPEG-2 (h262). The latter is far more common, so use this.
  info.codecName = "mpeg2";

  return info;
}

int dvd_inputstreamnavigator_cb_seek(void * p_stream, uint64_t i_pos)
{
  CDVDInputStreamFile *lpstream = reinterpret_cast<CDVDInputStreamFile*>(p_stream);
  if (lpstream->Seek(i_pos, SEEK_SET) >= 0)
    return 0;
  else
    return -1;
}

int dvd_inputstreamnavigator_cb_read(void * p_stream, void * buffer, int i_read)
{
  CDVDInputStreamFile *lpstream = reinterpret_cast<CDVDInputStreamFile*>(p_stream);

  int i_ret = 0;
  while (i_ret < i_read)
  {
    int i_r;
    i_r = lpstream->Read(reinterpret_cast<uint8_t *>(buffer) + i_ret, i_read - i_ret);
    if (i_r < 0)
    {
      CLog::Log(LOGERROR,"read error dvd_inputstreamnavigator_cb_read");
      return i_r;
    }
    if (i_r == 0)
      break;

    i_ret += i_r;
  }

  return i_ret;
}

int dvd_inputstreamnavigator_cb_readv(void * p_stream, void * p_iovec, int i_blocks)
{
  // NOTE/TODO: this vectored read callback somehow doesn't seem to be called by libdvdnav.
  // Therefore, the code below isn't really tested, but inspired from the libc_readv code for Win32 in libdvdcss (device.c:713).
  CDVDInputStreamFile *lpstream = reinterpret_cast<CDVDInputStreamFile*>(p_stream);
  const struct iovec* lpiovec = reinterpret_cast<const struct iovec*>(p_iovec);

  int i_index, i_len, i_total = 0;
  unsigned char *p_base;
  int i_bytes;

  for (i_index = i_blocks; i_index; i_index--, lpiovec++)
  {
    i_len = lpiovec->iov_len;
    p_base = reinterpret_cast<unsigned char*>(lpiovec->iov_base);

    if (i_len <= 0)
      continue;

    i_bytes = lpstream->Read(p_base, i_len);
    if (i_bytes < 0)
      return -1;
    else
      i_total += i_bytes;

    if (i_bytes != i_len)
    {
      /* We reached the end of the file or a signal interrupted
      * the read. Return a partial read. */
      int i_seek = lpstream->Seek(i_total,0);
      if (i_seek < 0)
        return i_seek;

      /* We have to return now so that i_pos isn't clobbered */
      return i_total;
    }
  }
  return i_total;
}