File: sector.c

package info (click to toggle)
libmirage 3.2.10-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,540 kB
  • sloc: ansic: 25,454; xml: 108; makefile: 11
file content (1925 lines) | stat: -rw-r--r-- 69,386 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
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
/*
 *  libMirage: sector
 *  Copyright (C) 2006-2014 Rok Mandeljc
 *
 *  This program 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/**
 * SECTION: mirage-sector
 * @title: MirageSector
 * @short_description: Object representing a sector.
 * @see_also: #MirageTrack
 * @include: mirage-sector.h
 *
 * #MirageSector object represents a sector. It provides access to the
 * sector data, generating it if needed.
 */

#include "mirage/config.h"
#include "mirage/mirage.h"

#include <glib/gi18n-lib.h>

#define __debug__ "Sector"


/**********************************************************************\
 *                          Private structure                         *
\**********************************************************************/
struct _MirageSectorPrivate
{
    MirageSectorType type;
    gint address; /* Absolute address of sector */

    gint real_data; /* Which parts of sector data were provided by image */
    gint valid_data; /* Which parts of sector data are valid (either provided by image or generated) */
    guint8 sector_data[2352]; /* Buffer for sector data */
    guint8 subchan_pw[96]; /* Buffer for interleaved PW subchannel */
    guint8 subchan_q[16]; /* Buffer for deinterleaved Q subchannel */
};


/**********************************************************************\
 *                          Private functions                         *
\**********************************************************************/
static gboolean mirage_sector_get_sync_offset_and_length (MirageSector *self, gint *offset, gint *length, GError **error)
{
    /* Sync is supported by all non-audio sectors */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE0:
        case MIRAGE_SECTOR_MODE1:
        case MIRAGE_SECTOR_MODE2:
        case MIRAGE_SECTOR_MODE2_FORM1:
        case MIRAGE_SECTOR_MODE2_FORM2: {
            *offset = 0;
            *length = 12;
            return TRUE;
        }
        default: {
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Sync pattern not available for sector type %d!"), self->priv->type);
            return FALSE;
        }
    }
}

static gboolean mirage_sector_get_header_offset_and_length (MirageSector *self, gint *offset, gint *length, GError **error)
{
    /* Header is supported by all non-audio sectors */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE0:
        case MIRAGE_SECTOR_MODE1:
        case MIRAGE_SECTOR_MODE2:
        case MIRAGE_SECTOR_MODE2_FORM1:
        case MIRAGE_SECTOR_MODE2_FORM2: {
            *offset = 12;
            *length = 4;
            return TRUE;
        }
        default: {
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Header not available for sector type %d!"), self->priv->type);
            return FALSE;
        }
    }
}

static gboolean mirage_sector_get_subheader_offset_and_length (MirageSector *self, gint *offset, gint *length, GError **error)
{
    /* Subheader is supported by formed Mode 2 sectors */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE2_FORM1:
        case MIRAGE_SECTOR_MODE2_FORM2: {
            *offset = 16;
            *length = 8;
            return TRUE;
        }
        default: {
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Subheader not available for sector type %d!"), self->priv->type);
            return FALSE;
        }
    }
}

static gboolean mirage_sector_get_data_offset_and_length (MirageSector *self, gint *offset, gint *length, GError **error)
{
    /* Data is supported by all sectors */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_AUDIO: {
            *offset = 0;
            *length = 2352;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE0: {
            *offset = 16;
            *length = 2336;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE1: {
            *offset = 16;
            *length = 2048;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE2: {
            *offset = 16;
            *length = 2336;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE2_FORM1: {
            *offset = 24;
            *length = 2048;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE2_FORM2: {
            *offset = 24;
            *length = 2324;
            return TRUE;
        }
        default: {
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Data not available for sector type %d!"), self->priv->type);
            return FALSE;
        }
    }
}

static gboolean mirage_sector_get_edc_ecc_offset_and_length (MirageSector *self, gint *offset, gint *length, GError **error)
{
    /* EDC/ECC is supported by Mode 1 and formed Mode 2 sectors */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE1: {
            *offset = 2064;
            *length = 288;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE2_FORM1: {
            *offset = 2072;
            *length = 280;
            return TRUE;
        }
        case MIRAGE_SECTOR_MODE2_FORM2: {
            *offset = 2348;
            *length = 4;
            return TRUE;
        }
        default: {
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("EDC/ECC not available for sector type %d!"), self->priv->type);
            return FALSE;
        }
    }
}


static gboolean mirage_sector_get_info_for_feed_or_extract (MirageSector *self, gint main_data_length, gint *data_offset, gint *real_data, GError **error)
{
    *data_offset = 0;
    *real_data = 0;

    switch (self->priv->type) {
        case MIRAGE_SECTOR_AUDIO: {
            /* Audio sector structure: data (2352) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2352: {
                    /* Audio data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    /* We mark the rest as valid as well, so that we don't need
                       additional checks in fake data generation code */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_EDC_ECC;
                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Audio sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Audio sector!"), main_data_length);
                    return FALSE;
                }
            }
            break;
        }
        case MIRAGE_SECTOR_MODE0: {
            /* Mode 0 sector structue:
                sync (12) + header (4) + data (2336) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2336: {
                    /* Data only */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2340: {
                    /* Data + header */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2352: {
                    /* Sync + header + data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 0 sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 0 sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        case MIRAGE_SECTOR_MODE1: {
            /* Mode 1 sector structue:
                sync (12) + header (4) + data (2048) + EDC/ECC (288) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2048: {
                    /* Data only */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2052: {
                    /* Header + data */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2064: {
                    /* Sync + header + data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2336: {
                    /* Data + EDC/ECC */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2340: {
                    /* Header + data + EDC/ECC */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2352: {
                    /* Sync + header + data + EDC/ECC */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 1 sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 1 sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        case MIRAGE_SECTOR_MODE2: {
            /* Mode 2 formless sector structue:
                sync (12) + header (4) + data (2336) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2336: {
                    /* Data only */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2340: {
                    /* Header + data */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2352: {
                    /* Sync + header + data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 2 Formless sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 2 Formless sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        case MIRAGE_SECTOR_MODE2_FORM1: {
            /* Mode 2 Form 1 sector structue:
                sync (12) + header (4) + subheader (8) + data (2048) + EDC/ECC (280) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2048: {
                    /* Data only */
                    *data_offset = 12 + 4 + 8; /* Offset: sync + header + subheader */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2056: {
                    /* Subheader + data */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2060: {
                    /* Header + subheader + data */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2072: {
                    /* Sync + header + subheader + data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2328: {
                    /* Data + EDC/ECC */
                    *data_offset = 12 + 4 + 8; /* Offset: sync + header + subheader */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2336: {
                    /* Subheader + data + EDC/ECC */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2340: {
                    /* Header + subheader + data + EDC/ECC */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2352: {
                    /* Sync + header + subheader + data + EDC/ECC */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 2 Form 1 sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 2 Form 1 sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        case MIRAGE_SECTOR_MODE2_FORM2: {
            /* Mode 2 Form 2 sector structue:
                sync (12) + header (4) + subheader (8) + data (2324) + EDC/ECC (4) */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2324: {
                    /* Data only */
                    *data_offset = 12 + 4 + 8; /* Offset: sync + header + subheader */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2332: {
                    /* Subheader + data */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }

                #if FALSE
                /* This one yields same size as subheader + data + EDC/ECC,
                   which is actually used, while this one most likely isn't. */
                case 2336: {
                    /* Header + subheader + data */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                #endif

                case 2348: {
                    /* Sync + header + subheader + data */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                }
                case 2328: {
                    /* Data + EDC/ECC */
                    *data_offset = 12 + 4 + 8; /* Offset: sync + header + subheader */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2336: {
                    /* Subheader + data + EDC/ECC */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2340: {
                    /* Header + subheader + data + EDC/ECC */
                    *data_offset = 12; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2352: {
                    /* Sync + header + subheader + data + EDC/ECC */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 2 Form 2 sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 2 Form 2 sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        case MIRAGE_SECTOR_MODE2_MIXED: {
            /* Mode 2 Mixed consists of both Mode 2 Form 1 and Mode 2 Form 2
               sectors, which are distinguished by subheader. In addition to
               having to provide subheader data, both Form 1 and Form 2 sectors
               must be of same size; this is true only if at least subheader,
               data and EDC/ECC are provided */
            switch (main_data_length) {
                case 0: {
                    /* Nothing; pregap */
                    break;
                }
                case 2332:
                    /* This one's a special case; it is same as 2336, except
                       that last four bytes (for Form 2 sectors, that's optional
                       EDC, and for Form 1 sectors, it's last four bytes of ECC)
                       are omitted. Therefore, we need to re-generate
                       the EDC/ECC code */

                    /* Subheader + data (+ EDC/ECC) */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;

                    break;
                case 2336: {
                    /* Subheader + data + EDC/ECC */
                    *data_offset = 12 + 4; /* Offset: sync + header */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2340: {
                    /* Header + subheader + data + EDC/ECC */
                    *data_offset = 12 + 4; /* Offset: sync */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                case 2352: {
                    /* Sync + header + subheader + data + EDC/ECC */
                    *data_offset = 0; /* Offset: 0 */

                    /* Valid */
                    *real_data |= MIRAGE_VALID_SYNC;
                    *real_data |= MIRAGE_VALID_HEADER;
                    *real_data |= MIRAGE_VALID_SUBHEADER;
                    *real_data |= MIRAGE_VALID_DATA;
                    *real_data |= MIRAGE_VALID_EDC_ECC;

                    break;
                }
                default: {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: unhandled sector size %d for Mode 2 Mixed sector!\n", __debug__, main_data_length);
                    g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Unhandled sector size %d for Mode 2 Mixed sector!"), main_data_length);
                    return FALSE;
                }
            }

            break;
        }
        default: {
            /* Raw sector type; nothing to do */
            break;
        }
    }

    return TRUE;
}


static void mirage_sector_generate_subchannel (MirageSector *self);

static void mirage_sector_generate_sync (MirageSector *self)
{
    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating sync\n", __debug__);

    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE0:
        case MIRAGE_SECTOR_MODE1:
        case MIRAGE_SECTOR_MODE2:
        case MIRAGE_SECTOR_MODE2_FORM1:
        case MIRAGE_SECTOR_MODE2_FORM2: {
            memcpy(self->priv->sector_data, mirage_pattern_sync, 12);
            break;
        }
        default: {
            return;
        }
    }

    self->priv->valid_data |= MIRAGE_VALID_SYNC;
}

static void mirage_sector_generate_header (MirageSector *self)
{
    guint8 *header = self->priv->sector_data+12;

    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating header\n", __debug__);

    /* Set mode */
    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE0: {
            header[3] = 0; /* Mode = 0 */
            break;
        }
        case MIRAGE_SECTOR_MODE1: {
            header[3] = 1; /* Mode = 1 */
            break;
        }
        case MIRAGE_SECTOR_MODE2:
        case MIRAGE_SECTOR_MODE2_FORM1:
        case MIRAGE_SECTOR_MODE2_FORM2: {
            header[3] = 2; /* Mode = 2 */
            break;
        }
        default: {
            return;
        }
    }

    /* Address */
    mirage_helper_lba2msf(self->priv->address, TRUE, &header[0], &header[1], &header[2]);
    header[0] = mirage_helper_hex2bcd(header[0]);
    header[1] = mirage_helper_hex2bcd(header[1]);
    header[2] = mirage_helper_hex2bcd(header[2]);

    self->priv->valid_data |= MIRAGE_VALID_HEADER;
}

static void mirage_sector_generate_subheader (MirageSector *self)
{
    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating subheader\n", __debug__);

    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE2_FORM1: {
            guint8 *subheader = self->priv->sector_data+16;
            subheader[2] |= (0 << 5); /* Form 1 */
            subheader[5] = subheader[2];
            break;
        }
        case MIRAGE_SECTOR_MODE2_FORM2: {
            guint8 *subheader = self->priv->sector_data+16;
            subheader[2] |= (1 << 5); /* Form 2 */
            subheader[5] = subheader[2];
            break;
        }
        default: {
            return;
        }
    }

    self->priv->valid_data |= MIRAGE_VALID_SUBHEADER;
}

static void mirage_sector_generate_data (MirageSector *self)
{
    gint offset = 0;
    gint length = 0;

    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: \"generating\" (clearing) user data\n", __debug__);

    mirage_sector_get_data_offset_and_length(self, &offset, &length, NULL);
    memset(self->priv->sector_data + offset, 0, length);

    self->priv->valid_data |= MIRAGE_VALID_DATA;
}

static void mirage_sector_generate_edc_ecc (MirageSector *self)
{
    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating EDC/ECC\n", __debug__);

    /* If user data is not set, make sure we have cleared it! */
    if (!(self->priv->valid_data & MIRAGE_VALID_DATA)) {
        mirage_sector_generate_data(self);
    }

    switch (self->priv->type) {
        case MIRAGE_SECTOR_MODE1: {
            /* EDC/ECC are generated over sync, header and data in Mode 1 sectors...
               so make sure we have those */
            if (!(self->priv->valid_data & MIRAGE_VALID_SYNC)) {
                mirage_sector_generate_sync(self);
            }
            if (!(self->priv->valid_data & MIRAGE_VALID_HEADER)) {
                mirage_sector_generate_header(self);
            }

            /* Generate EDC */
            mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x00, 0x810, self->priv->sector_data+0x810);
            /* Generate ECC P/Q codes */
            mirage_helper_sector_edc_ecc_compute_ecc_block(self->priv->sector_data+0xC, 86, 24, 2, 86, self->priv->sector_data+0x81C); /* P */
            mirage_helper_sector_edc_ecc_compute_ecc_block(self->priv->sector_data+0xC, 52, 43, 86, 88, self->priv->sector_data+0x8C8); /* Q */

            break;
        }
        case MIRAGE_SECTOR_MODE2_FORM1: {
            guint8 tmp_header[4];
            /* Zero the header, because it is not supposed to be included in the
               calculation; copy, calculate, then copy back */
            memcpy(tmp_header, self->priv->sector_data+12, 4);
            memset(self->priv->sector_data+12, 0, 4);
            /* Generate EDC */
            mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x10, 0x808, self->priv->sector_data+0x818);
            /* Generate ECC P/Q codes */
            mirage_helper_sector_edc_ecc_compute_ecc_block(self->priv->sector_data+0xC, 86, 24, 2, 86, self->priv->sector_data+0x81C); /* P */
            mirage_helper_sector_edc_ecc_compute_ecc_block(self->priv->sector_data+0xC, 52, 43, 86, 88, self->priv->sector_data+0x8C8); /* Q */
            /* Unzero */
            memcpy(self->priv->sector_data+12, tmp_header, 4);

            break;
        }
        case MIRAGE_SECTOR_MODE2_FORM2: {
            /* Compute EDC */
            mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x10, 0x91C, self->priv->sector_data+0x92C);

            break;
        }
        default: {
            return;
        }
    }

    self->priv->valid_data |= MIRAGE_VALID_EDC_ECC;
}


/**********************************************************************\
 *                             Public API                             *
\**********************************************************************/
/**
 * mirage_sector_feed_data:
 * @self: a #MirageSector
 * @address: (in): absolute disc address the sector represents. Given in sectors.
 * @type: (in): track type (one of #MirageSectorType)
 * @main_data: (in): main data buffer
 * @main_data_length: (in): length of data in main data buffer
 * @subchannel_format: (in): subchannel data format
 * @subchannel_data: (in) (allow-none): subchannel data buffer
 * @subchannel_data_length: (in): length of data in subchannel data buffer
 * @ignore_data_mask: (in): a mask of #MirageSectorValidData values, indicating which parts of main channel sector data, if any, should be ignored and regerated even though they are provided by the data feed
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Feeds data to sector. If @type is %MIRAGE_SECTOR_RAW or %MIRAGE_SECTOR_RAW_SCRAMBLED,
 * the real sector type is determined during feeding.
 *
 * <note>
 * Intended for internal use.
 * </note>
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_feed_data (MirageSector *self, gint address, MirageSectorType type, const guint8 *main_data, guint main_data_length, MirageSectorSubchannelFormat subchannel_format, const guint8 *subchannel_data, guint subchannel_data_length, gint ignore_data_mask, GError **error)
{
    gint data_offset;

    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: feeding: address: %Xh (%d), type: %d, main channel data size: %d, subchannel data size: %d\n", __debug__, address, address, type, main_data_length, subchannel_data_length);

    /* Reset data validity flags */
    self->priv->real_data = self->priv->valid_data = 0;

    /* Store address and sector type */
    self->priv->address = address;
    self->priv->type = type;

    /* If type is raw or scrambled raw, we copy data first and determine
       sector type from it. Then we use the main switch to fill in the
       valid data flags for us, and avoid copying the data again. */
    if (type == MIRAGE_SECTOR_RAW || type == MIRAGE_SECTOR_RAW_SCRAMBLED) {
        if (main_data_length != 2352) {
            MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: raw sectors require 2352 bytes of data!\n", __debug__);
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Raw sectors require 2352 bytes of data!"));
            return FALSE;
        }

        /* Copy data from buffer */
        memcpy(self->priv->sector_data, main_data, main_data_length);

        /* We can easily recognise an audio sector by the lack of sync
           pattern at the beginning */
        if (!memcmp(self->priv->sector_data, mirage_pattern_sync, sizeof(mirage_pattern_sync))) {
            /* Data sector; unscramble if necessary */
            if (type == MIRAGE_SECTOR_RAW_SCRAMBLED) {
                mirage_sector_scramble(self);
            }

            /* Determine sector type */
            self->priv->type = mirage_helper_determine_sector_type(self->priv->sector_data);
        } else {
            /* Audio sector */
            self->priv->type = MIRAGE_SECTOR_AUDIO;
        }
    }

    /* Now, determine offset and real data flags based on type and main channel data length */
    if (!mirage_sector_get_info_for_feed_or_extract(self, main_data_length, &data_offset, &self->priv->real_data, error)) {
        return FALSE;
    }

    /* Copy data (skip if initial sector type was raw) */
    if (type != MIRAGE_SECTOR_RAW && type != MIRAGE_SECTOR_RAW_SCRAMBLED) {
        memcpy(self->priv->sector_data+data_offset, main_data, main_data_length);
    }

    /* Now, if we had Mode 2 Mixed, we can determine whether we have
       Mode 2 Form 1 or Mode 2 Form 2 */
    if (self->priv->type == MIRAGE_SECTOR_MODE2_MIXED) {
        /* Check the subheader... */
        if (self->priv->sector_data[18] & 0x20) {
            self->priv->type = MIRAGE_SECTOR_MODE2_FORM2;
        } else {
            self->priv->type = MIRAGE_SECTOR_MODE2_FORM1;
        }
    }

    /* Mask the real_data with ignore_data_mask, to force re-generation
       of masked parts of sector data */
    self->priv->real_data &= ~ignore_data_mask;

    /* At this point, real_data field indicates which parts of sector
       data were provided by the image file; make a copy of this field
       in valid_data field, which will be modified when the missing data
       is generated */
    self->priv->valid_data = self->priv->real_data;

    /* Subchannel; use sector's function to set it */
    if (subchannel_data_length && subchannel_data) {
        if (!mirage_sector_set_subchannel(self, subchannel_format, subchannel_data, subchannel_data_length, error)) {
            return FALSE;
        }
    }

    return TRUE;
}

/**
 * mirage_sector_extract_data:
 * @self: a #MirageSector
 * @main_data: (out) (transfer none): location to store pointer to main data buffer
 * @main_data_length: (in): requested length of data in main data buffer
 * @subchannel_format: (out): requested subchannel data format
 * @subchannel_data: (in) (transfer none) (allow-none): location to store pointer to subchannel data buffer, or %NULL
 * @subchannel_data_length: (in): requested length of data in subchannel data buffer
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Extracts data from sector. Which parts of main channel data are extracted
 * depends on provided @main_data_length.
 *
 * <note>
 * Intended for internal use.
 * </note>
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_extract_data (MirageSector *self, const guint8 **main_data, guint main_data_length, MirageSectorSubchannelFormat subchannel_format, const guint8 **subchannel_data, guint subchannel_data_length, GError **error)
{
    gint data_offset, required_data;
    gint actual_subchannel_length;

    /* Determine offset and real data flags based on type and main channel data length */
    if (!mirage_sector_get_info_for_feed_or_extract(self, main_data_length, &data_offset, &required_data, error)) {
        return FALSE;
    }

    /* Ensure that all required data is available */
    gint need_to_generate = (required_data ^ self->priv->valid_data) & required_data;
    if (need_to_generate & MIRAGE_VALID_SYNC) {
        mirage_sector_generate_sync(self);
    }
    if (need_to_generate & MIRAGE_VALID_HEADER) {
        mirage_sector_generate_header(self);
    }
    if (need_to_generate & MIRAGE_VALID_SUBHEADER) {
        mirage_sector_generate_subheader(self);
    }
    if (need_to_generate & MIRAGE_VALID_DATA) {
        mirage_sector_generate_data(self);
    }
    if (need_to_generate & MIRAGE_VALID_EDC_ECC) {
        mirage_sector_generate_edc_ecc(self);
    }

    /* Return pointer to main data buffer */
    *main_data = self->priv->sector_data + data_offset;

    /* Subchannel */
    if (!mirage_sector_get_subchannel(self, subchannel_format, subchannel_data, &actual_subchannel_length, error)) {
        return FALSE;
    }

    if (actual_subchannel_length != subchannel_data_length) {
        MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: requested subchannel size (%d) and actual subchannel size (%d) mismatch!\n", __debug__, subchannel_data_length, actual_subchannel_length);
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Requested subchannel size (%d) and actual subchannel size (%d) mismatch!"), subchannel_data_length, actual_subchannel_length);
        return FALSE;
    }

    return TRUE;
}


/**
 * mirage_sector_get_sector_type:
 * @self: a #MirageSector
 *
 * Retrieves sector type (track mode); one of #MirageSectorType.
 *
 * Returns: sector type (track mode)
 */
MirageSectorType mirage_sector_get_sector_type (MirageSector *self)
{
    /* Return sector type */
    return self->priv->type;
}

/**
 * mirage_sector_get_address:
 * @self: a #MirageSector
 *
 * Retrieves absolute disc address of the sector.
 *
 * Returns: sector address
 */
gint mirage_sector_get_address (MirageSector *self)
{
    /* Return sector address */
    return self->priv->address;
}


/**
 * mirage_sector_get_sync:
 * @self: a #MirageSector
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing sync pattern, or %NULL
 * @ret_len: (out) (allow-none): location to store length of sync pattern, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's sync pattern. The pointer to appropriate location in
 * sector's data buffer is stored into @ret_buf; therefore, the buffer should not
 * be modified.
 *
 * If sync pattern is not provided by image file(s), it is generated.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_sync (MirageSector *self, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    gboolean succeeded;
    gint offset = 0, length = 0;

    /* Generate sync if it's not provided; generation routine takes care of
       incompatible sector types */
    if (!(self->priv->valid_data & MIRAGE_VALID_SYNC)) {
        mirage_sector_generate_sync(self);
    }

    /* Get offset and length */
    succeeded = mirage_sector_get_sync_offset_and_length(self, &offset, &length, error);

    /* Return the requested data */
    if (ret_buf) {
        *ret_buf = succeeded ? self->priv->sector_data + offset : NULL;
    }
    if (ret_len) {
        *ret_len = succeeded ? length : 0;
    }

    return succeeded;
}

/**
 * mirage_sector_set_sync:
 * @self: a #MirageSector
 * @buf: (in) (array length=len): buffer containing sync pattern
 * @len: (in): length of sync pattern
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's sync pattern to that stored in @buf.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_sync (MirageSector *self, const guint8 *buf, gint len, GError **error)
{
    gint offset, expected_length;

    /* Get offset and length */
    if (!mirage_sector_get_sync_offset_and_length(self, &offset, &expected_length, error)) {
        return FALSE;
    }

    /* Validate length */
    if (len != expected_length) {
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected %d bytes for sync pattern!"), expected_length);
        return FALSE;
    }

    /* Copy */
    memcpy(self->priv->sector_data + offset, buf, len);

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_SYNC;
    self->priv->valid_data |= MIRAGE_VALID_SYNC;

    return TRUE;
}


/**
 * mirage_sector_get_header:
 * @self: a #MirageSector
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing header, or %NULL
 * @ret_len: (out) (allow-none): location to store length of header, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's header. The pointer to appropriate location in
 * sector's data buffer is stored into @ret_buf; therefore, the buffer should not
 * be modified.
 *
 * If header is not provided by image file(s), it is generated.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_header (MirageSector *self, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    gboolean succeeded;
    gint offset = 0, length = 0;

    /* Generate header if it's not provided; generation routine takes care of
       incompatible sector types */
    if (!(self->priv->valid_data & MIRAGE_VALID_HEADER)) {
        mirage_sector_generate_header(self);
    }

    /* Get offset and length */
    succeeded = mirage_sector_get_header_offset_and_length(self, &offset, &length, error);

    /* Return the requested data */
    if (ret_buf) {
        *ret_buf = succeeded ? self->priv->sector_data + offset : NULL;
    }
    if (ret_len) {
        *ret_len = succeeded ? length : 0;
    }

    return succeeded;
}

/**
 * mirage_sector_set_header:
 * @self: a #MirageSector
 * @buf: (in) (array length=len): buffer containing header
 * @len: (in): length of header
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's header to that stored in @buf.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_header (MirageSector *self, const guint8 *buf, gint len, GError **error)
{
    gint offset, expected_length;

    /* Get offset and length */
    if (!mirage_sector_get_header_offset_and_length(self, &offset, &expected_length, error)) {
        return FALSE;
    }

    /* Validate length */
    if (len != expected_length) {
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected %d bytes for header!"), expected_length);
        return FALSE;
    }

    /* Copy */
    memcpy(self->priv->sector_data + offset, buf, len);

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_HEADER;
    self->priv->valid_data |= MIRAGE_VALID_HEADER;

    return TRUE;
}


/**
 * mirage_sector_get_subheader:
 * @self: a #MirageSector
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing subheader, or %NULL
 * @ret_len: (out) (allow-none): location to store length of subheader, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's subheader. The pointer to appropriate location in
 * sector's data buffer is stored into @ret_buf;  therefore, the buffer should not
 * be modified.
 *
 * If subheader is not provided by image file(s), it is generated.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_subheader (MirageSector *self, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    gboolean succeeded;
    gint offset = 0, length = 0;

    /* Generate subheader if it's not provided; generation routine takes care of
       incompatible sector types */
    if (!(self->priv->valid_data & MIRAGE_VALID_SUBHEADER)) {
        mirage_sector_generate_subheader(self);
    }

    /* Get offset and length */
    succeeded = mirage_sector_get_subheader_offset_and_length(self, &offset, &length, error);

    /* Return the requested data */
    if (ret_buf) {
        *ret_buf = succeeded ? self->priv->sector_data + offset : NULL;
    }
    if (ret_len) {
        *ret_len = succeeded ? length : 0;
    }

    return succeeded;
}

/**
 * mirage_sector_set_subheader:
 * @self: a #MirageSector
 * @buf: (in) (array length=len): buffer containing subheader
 * @len: (in): length of subheader
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's subheader to that stored in @buf.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_subheader (MirageSector *self, const guint8 *buf, gint len, GError **error)
{
    gint offset, expected_length;

    /* Get offset and length */
    if (!mirage_sector_get_subheader_offset_and_length(self, &offset, &expected_length, error)) {
        return FALSE;
    }

    /* Validate length */
    if (len == expected_length) {
        /* Copy */
        memcpy(self->priv->sector_data + offset, buf, len);
    } else if (expected_length == 8 && len == 4) {
        /* This is valid as well; make two copies */
        memcpy(self->priv->sector_data + offset, buf, len);
        memcpy(self->priv->sector_data + offset + 4, buf, len);
    } else {
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected %d bytes for subheader!"), expected_length);
        return FALSE;
    }

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_SUBHEADER;
    self->priv->valid_data |= MIRAGE_VALID_SUBHEADER;

    return TRUE;
}


/**
 * mirage_sector_get_data:
 * @self: a #MirageSector
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing user data, or %NULL
 * @ret_len: (out) (allow-none): location to store length of user data, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's user data. The pointer to appropriate location in
 * sector's data buffer is stored into @ret_buf;  therefore, the buffer should not
 * be modified.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_data (MirageSector *self, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    gboolean succeeded;
    gint offset = 0, length = 0;

    /* If user data is not available, make sure that it is blank */
    if (!(self->priv->valid_data & MIRAGE_VALID_DATA)) {
        mirage_sector_generate_data(self);
    }

    /* Get offset and length */
    succeeded = mirage_sector_get_data_offset_and_length(self, &offset, &length, error);

    /* Return the requested data */
    if (ret_buf) {
        *ret_buf = succeeded ? self->priv->sector_data + offset : NULL;
    }
    if (ret_len) {
        *ret_len = succeeded ? length : 0;
    }

    return succeeded;
}

/**
 * mirage_sector_set_data:
 * @self: a #MirageSector
 * @buf: (in) (array length=len): buffer containing user data
 * @len: (in): length of user data
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's user data to that stored in @buf.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_data (MirageSector *self, const guint8 *buf, gint len, GError **error)
{
    gint offset, expected_length;

    /* Get offset and length */
    if (!mirage_sector_get_data_offset_and_length(self, &offset, &expected_length, error)) {
        return FALSE;
    }

    /* Validate length */
    if (len != expected_length) {
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected %d bytes for data!"), expected_length);
        return FALSE;
    }

    /* Copy */
    memcpy(self->priv->sector_data + offset, buf, len);

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_DATA;
    self->priv->valid_data |= MIRAGE_VALID_DATA;

    return TRUE;
}

/**
 * mirage_sector_get_edc_ecc:
 * @self: a #MirageSector
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing EDC/ECC data, or %NULL
 * @ret_len: (out) (allow-none): location to store length of EDC/ECC data, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's EDC/ECC data. The pointer to appropriate location in
 * sector's data buffer is stored into @ret_buf;  therefore, the buffer should not
 * be modified.
 *
 * If EDC/ECC data is not provided by image file(s), it is generated.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_edc_ecc (MirageSector *self, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    gboolean succeeded;
    gint offset = 0, length = 0;

    /* Generate EDC/ECC if it's not provided; generation routine takes care of
       incompatible sector types */
    if (!(self->priv->valid_data & MIRAGE_VALID_EDC_ECC)) {
        mirage_sector_generate_edc_ecc(self);
    }

    /* Get offset and length */
    succeeded = mirage_sector_get_edc_ecc_offset_and_length(self, &offset, &length, error);

    /* Return the requested data */
    if (ret_buf) {
        *ret_buf = succeeded ? self->priv->sector_data + offset : NULL;
    }
    if (ret_len) {
        *ret_len = succeeded ? length : 0;
    }

    return succeeded;
}

/**
 * mirage_sector_set_edc_ecc:
 * @self: a #MirageSector
 * @buf: (in) (array length=len): buffer containing EDC/ECC data
 * @len: (in): length of EDC/ECC data
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's EDC/ECC data to that stored in @buf.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_edc_ecc (MirageSector *self, const guint8 *buf, gint len, GError **error)
{
    gint offset, expected_length;

    /* Get offset and length */
    if (!mirage_sector_get_edc_ecc_offset_and_length(self, &offset, &expected_length, error)) {
        return FALSE;
    }

    /* Validate length */
    if (len != expected_length) {
        g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected %d bytes for EDC/ECC!"), expected_length);
        return FALSE;
    }

    /* Copy */
    memcpy(self->priv->sector_data + offset, buf, len);

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_EDC_ECC;
    self->priv->valid_data |= MIRAGE_VALID_EDC_ECC;

    return TRUE;
}

/**
 * mirage_sector_get_subchannel:
 * @self: a #MirageSector
 * @format: (in): subchannel format
 * @ret_buf: (out) (transfer none) (allow-none) (array length=ret_len): location to store pointer to buffer containing subchannel, or %NULL
 * @ret_len: (out) (allow-none): location to store length of subchannel data, or %NULL. Length is given in bytes.
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Retrieves sector's subchannel. @format must be one of #MirageSectorSubchannelFormat.
 * The pointer to appropriate location in sector's data buffer is stored into
 * @ret_buf;  therefore, the buffer should not be modified.
 *
 * If subchannel is not provided by image file(s), it is generated.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_get_subchannel (MirageSector *self, MirageSectorSubchannelFormat format, const guint8 **ret_buf, gint *ret_len, GError **error)
{
    /* Generate subchannel if it's not provided */
    if (!(self->priv->valid_data & MIRAGE_VALID_SUBCHAN)) {
        mirage_sector_generate_subchannel(self);
    }

    switch (format) {
        case MIRAGE_SUBCHANNEL_NONE: {
            /* No subchannel */
            if (ret_buf) {
                *ret_buf = NULL;
            }
            if (ret_len) {
                *ret_len = 0;
            }
            break;
        }
        case MIRAGE_SUBCHANNEL_PW: {
            /* Interleaved PW subchannel */
            if (ret_buf) {
                *ret_buf = self->priv->subchan_pw;
            }
            if (ret_len) {
                *ret_len = 96;
            }
            break;
        }
        case MIRAGE_SUBCHANNEL_Q: {
            /* De-interleaved Q subchannel */
            memset(self->priv->subchan_q, 0, sizeof(self->priv->subchan_q));
            mirage_helper_subchannel_deinterleave(SUBCHANNEL_Q, self->priv->subchan_pw, self->priv->subchan_q);
            if (ret_buf) {
                *ret_buf = self->priv->subchan_q;
            }
            if (ret_len) {
                *ret_len = 16;
            }
            break;
        }
        default: {
            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: subchannel format %d not supported yet!\n", __debug__, format);
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Subchannel format %d not supported yet!"), format);
            return FALSE;
        }
    }

    return TRUE;
}

/**
 * mirage_sector_set_subchannel:
 * @self: a #MirageSector
 * @format: (in): subchannel format
 * @buf: (in) (array length=len): buffer containing subchannel data
 * @len: (in): length of subchannel data
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Sets sector's subchannel data to that stored in @buf. @format must be
 * one of #MirageSectorSubchannelFormat.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean mirage_sector_set_subchannel (MirageSector *self, MirageSectorSubchannelFormat format, const guint8 *buf, gint len, GError **error)
{
    switch (format) {
        case MIRAGE_SUBCHANNEL_PW: {
            /* Interleaved PW subchannel */
            if (len != 96) {
                g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected 96 bytes for PW subchannel!"));
                return FALSE;
            }
            /* Copy */
            memcpy(self->priv->subchan_pw, buf, len);
            break;
        }
        case MIRAGE_SUBCHANNEL_Q: {
            /* De-interleaved Q subchannel */
            if (len != 16) {
                g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Expected 16 bytes for Q subchannel!"));
                return FALSE;
            }
            /* Interleave Q (first 12 bytes) */
            memset(self->priv->subchan_pw, 0, sizeof(self->priv->subchan_pw));
            mirage_helper_subchannel_interleave(SUBCHANNEL_Q, buf, self->priv->subchan_pw);

            /* Byte 15 actually has P state in its most-significant bit
               (but only if sectors are fed from recording code; when
               reading, P bit is not returned) */
            if (buf[15]) {
                const guint8 p_subchannel[12] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
                mirage_helper_subchannel_interleave(SUBCHANNEL_P, p_subchannel, self->priv->subchan_pw);
            }

            break;
        }
        default: {
            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: subchannel format %d not supported yet!\n", __debug__, format);
            g_set_error(error, MIRAGE_ERROR, MIRAGE_ERROR_SECTOR_ERROR, Q_("Subchannel format %d not supported yet!"), format);
            return FALSE;
        }
    }

    /* Mark as both real and valid */
    self->priv->real_data |= MIRAGE_VALID_SUBCHAN;
    self->priv->valid_data |= MIRAGE_VALID_SUBCHAN;

    return TRUE;
}


/**
 * mirage_sector_verify_lec:
 * @self: a #MirageSector
 *
 * Verifies the sector data in terms of L-EC error detection/correction.
 * Data sectors (Mode 1, Mode 2 Form 1 and Mode 2 Form 2) contain error
 * detection/error correction codes which is part of so called layered
 * error correction. This function calculates the EDC for sector data and
 * compares it with EDC provided by the image file.
 *
 * As a result of comparison, the sectors with intentionally faulty EDC
 * (and possibly ECC, though ECC is not verified) can be discovered.
 *
 * This function requires EDC/ECC data to be provided by the image. If it
 * is not provided, it would be generated by #MirageSector on first access
 * via mirage_sector_get_edc_ecc() using the same algorithm as the one used
 * by this function. Therefore, in case of EDC/ECC data missing, the verification
 * automatically succeeds.
 *
 * Returns: %TRUE if sector passes verification (i.e. no L-EC errors are detected) otherwise %FALSE
 */
gboolean mirage_sector_verify_lec (MirageSector *self)
{
    gboolean valid = TRUE;

    /* Validation is possible only if EDC/ECC data was provided by the
       image file; if it is missing, it is generated by same algorithm
       as used in verification. */
    if (self->priv->real_data & MIRAGE_VALID_EDC_ECC) {
        /* I believe calculating EDC suffices for this test; ECC should
           not really be needed, since we won't be doing any corrections */
        guint8 computed_edc[4];

        switch (self->priv->type) {
            case MIRAGE_SECTOR_MODE1: {
                /* We assume sync and header data are available, which is probably
                   a reasonable assumption at this point... */
                mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x00, 0x810, computed_edc);
                valid = !memcmp(computed_edc, self->priv->sector_data+0x810, 4);
                break;
            }
            case MIRAGE_SECTOR_MODE2_FORM1: {
                /* We assume subheader data is available... */
                mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x10, 0x808, computed_edc);
                valid = !memcmp(computed_edc, self->priv->sector_data+0x818, 4);
                break;
            }
            case MIRAGE_SECTOR_MODE2_FORM2: {
                /* We assume subheader data is available... */
                mirage_helper_sector_edc_ecc_compute_edc_block(self->priv->sector_data+0x10, 0x91C, computed_edc);
                valid = !memcmp(computed_edc, self->priv->sector_data+0x92C, 4);
                break;
            }
            default: {
                break; /* Succeed for other sector types */
            }
        }
    }

    return valid;
}


/**
 * mirage_sector_verify_subchannel_crc:
 * @self: a #MirageSector
 *
 * Verifies the Q subchannel's CRC for the sector.
 *
 * As a result of comparison, the sectors with intentionally faulty Q subchannel
 * can be discovered.
 *
 * This function requires subchannel data to be provided by the image. If it
 * is not provided, it would be generated by #MirageSector on first access
 * via mirage_sector_get_subchannel() using the same algorithm as the one used
 * by this function. Therefore, in case of subchannel data missing, the verification
 * automatically succeeds.
 *
 * Returns: %TRUE if sector's Q subchannel CRC passes verification otherwise %FALSE
 */
gboolean mirage_sector_verify_subchannel_crc (MirageSector *self)
{
    gboolean valid = TRUE;

    /* Validation is possible only if subchannel data was provided by the
       image file; if it is missing, it is generated by same algorithm
       as used in verification. */
    if (self->priv->real_data & MIRAGE_VALID_SUBCHAN) {
        guint16 computed_crc;
        const guint8 *buf;
        gint buflen;

        /* Get Q subchannel */
        mirage_sector_get_subchannel(self, MIRAGE_SUBCHANNEL_Q, &buf, &buflen, NULL);

        /* Compute CRC */
        computed_crc = mirage_helper_subchannel_q_calculate_crc(&buf[0]);

        /* Compare */
        valid = computed_crc == ((buf[10] << 8) | buf[11]);
    }

    return valid;
}


/**
 * mirage_sector_scramble:
 * @self: a #MirageSector
 *
 * Scrambles 2340 bytes of sector data after sync pattern, using scrambler
 * from ECMA-130 Annex B. Running this function on already-scrambled
 * sector results in unscrambling.
 */
void mirage_sector_scramble (MirageSector *self)
{
    /* Make sure scrambler LUT is initialized */
    if (!ecma_130_scrambler_lut) {
        MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: cannot scramble sector - scrambler LUT not initialized!\n", __debug__);
        return;
    }

    for (gint i = 0; i < 2340; i++) {
        *(self->priv->sector_data + 12 + i) ^= ecma_130_scrambler_lut[i];
    }
}


/**********************************************************************\
 *                             Object init                            *
\**********************************************************************/
G_DEFINE_TYPE_WITH_PRIVATE(MirageSector, mirage_sector, MIRAGE_TYPE_OBJECT)


static void mirage_sector_init (MirageSector *self)
{
    self->priv = mirage_sector_get_instance_private(self);

    /* Un-initialize sector type */
    self->priv->type = 0xDEADBEEF;
}

static void mirage_sector_class_init (MirageSectorClass *klass G_GNUC_UNUSED)
{
}


/**********************************************************************\
 *                        Subchannel generation                       *
\**********************************************************************/
static gint subchannel_generate_p (MirageSector *self, guint8 *buf)
{
    MirageTrack *track;
    gint track_start;
    gint relative_address;

    /* Get sector's parent track */
    track = mirage_object_get_parent(MIRAGE_OBJECT(self));
    if (!track) {
        MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: failed to get sector's parent!\n", __debug__);
        return 12;
    }

    relative_address = self->priv->address - mirage_track_layout_get_start_sector(track);
    track_start = mirage_track_get_track_start(track);

    /* P subchannel being 0xFF indicates we're in the pregap */
    if (relative_address < track_start) {
        memset(buf, 0xFF, 12);
    } else {
        memset(buf, 0, 12);
    }

    /* Release sector's parent track */
    g_object_unref(track);

    return 12;
}

static gint subchannel_generate_q (MirageSector *self, guint8 *buf)
{
    MirageTrack *track;

    gint mode_switch;
    gint relative_address, absolute_address;
    guint16 crc;

    /* Get sector's parent track */
    track = mirage_object_get_parent(MIRAGE_OBJECT(self));
    if (!track) {
        MIRAGE_DEBUG(self, MIRAGE_DEBUG_WARNING, "%s: failed to get sector's parent!\n", __debug__);
        return 12;
    }

    absolute_address = self->priv->address;
    relative_address = self->priv->address - mirage_track_layout_get_start_sector(track);

    /* We support Mode-1, Mode-2 and Mode-3 Q; according to INF8090 and MMC-3,
       "if used, they shall exist in at least one out of 100 consecutive sectors".
       So we put MCN in every 25th sector and ISRC in every 50th sector */

    /* Track number, index, absolute and relative track adresses are converted
       from HEX to BCD */

    switch (relative_address % 100) {
        case 25: {
            /* MCN is to be returned; check if we actually have it */
            MirageSession *session;

            session = mirage_object_get_parent(MIRAGE_OBJECT(track));

            if (!mirage_session_get_mcn(session)) {
                mode_switch = 0x01;
            } else {
                mode_switch = 0x02;
            }

            g_object_unref(session);

            break;
        }
        case 50: {
            /* ISRC is to be returned; verify that this is an audio track and
               that it actually has ISRC set */
            gint mode = mirage_sector_get_sector_type(self);

            if (mode != MIRAGE_SECTOR_AUDIO) {
                mode_switch = 0x01;
            } else if (!mirage_track_get_isrc(track)) {
                mode_switch = 0x01;
            } else {
                mode_switch = 0x03;
            }

            break;
        }
        default: {
            /* Current position */
            mode_switch = 1;
            break;
        }
    }

    switch (mode_switch) {
        case 0x01: {
            /* Mode-1: Current position */
            gint ctl, track_number;
            gint track_start;
            MirageIndex *index;

            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating Mode-1 Q: Position\n", __debug__);

            ctl = mirage_track_get_ctl(track);
            track_number = mirage_track_layout_get_track_number(track);

            track_start = mirage_track_get_track_start(track);

            buf[0] = (ctl << 0x04) | 0x01; /* Mode-1 Q */
            buf[1] = mirage_helper_hex2bcd(track_number); /* Track number */

            /* Index: try getting index object by address; if it's not found, we
               check if sector lies before track start... */
            index = mirage_track_get_index_by_address(track, relative_address, NULL);
            if (index) {
                gint index_number = mirage_index_get_number(index);
                MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: relative address 0x%X belongs to index with number: %d\n", __debug__, relative_address, index_number);
                buf[2] = index_number;
                g_object_unref(index);
            } else {
                /* No index... check if address is in a pregap (strictly less than track start) */
                if (relative_address < track_start) {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: relative address 0x%X is part of a pregap\n", __debug__, relative_address);
                    buf[2] = 0;
                } else {
                    MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: relative address 0x%X belongs to index 1\n", __debug__, relative_address);
                    buf[2] = 1;
                }
            }
            buf[2] = mirage_helper_hex2bcd(buf[2]);

            /* Relative M/S/F; when converting, we do not add 2 seconds */
            mirage_helper_lba2msf(ABS(relative_address - track_start), FALSE, &buf[3], &buf[4], &buf[5]);
            buf[3] = mirage_helper_hex2bcd(buf[3]);
            buf[4] = mirage_helper_hex2bcd(buf[4]);
            buf[5] = mirage_helper_hex2bcd(buf[5]);
            buf[6] = 0; /* Zero */
            /* Absolute M/S/F */
            mirage_helper_lba2msf(absolute_address, TRUE, &buf[7], &buf[8], &buf[9]);
            buf[7] = mirage_helper_hex2bcd(buf[7]);
            buf[8] = mirage_helper_hex2bcd(buf[8]);
            buf[9] = mirage_helper_hex2bcd(buf[9]);
            break;
        }
        case 0x02: {
            /* Mode-2: MCN */
            gint ctl;

            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating Mode-2 Q: MCN\n", __debug__);

            ctl = mirage_track_get_ctl(track);
            buf[0] = (ctl << 0x04) | 0x02; /* Mode-2 Q */

            /* MCN */
            MirageSession *session;

            const gchar *mcn;

            session = mirage_object_get_parent(MIRAGE_OBJECT(track));

            mcn = mirage_session_get_mcn(session);

            g_object_unref(session);

            mirage_helper_subchannel_q_encode_mcn(&buf[1], mcn);
            buf[8] = 0; /* zero */
            /* AFRAME */
            mirage_helper_lba2msf(absolute_address, TRUE, NULL, NULL, &buf[9]);
            buf[9] = mirage_helper_hex2bcd(buf[9]);
            break;
        }
        case 0x03: {
            /* Mode-3: ISRC */
            gint ctl;

            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: generating Mode-3 Q: ISRC\n", __debug__);

            ctl = mirage_track_get_ctl(track);
            buf[0] = (ctl << 0x04) | 0x03; /* Mode-3 Q */

            /* ISRC*/
            const gchar *isrc = mirage_track_get_isrc(track);
            mirage_helper_subchannel_q_encode_isrc(&buf[1], isrc);
            MIRAGE_DEBUG(self, MIRAGE_DEBUG_SECTOR, "%s: ISRC string: %s bytes: %02X %02X %02X %02X %02X %02X %02X %02X\n", __debug__, isrc, buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8]);
            /* AFRAME */
            mirage_helper_lba2msf(absolute_address, TRUE, NULL, NULL, &buf[9]);
            buf[9] = mirage_helper_hex2bcd(buf[9]);
            break;
        }
    }

    /* CRC */
    crc = mirage_helper_subchannel_q_calculate_crc(&buf[0]);
    buf[10] = (crc & 0xFF00) >> 0x08;
    buf[11] = (crc & 0x00FF) >> 0x00;

    /* Release sector's parent track */
    g_object_unref(track);

    return 12;
}

static void mirage_sector_generate_subchannel (MirageSector *self)
{
    guint8 tmp_buf[12];

    /* Generate subchannel: only P/Q can be generated at the moment
       (other subchannels are set to 0) */

    memset(self->priv->subchan_pw, 0, sizeof(self->priv->subchan_pw));

    /* Read P subchannel into temporary buffer, then interleave it */
    subchannel_generate_p(self, tmp_buf);
    mirage_helper_subchannel_interleave(SUBCHANNEL_P, tmp_buf, self->priv->subchan_pw);
    /* Read Q subchannel into temporary buffer, then interleave it */
    subchannel_generate_q(self, tmp_buf);
    mirage_helper_subchannel_interleave(SUBCHANNEL_Q, tmp_buf, self->priv->subchan_pw);
}