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
#[macro_use]
extern crate nom;
extern crate iso6937;
extern crate chrono;

use std::fmt;
use std::str;
use std::io;
use std::io::prelude::*;
use std::fs::File;

pub mod parser;
pub use parser::ParseError;
use parser::parse_stl_from_slice;

// STL File

#[derive(Debug)]
pub struct Stl {
    pub gsi: GsiBlock,
    pub ttis: Vec<TtiBlock>,
}

impl fmt::Display for Stl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}\n{:?}\n", self.gsi, self.ttis)
    }
}

pub struct TtiFormat {
    #[doc="Justification Code"]
    pub jc: u8,
    #[doc="Vertical Position"]
    pub vp: u8,
    #[doc="Double Height"]
    pub dh: bool,
}

impl Stl {
    pub fn new() -> Stl {
        Stl {
            gsi: GsiBlock::new(),
            ttis: vec![],
        }
    }

    pub fn write_to_file(&self, filename: &str) -> Result<(), io::Error> {
        let mut f = try!(File::create(filename));
        try!(f.write_all(&self.gsi.serialize()));
        for tti in self.ttis.iter() {
            try!(f.write_all(&tti.serialize()));
        }
        Ok(())
    }

    pub fn add_sub(&mut self, tci: Time, tco: Time, txt: &str, opt: TtiFormat) {
        if txt.len() > 112 {
            //TODO: if txt.len() > 112 split in multiple
            println!("Warning: sub text is too long!");
        }
        self.gsi.tnb += 1; // First TTI has sn=1
        let tti = TtiBlock::new(self.gsi.tnb, tci, tco, txt, opt);
        self.gsi.tns += 1;
        self.ttis.push(tti);
    }
}

pub fn parse_stl_from_file(filename: &str) -> Result<Stl, ParseError> {
    let mut f = try!(File::open(filename));
    let mut buffer = vec![];
    try!(f.read_to_end(&mut buffer));

    parse_stl_from_slice(&buffer)
}


// GSI Block

#[derive(Debug)]
#[allow(non_camel_case_types)]
enum CodePageNumber {
    CPN_437,
    CPN_850,
    CPN_860,
    CPN_863,
    CPN_865,
}

impl CodePageNumber {
    fn parse(data: &[u8]) -> Result<CodePageNumber, ParseError> {
        if data.len() != 3 {
            return Err(ParseError::CodePageNumber);
        }
        if data[0] == 0x34 && data[1] == 0x33 && data[2] == 0x37 {
            return Ok(CodePageNumber::CPN_437);
        } else if data[0] == 0x38 && data[1] == 0x35 && data[2] == 0x30 {
            return Ok(CodePageNumber::CPN_850);
        } else if data[0] == 0x38 && data[1] == 0x36 && data[2] == 0x30 {
            return Ok(CodePageNumber::CPN_860);
        } else if data[0] == 0x38 && data[1] == 0x36 && data[2] == 0x33 {
            return Ok(CodePageNumber::CPN_863);
        } else if data[0] == 0x38 && data[1] == 0x36 && data[2] == 0x35 {
            return Ok(CodePageNumber::CPN_865);
        }
        return Err(ParseError::CodePageNumber);
    }

    fn serialize(&self) -> Vec<u8> {
        return 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],
               };
    }
}


#[derive(Debug)]
enum DisplayStandardCode {
    Blank,
    OpenSubtitling,
    Level1Teletext,
    Level2Teletext,
}

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

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

#[derive(Debug)]
enum TimeCodeStatus {
    NotIntendedForUse,
    IntendedForUse,
}

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

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


#[derive(Debug)]
enum CharacterCodeTable {
    Latin,
    LatinCyrillic,
    LatinArabic,
    LatinGreek,
    LatinHebrew,
}

impl CharacterCodeTable {
    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),
        }
    }

    fn serialize(&self) -> Vec<u8> {
        return 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],
               };
    }
}

#[derive(Debug)]
#[allow(non_camel_case_types)]
pub enum DiskFormatCode {
    STL25_01,
    STL30_01,
}

impl DiskFormatCode {
    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)
        }
    }

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

    pub fn get_fps(self) -> usize {
        return match self {
                   DiskFormatCode::STL25_01 => 25,
                   DiskFormatCode::STL30_01 => 30,
               };
    }
}

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

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

impl GsiBlock {
    pub fn new() -> GsiBlock {
        let date = chrono::Local::now();
        let now = date.format("%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.clone(),
            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(),
        }
    }

    fn serialize(&self) -> Vec<u8> {
        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_string(&mut res, &self.lc, 15 - 14 + 1);
        push_string(&mut res, &self.opt, 47 - 16 + 1);
        push_string(&mut res, &self.oet, 79 - 48 + 1);
        push_string(&mut res, &self.tpt, 111 - 80 + 1);
        push_string(&mut res, &self.tet, 143 - 112 + 1);
        push_string(&mut res, &self.tn, 175 - 144 + 1);
        push_string(&mut res, &self.tcd, 207 - 176 + 1);
        push_string(&mut res, &self.slr, 223 - 208 + 1);
        push_string(&mut res, &self.cd, 229 - 224 + 1);
        push_string(&mut res, &self.rd, 235 - 230 + 1);
        push_string(&mut res, &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_string(&mut res, &self.tcp, 263 - 256 + 1);
        push_string(&mut res, &self.tcf, 271 - 264 + 1);
        push_string(&mut res, &format!("{:1}", self.tnd), 1);
        push_string(&mut res, &format!("{:1}", self.dsn), 1);
        push_string(&mut res, &self.co, 276 - 274 + 1);
        push_string(&mut res, &self.pub_, 308 - 277 + 1);
        push_string(&mut res, &self.en, 340 - 309 + 1);
        push_string(&mut res, &self.ecd, 372 - 341 + 1);
        push_string(&mut res, &self._spare, 447 - 373 + 1);
        push_string(&mut res, &self.uda, 1023 - 448 + 1);

        return res;
    }
}

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)
    }
}

// TTI Block

#[derive(Debug)]
enum CumulativeStatus {
    NotPartOfASet,
    FirstInSet,
    IntermediateInSet,
    LastInSet,
}

impl CumulativeStatus {
    fn parse(d: u8) -> Result<CumulativeStatus, ParseError> {
        return match d {
                   0 => Ok(CumulativeStatus::NotPartOfASet),
                   1 => Ok(CumulativeStatus::FirstInSet),
                   2 => Ok(CumulativeStatus::IntermediateInSet),
                   3 => Ok(CumulativeStatus::LastInSet),
                   _ => Err(ParseError::CumulativeStatus),
               };
    }

    fn serialize(&self) -> u8 {
        return match *self {
                   CumulativeStatus::NotPartOfASet => 0,
                   CumulativeStatus::FirstInSet => 1,
                   CumulativeStatus::IntermediateInSet => 2,
                   CumulativeStatus::LastInSet => 3,
               };
    }
}

pub enum Justification {
    Unchanged,
    Left,
    Centered,
    Right,
}

#[derive(Debug, PartialEq)]
pub struct Time {
    pub hours: u8,
    pub minutes: u8,
    pub seconds: u8,
    pub frames: u8,
}

impl Time {
    fn new(h: u8, m: u8, s: u8, f: u8) -> Time {
        Time {
            hours: h,
            minutes: m,
            seconds: s,
            frames: f,
        }
    }

    pub fn format_fps(&self, fps: usize) -> String {
        format!("{}:{}:{},{}",
                self.hours,
                self.minutes,
                self.seconds,
                self.frames as usize * 1000 / fps)
    }
    fn serialize(&self) -> Vec<u8> {
        vec![self.hours, self.minutes, self.seconds, self.frames]
    }
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "{}:{}:{}/{})",
               self.hours,
               self.minutes,
               self.seconds,
               self.frames)
    }
}

pub struct TtiBlock {
    #[doc="0 Subtitle Group Number. 00h-FFh"]
    sgn: u8,
    #[doc="1..2 Subtitle Number range. 0000h-FFFFh"]
    sn: u16,
    #[doc="3 Extension Block Number. 00h-FFh"]
    ebn: u8,
    #[doc="4 Cumulative Status. 00-03h"]
    cs: CumulativeStatus,
    #[doc="5..8 Time Code In"]
    tci: Time,
    #[doc="9..12 Time Code Out"]
    tco: Time,
    #[doc="13 Vertical Position"]
    vp: u8,
    #[doc="14 Justification Code"]
    jc: u8,
    #[doc="15 Comment Flag"]
    cf: u8,
    #[doc="16..127 Text Field"]
    tf: Vec<u8>,
}


impl TtiBlock {
    pub fn new(idx: u16, tci: Time, tco: Time, txt: &str, opt: TtiFormat) -> TtiBlock {
        TtiBlock {
            sgn: 0,
            sn: idx,
            ebn: 0xff,
            cs: CumulativeStatus::NotPartOfASet,
            tci: tci,
            tco: tco,
            vp: opt.vp,
            jc: opt.jc,
            cf: 0,
            tf: TtiBlock::encode_text(txt, opt.dh),
        }
    }

    fn encode_text(txt: &str, dh: bool) -> Vec<u8> {
        const TF_LENGTH: usize = 112;
        let text = iso6937::encode(txt);
        let mut res = Vec::with_capacity(TF_LENGTH);
        if dh {
            res.push(0x0d);
        }
        res.push(0x0b);
        res.push(0x0b);
        res.extend(text);

        // Make sure size does not exceeds 112 bytes, FIXME: and what if!
        let max_size = TF_LENGTH - 3; // 3 trailing teletext codes to add.
        if res.len() > max_size {
            println!("!!! subtitle length is too long, truncating!");
        }
        res.truncate(max_size);
        res.push(0x0A);
        res.push(0x0A);
        res.push(0x8A);
        let padding = TF_LENGTH - res.len();
        res.extend(vec![0x8Fu8; padding]);
        res
    }

    pub fn get_text(&self) -> String {
        let mut result = String::from("");
        let mut first = 0;
        for i in 0..self.tf.len() {
            let c = self.tf[i];
            if match c {
                   0x0...0x1f => true, //TODO: decode teletext control codes
                   0x20...0x7f => false,
                   0x7f...0x9f => true, // TODO: decode codes
                   0xa1...0xff => false,
                   _ => break,
               } {
                if first != i {
                    result.push_str(&iso6937::decode(&self.tf[first..i]));
                }
                if c == 0x8f {
                    break;
                } else if c == 0x8a {
                    result.push_str("\r\n");
                }
                first = i + 1;
            }
        }
        return result;
    }

    fn serialize(&self) -> Vec<u8> {
        let mut res = vec![];
        res.push(self.sgn);
        res.push((self.sn & 0xff) as u8);
        res.push((self.sn >> 8) as u8);
        res.push(self.ebn);
        res.push(self.cs.serialize());
        res.extend(self.tci
                       .serialize()
                       .iter()
                       .cloned());
        res.extend(self.tco
                       .serialize()
                       .iter()
                       .cloned());
        res.push(self.vp);
        res.push(self.jc);
        res.push(self.cf);
        res.extend(self.tf.iter().cloned());
        return res;
    }
}

impl fmt::Debug for TtiBlock {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "\n{}-->{} sgn:{} sn:{} ebn:{} cs:{:?} vp:{} jc:{} cf:{} [{}]",
               self.tci,
               self.tco,
               self.sgn,
               self.sn,
               self.ebn,
               self.cs,
               self.vp,
               self.jc,
               self.cf,
               self.get_text())
    }
}

impl fmt::Display for TtiBlock {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "\n{} {} {} {} {:?} [{}]",
               self.tci,
               self.sgn,
               self.sn,
               self.ebn,
               self.cs,
               self.get_text())
    }
}