ebustl-parser 0.7.0

Parse subtitle files in the EBU-STL format with Rust.
Documentation
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
//! General Subtitle Information (GSI) block, Tech 3264 section 4.2.

use std::fmt;

use codepage_strings::Coding;
use jiff::Zoned;

use crate::{Date, InvalidFieldValue, LanguageCode, ParseError, Time, fields};

/// Maximum Total Number of TTI Blocks (TNB)
pub(crate) const MAX_TNB: u32 = 99_999;

pub(crate) struct CodePageCodec {
    coding: Coding,
    codepage: u16,
}

impl CodePageCodec {
    pub fn new(codepage: u16) -> Result<Self, ParseError> {
        Ok(Self {
            codepage,
            coding: Coding::new(codepage).map_err(|_e| ParseError::CodePageNumber(codepage))?,
        })
    }

    pub(crate) fn decode(&self, data: &[u8]) -> Result<String, ParseError> {
        Ok(self.coding.decode_lossy(data).to_string())
    }
    pub(crate) fn encode(&self, value: &str) -> Result<Vec<u8>, ParseError> {
        self.coding
            .encode(value)
            .map_err(|err| ParseError::CodePageEncoding {
                codepage: self.codepage,
                value: value.to_string(),
                source: err,
            })
    }
}

/// Code Page Number (CPN), the code page of the text in the GSI block.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[allow(non_camel_case_types)]
pub enum CodePageNumber {
    /// Code page 437, United States
    CPN_437,
    /// Code page 850, Multilingual
    CPN_850,
    /// Code page 860, Portugal
    CPN_860,
    /// Code page 863, Canada-French
    CPN_863,
    /// Code page 865, Nordic
    CPN_865,
}

impl CodePageNumber {
    pub(crate) fn serialize(&self) -> Vec<u8> {
        match *self {
            CodePageNumber::CPN_437 => vec![0x34, 0x33, 0x37],
            CodePageNumber::CPN_850 => vec![0x38, 0x35, 0x30],
            CodePageNumber::CPN_860 => vec![0x38, 0x36, 0x30],
            CodePageNumber::CPN_863 => vec![0x38, 0x36, 0x33],
            CodePageNumber::CPN_865 => vec![0x38, 0x36, 0x35],
        }
    }

    pub(crate) fn from_u16(codepage: u16) -> Result<CodePageNumber, ParseError> {
        match codepage {
            437 => Ok(CodePageNumber::CPN_437),
            850 => Ok(CodePageNumber::CPN_850),
            860 => Ok(CodePageNumber::CPN_860),
            863 => Ok(CodePageNumber::CPN_863),
            865 => Ok(CodePageNumber::CPN_865),
            _ => Err(ParseError::CodePageNumber(codepage)),
        }
    }

    fn to_u16(self) -> u16 {
        match self {
            CodePageNumber::CPN_437 => 437,
            CodePageNumber::CPN_850 => 850,
            CodePageNumber::CPN_860 => 860,
            CodePageNumber::CPN_863 => 863,
            CodePageNumber::CPN_865 => 865,
        }
    }
}

/// Display Standard Code (DSC).
#[derive(Debug, PartialEq, Eq)]
pub enum DisplayStandardCode {
    /// Blank (20h), undefined
    Blank,
    /// Open subtitling (30h)
    OpenSubtitling,
    /// Level-1 teletext (31h)
    Level1Teletext,
    /// Level-2 teletext (32h)
    Level2Teletext,
}

impl DisplayStandardCode {
    pub(crate) fn parse(data: u8) -> Result<DisplayStandardCode, ParseError> {
        match data {
            0x20 => Ok(DisplayStandardCode::Blank),
            0x30 => Ok(DisplayStandardCode::OpenSubtitling),
            0x31 => Ok(DisplayStandardCode::Level1Teletext),
            0x32 => Ok(DisplayStandardCode::Level2Teletext),
            _ => Err(ParseError::DisplayStandardCode),
        }
    }

    pub(crate) fn serialize(&self) -> u8 {
        match *self {
            DisplayStandardCode::Blank => 0x20,
            DisplayStandardCode::OpenSubtitling => 0x30,
            DisplayStandardCode::Level1Teletext => 0x31,
            DisplayStandardCode::Level2Teletext => 0x32,
        }
    }
}

/// Time Code: Status (TCS), whether the time codes in the GSI and TTI blocks are intended for use.
#[derive(Debug, PartialEq, Eq)]
pub enum TimeCodeStatus {
    /// 30h, the time codes are not intended for use
    NotIntendedForUse,
    /// 31h, the time codes are intended for use
    IntendedForUse,
}

impl TimeCodeStatus {
    pub(crate) fn parse(data: u8) -> Result<TimeCodeStatus, ParseError> {
        match data {
            0x30 => Ok(TimeCodeStatus::NotIntendedForUse),
            0x31 => Ok(TimeCodeStatus::IntendedForUse),
            _ => Err(ParseError::TimeCodeStatus),
        }
    }

    pub(crate) fn serialize(&self) -> u8 {
        match *self {
            TimeCodeStatus::NotIntendedForUse => 0x30,
            TimeCodeStatus::IntendedForUse => 0x31,
        }
    }
}

/// Character Code Table (CCT), the character set of the Text Fields in the TTI blocks.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CharacterCodeTable {
    /// 00, Latin alphabet (ISO 6937)
    Latin,
    /// 01, Latin/Cyrillic alphabet (ISO 8859-5)
    LatinCyrillic,
    /// 02, Latin/Arabic alphabet (ISO 8859-6)
    LatinArabic,
    /// 03, Latin/Greek alphabet (ISO 8859-7)
    LatinGreek,
    /// 04, Latin/Hebrew alphabet (ISO 8859-8)
    LatinHebrew,
}

impl CharacterCodeTable {
    pub(crate) fn parse(data: &[u8]) -> Result<CharacterCodeTable, ParseError> {
        if data.len() != 2 {
            return Err(ParseError::CharacterCodeTable);
        }
        if data[0] != 0x30 {
            return Err(ParseError::CharacterCodeTable);
        }
        match data[1] {
            0x30 => Ok(CharacterCodeTable::Latin),
            0x31 => Ok(CharacterCodeTable::LatinCyrillic),
            0x32 => Ok(CharacterCodeTable::LatinArabic),
            0x33 => Ok(CharacterCodeTable::LatinGreek),
            0x34 => Ok(CharacterCodeTable::LatinHebrew),
            _ => Err(ParseError::CharacterCodeTable),
        }
    }

    pub(crate) fn serialize(&self) -> Vec<u8> {
        match *self {
            CharacterCodeTable::Latin => vec![0x30, 0x30],
            CharacterCodeTable::LatinCyrillic => vec![0x30, 0x31],
            CharacterCodeTable::LatinArabic => vec![0x30, 0x32],
            CharacterCodeTable::LatinGreek => vec![0x30, 0x33],
            CharacterCodeTable::LatinHebrew => vec![0x30, 0x34],
        }
    }
}

/// Disk Format Code (DFC), the frame rate of the time codes.
#[derive(Debug, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum DiskFormatCode {
    /// `STL25.01`, 25 frames per second
    STL25_01,
    /// `STL30.01`, 30 frames per second
    STL30_01,
}

impl DiskFormatCode {
    pub(crate) fn parse(data: &str) -> Result<DiskFormatCode, ParseError> {
        if data == "STL25.01" {
            Ok(DiskFormatCode::STL25_01)
        } else if data == "STL30.01" {
            Ok(DiskFormatCode::STL30_01)
        } else {
            Err(ParseError::DiskFormatCode(data.to_string()))
        }
    }

    pub(crate) fn serialize(&self) -> Vec<u8> {
        match *self {
            DiskFormatCode::STL25_01 => String::from("STL25.01").into_bytes(),
            DiskFormatCode::STL30_01 => String::from("STL30.01").into_bytes(),
        }
    }

    /// The number of frames per second, 25 or 30.
    ///
    /// `STL30.01` is commonly used for 29.97 frames per second (30 x 1000/1001), which the spec
    /// does not distinguish from 30.
    pub fn fps(&self) -> usize {
        match self {
            DiskFormatCode::STL25_01 => 25,
            DiskFormatCode::STL30_01 => 30,
        }
    }
}

/// General Subtitle Information (GSI) block, the first 1024 bytes of an STL file.
#[derive(Debug, PartialEq, Eq)]
pub struct GsiBlock {
    #[doc = "0..2 Code Page Number"]
    pub(crate) cpn: CodePageNumber,
    #[doc = "3..10 Disk Format Code"]
    pub(crate) dfc: DiskFormatCode,
    #[doc = "11 Display Standard Code"]
    pub(crate) dsc: DisplayStandardCode,
    #[doc = "12..13 Character Code Table Number"]
    pub(crate) cct: CharacterCodeTable,
    #[doc = "14..15 Language Code"]
    pub(crate) lc: String,
    #[doc = "16..47 Original Programme Title"]
    pub(crate) opt: String,
    #[doc = "48..79 Original Episode Title"]
    pub(crate) oet: String,
    #[doc = "80..111 Translated Programme Title"]
    pub(crate) tpt: String,
    #[doc = "112..143 Translated Episode Title"]
    pub(crate) tet: String,
    #[doc = "144..175 Translator's Name"]
    pub(crate) tn: String,
    #[doc = "176..207 Translator's Contact Details"]
    pub(crate) tcd: String,
    #[doc = "208..223 Subtitle List Reference Code"]
    pub(crate) slr: String,
    #[doc = "224..229 Creation Date"]
    pub(crate) cd: String,
    #[doc = "230..235 Revision Date"]
    pub(crate) rd: String,
    #[doc = "236..237 Revision Number"]
    pub(crate) rn: String,
    #[doc = "238..242 Total Number of Text and Timing Blocks. 0-99 999"]
    pub(crate) tnb: u32,
    #[doc = "243..247 Total Number of Subtitles. 0-99 999"]
    pub(crate) tns: u32,
    #[doc = "248..250 Total Number of Subtitle Groups"]
    pub(crate) tng: u16,
    #[doc = "251..252 Maximum Number of Displayable Characters in a Text Row"]
    pub(crate) mnc: u16,
    #[doc = "253..254 Maximum Number of Displayable Rows"]
    pub(crate) mnr: u16,
    #[doc = "255 Time Code Status"]
    pub(crate) tcs: TimeCodeStatus,
    #[doc = "256..263 Time Code: Start of Programme (format: HHMMSSFF)"]
    pub(crate) tcp: String,
    #[doc = "264..271 Time Code: First-in-Cue (format: HHMMSSFF)"]
    pub(crate) tcf: String,
    #[doc = "272 Total Number of Disks"]
    pub(crate) tnd: u8,
    #[doc = "273 Disk Sequence Number"]
    pub(crate) dsn: u8,
    #[doc = "274..276 Country of Origin"]
    pub(crate) co: String, // TODO Type with country definitions
    #[doc = "277..308 Publisher"]
    pub(crate) pub_: String,
    #[doc = "309..340 Editor's Name"]
    pub(crate) en: String,
    #[doc = "341..372 Editor's Contact Details"]
    pub(crate) ecd: String,
    #[doc = "373..447 Spare Bytes"]
    pub(crate) _spare: String,
    #[doc = "448..1023 User-Defined Area"]
    pub(crate) uda: String,
}

// Accessors in the order of the fields in the block. Accessors that validate a field return
// the value as stored in the file in the error, see `InvalidFieldValue`.
impl GsiBlock {
    /// Code Page Number (CPN), the code page of the text in the GSI block.
    pub fn code_page_number(&self) -> &CodePageNumber {
        &self.cpn
    }

    /// Disk Format Code (DFC), the frame rate of the time codes.
    pub fn disk_format_code(&self) -> &DiskFormatCode {
        &self.dfc
    }

    /// Display Standard Code (DSC).
    pub fn display_standard_code(&self) -> &DisplayStandardCode {
        &self.dsc
    }

    /// Character Code Table (CCT) of the Text Fields in the TTI blocks.
    pub fn character_code_table(&self) -> &CharacterCodeTable {
        &self.cct
    }

    /// Language Code (LC), validated as two hexadecimal digits 00h-7Fh, the range of the codes in
    /// Appendix 3. A validated code may still be unassigned, see [`LanguageCode::name`]. `None` if
    /// blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// // The test file uses 2Fh, which is reserved for national assignment
    /// let language = stl.gsi.language().unwrap().unwrap();
    /// assert_eq!(0x2F, language.0);
    /// assert_eq!(None, language.name());
    /// ```
    pub fn language(&self) -> Result<Option<LanguageCode>, InvalidFieldValue<String>> {
        fields::parse_field("LC", &self.lc, fields::parse_language_code)
    }

    /// Original Programme Title (OPT), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("TEST"), stl.gsi.original_programme_title());
    /// ```
    pub fn original_programme_title(&self) -> Option<&str> {
        fields::text(&self.opt)
    }

    /// Original Episode Title (OET), without the trailing space padding. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("TEST EPISODE"), stl.gsi.original_episode_title());
    /// ```
    pub fn original_episode_title(&self) -> Option<&str> {
        fields::text(&self.oet)
    }

    /// Translated Programme Title (TPT), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("TEST"), stl.gsi.translated_programme_title());
    /// ```
    pub fn translated_programme_title(&self) -> Option<&str> {
        fields::text(&self.tpt)
    }

    /// Translated Episode Title (TET), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("EPISODE DE TEST"), stl.gsi.translated_episode_title());
    /// ```
    pub fn translated_episode_title(&self) -> Option<&str> {
        fields::text(&self.tet)
    }

    /// Translator's Name (TN), without the trailing space padding. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("C. Lebeaupin"), stl.gsi.translators_name());
    /// ```
    pub fn translators_name(&self) -> Option<&str> {
        fields::text(&self.tn)
    }

    /// Translator's Contact Details (TCD), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(None, stl.gsi.translators_contact_details());
    /// ```
    pub fn translators_contact_details(&self) -> Option<&str> {
        fields::text(&self.tcd)
    }

    /// Subtitle List Reference Code (SLR), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(None, stl.gsi.subtitle_list_reference_code());
    /// ```
    pub fn subtitle_list_reference_code(&self) -> Option<&str> {
        fields::text(&self.slr)
    }

    /// Creation Date (CD), validated as an existing date in the format YYMMDD. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ebustl_parser::Date;
    ///
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// let date = Date { year: 2013, month: 10, day: 10 };
    /// assert_eq!(Ok(Some(date)), stl.gsi.creation_date());
    /// ```
    pub fn creation_date(&self) -> Result<Option<Date>, InvalidFieldValue<String>> {
        fields::parse_field("CD", &self.cd, fields::parse_date)
    }

    /// Revision Date (RD), validated as an existing date in the format YYMMDD. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ebustl_parser::Date;
    ///
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// let date = Date { year: 2013, month: 10, day: 17 };
    /// assert_eq!(Ok(Some(date)), stl.gsi.revision_date());
    /// ```
    pub fn revision_date(&self) -> Result<Option<Date>, InvalidFieldValue<String>> {
        fields::parse_field("RD", &self.rd, fields::parse_date)
    }

    /// Revision Number (RN), validated as 0-99, ignoring space padding. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// // Blank in the test file
    /// assert_eq!(Ok(None), stl.gsi.revision_number());
    /// ```
    pub fn revision_number(&self) -> Result<Option<u8>, InvalidFieldValue<String>> {
        fields::parse_field("RN", &self.rn, fields::parse_revision_number)
    }

    /// Total Number of TTI Blocks (TNB), including extension blocks.
    pub fn total_number_of_text_and_timing_blocks(&self) -> u32 {
        self.tnb
    }

    /// Total Number of Subtitles (TNS).
    pub fn total_number_of_subtitles(&self) -> u32 {
        self.tns
    }

    /// Total Number of Subtitle Groups (TNG).
    pub fn total_number_of_subtitle_groups(&self) -> u16 {
        self.tng
    }

    /// Maximum Number of Displayable Characters in any text row (MNC).
    pub fn max_number_of_chars_in_row(&self) -> u16 {
        self.mnc
    }

    /// Maximum Number of Displayable Rows (MNR).
    pub fn max_number_of_rows(&self) -> u16 {
        self.mnr
    }

    /// Time Code: Status (TCS), whether the time codes in the GSI and TTI blocks are intended for
    /// use.
    pub fn time_code_status(&self) -> &TimeCodeStatus {
        &self.tcs
    }

    /// Time Code: Start-of-Programme (TCP), validated as HHMMSSFF with minutes and seconds 0-59 and
    /// frames according to the Disk Format Code. Hours may exceed 23, e.g. for a programme that
    /// continues past midnight. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ebustl_parser::Time;
    ///
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// let time = Time { hours: 10, minutes: 0, seconds: 0, frames: 0 };
    /// assert_eq!(Ok(Some(time)), stl.gsi.time_code_start_of_programme());
    /// ```
    pub fn time_code_start_of_programme(&self) -> Result<Option<Time>, InvalidFieldValue<String>> {
        let fps = self.dfc.fps();
        fields::parse_field("TCP", &self.tcp, |value| {
            fields::parse_time_code(value, fps)
        })
    }

    /// Time Code: First In-Cue (TCF), validated as HHMMSSFF with minutes and seconds 0-59 and
    /// frames according to the Disk Format Code. Hours may exceed 23, e.g. for a programme that
    /// continues past midnight. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ebustl_parser::Time;
    ///
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// let time = Time { hours: 10, minutes: 0, seconds: 0, frames: 0 };
    /// assert_eq!(Ok(Some(time)), stl.gsi.time_code_first_in_cue());
    /// ```
    pub fn time_code_first_in_cue(&self) -> Result<Option<Time>, InvalidFieldValue<String>> {
        let fps = self.dfc.fps();
        fields::parse_field("TCF", &self.tcf, |value| {
            fields::parse_time_code(value, fps)
        })
    }

    /// Total Number of Disks (TND) in the set holding the subtitle list.
    pub fn total_number_of_disks(&self) -> u8 {
        self.tnd
    }

    /// Disk Sequence Number (DSN) of this disk in the set, starting at 1.
    pub fn disk_sequence_number(&self) -> u8 {
        self.dsn
    }

    /// Country of Origin (CO), validated as three upper case letters (ISO 3166 alpha-3). `None` if
    /// blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Ok(Some("FRA")), stl.gsi.country_of_origin());
    /// ```
    pub fn country_of_origin(&self) -> Result<Option<&str>, InvalidFieldValue<String>> {
        fields::parse_field("CO", &self.co, fields::parse_country_code)
    }

    /// Publisher (PUB), without the trailing space padding. `None` if blank.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("TESTSUB"), stl.gsi.publisher());
    /// ```
    pub fn publisher(&self) -> Option<&str> {
        fields::text(&self.pub_)
    }

    /// Editor's Name (EN), without the trailing space padding. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(Some("TESTSUB 1.0.1"), stl.gsi.editors_name());
    /// ```
    pub fn editors_name(&self) -> Option<&str> {
        fields::text(&self.en)
    }

    /// Editor's Contact Details (ECD), without the trailing space padding. `None` if blank.
    ///
    /// On error, [`InvalidFieldValue::value`] gives the value as stored in the file.
    ///
    /// # Example
    ///
    /// ```rust
    /// let stl = ebustl_parser::parse_stl_from_file("stls/test.stl").unwrap();
    /// assert_eq!(None, stl.gsi.editors_contact_details());
    /// ```
    pub fn editors_contact_details(&self) -> Option<&str> {
        fields::text(&self.ecd)
    }

    /// User-Defined Area (UDA), decoded with the code page of the GSI block.
    pub fn user_defined_area(&self) -> &str {
        &self.uda
    }
}

fn push_string(v: &mut Vec<u8>, s: &str, len: usize) {
    let addendum = s.to_owned().into_bytes();
    let padding = len - addendum.len();
    v.extend(addendum.iter().cloned());
    v.extend(vec![0x20u8; padding]);
}

fn push_encoded_string(
    v: &mut Vec<u8>,
    c: &CodePageCodec,
    s: &str,
    len: usize,
) -> Result<(), ParseError> {
    let addendum = c.encode(s)?;
    let padding = len - addendum.len();
    v.extend(addendum.iter().cloned());
    v.extend(vec![0x20u8; padding]);
    Ok(())
}

impl GsiBlock {
    /// Creates a GSI block for a teletext subtitle list.
    ///
    /// The defaults are code page 850, 25 frames per second, Level-1 teletext, the Latin character
    /// code table, today as creation and revision date and time codes intended for use.
    pub fn new() -> GsiBlock {
        let date = Zoned::now();
        let now = date.strftime("%y%m%d").to_string();
        GsiBlock {
            cpn: CodePageNumber::CPN_850,
            dfc: DiskFormatCode::STL25_01,
            dsc: DisplayStandardCode::Level1Teletext,
            cct: CharacterCodeTable::Latin,
            lc: "0F".to_string(), // FIXME: ok for default?
            opt: "".to_string(),
            oet: "".to_string(),
            tpt: "".to_string(),
            tet: "".to_string(),
            tn: "".to_string(),
            tcd: "".to_string(),
            slr: "".to_string(),
            cd: now.clone(),
            rd: now,
            rn: "00".to_string(),
            tnb: 0,
            tns: 0,
            tng: 1,  // At least one group?
            mnc: 40, // FIXME: ok for default?
            mnr: 23, // FIXME: ok for default?
            tcs: TimeCodeStatus::IntendedForUse,
            tcp: "00000000".to_string(),
            tcf: "00000000".to_string(),
            tnd: 1,
            dsn: 1,
            co: "".to_string(),
            pub_: "".to_string(),
            en: "".to_string(),
            ecd: "".to_string(),
            _spare: "".to_string(),
            uda: "".to_string(),
        }
    }

    pub(crate) fn serialize(&self) -> Result<Vec<u8>, ParseError> {
        let codepage = self.code_page_number().to_u16();
        let coding = CodePageCodec::new(codepage).expect("codepage");
        let mut res = Vec::with_capacity(1024);
        res.extend(self.cpn.serialize());
        res.extend(self.dfc.serialize().iter().cloned());
        res.push(self.dsc.serialize());
        res.extend(self.cct.serialize());
        // be careful for the length of following: must force padding
        push_encoded_string(&mut res, &coding, &self.lc, 15 - 14 + 1)?;
        push_encoded_string(&mut res, &coding, &self.opt, 47 - 16 + 1)?;
        push_encoded_string(&mut res, &coding, &self.oet, 79 - 48 + 1)?;
        push_encoded_string(&mut res, &coding, &self.tpt, 111 - 80 + 1)?;
        push_encoded_string(&mut res, &coding, &self.tet, 143 - 112 + 1)?;
        push_encoded_string(&mut res, &coding, &self.tn, 175 - 144 + 1)?;
        push_encoded_string(&mut res, &coding, &self.tcd, 207 - 176 + 1)?;
        push_encoded_string(&mut res, &coding, &self.slr, 223 - 208 + 1)?;
        push_encoded_string(&mut res, &coding, &self.cd, 229 - 224 + 1)?;
        push_encoded_string(&mut res, &coding, &self.rd, 235 - 230 + 1)?;
        push_encoded_string(&mut res, &coding, &self.rn, 237 - 236 + 1)?;

        push_string(&mut res, &format!("{:05}", self.tnb), 242 - 238 + 1);
        push_string(&mut res, &format!("{:05}", self.tns), 247 - 243 + 1);
        push_string(&mut res, &format!("{:03}", self.tng), 250 - 248 + 1);
        push_string(&mut res, &format!("{:02}", self.mnc), 252 - 251 + 1);
        push_string(&mut res, &format!("{:02}", self.mnr), 254 - 253 + 1);

        res.push(self.tcs.serialize());
        push_encoded_string(&mut res, &coding, &self.tcp, 263 - 256 + 1)?;
        push_encoded_string(&mut res, &coding, &self.tcf, 271 - 264 + 1)?;
        push_string(&mut res, &format!("{:1}", self.tnd), 1);
        push_string(&mut res, &format!("{:1}", self.dsn), 1);
        push_encoded_string(&mut res, &coding, &self.co, 276 - 274 + 1)?;
        push_encoded_string(&mut res, &coding, &self.pub_, 308 - 277 + 1)?;
        push_encoded_string(&mut res, &coding, &self.en, 340 - 309 + 1)?;
        push_encoded_string(&mut res, &coding, &self.ecd, 372 - 341 + 1)?;
        push_encoded_string(&mut res, &coding, &self._spare, 447 - 373 + 1)?;
        push_encoded_string(&mut res, &coding, &self.uda, 1023 - 448 + 1)?;

        Ok(res)
    }
}

impl Default for GsiBlock {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for GsiBlock {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Program Title: {}\nEpisode Title: {}\ncct:{:?} lc:{}\n",
            self.opt, self.oet, self.cct, self.lc
        )
    }
}