Welcome to mirror list, hosted at ThFree Co, Russian Federation.

imp.rs « mcc_parse « src « closedcaption « video - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6bbbf0d99271cd9b5a8994d08d9f198d0a3a2720 (plain)
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
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// <https://mozilla.org/MPL/2.0/>.
//
// SPDX-License-Identifier: MPL-2.0

use gst::glib;
use gst::prelude::*;
use gst::subclass::prelude::*;
use gst_video::ValidVideoTimeCode;

use std::cmp;
use std::sync::{Mutex, MutexGuard};

use once_cell::sync::Lazy;

use super::parser::{MccLine, MccParser};
use crate::line_reader::LineReader;
use crate::parser_utils::TimeCode;

static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
    gst::DebugCategory::new(
        "mccparse",
        gst::DebugColorFlags::empty(),
        Some("Mcc Parser Element"),
    )
});

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Format {
    Cea708Cdp,
    Cea608,
}

#[derive(Debug)]
struct PullState {
    need_stream_start: bool,
    stream_id: String,
    offset: u64,
    duration: Option<gst::ClockTime>,
}

impl PullState {
    fn new(imp: &MccParse, pad: &gst::Pad) -> Self {
        Self {
            need_stream_start: true,
            stream_id: pad.create_stream_id(&*imp.obj(), Some("src")).to_string(),
            offset: 0,
            duration: gst::ClockTime::NONE,
        }
    }
}

#[derive(Debug)]
struct State {
    reader: LineReader<gst::MappedBuffer<gst::buffer::Readable>>,
    parser: MccParser,
    format: Option<Format>,
    need_segment: bool,
    pending_events: Vec<gst::Event>,
    start_position: Option<gst::ClockTime>,
    last_position: Option<gst::ClockTime>,
    last_timecode: Option<gst_video::ValidVideoTimeCode>,
    timecode_rate: Option<(u8, bool)>,
    segment: gst::FormattedSegment<gst::ClockTime>,

    // Pull mode
    pull: Option<PullState>,

    // seeking
    seeking: bool,
    discont: bool,
    seek_seqnum: Option<gst::Seqnum>,
    last_raw_line: Vec<u8>,
    replay_last_line: bool,
    need_flush_stop: bool,
}

impl Default for State {
    fn default() -> Self {
        Self {
            reader: LineReader::new(),
            parser: MccParser::new(),
            format: None,
            need_segment: true,
            pending_events: Vec::new(),
            start_position: None,
            last_position: None,
            last_timecode: None,
            timecode_rate: None,
            segment: gst::FormattedSegment::new(),
            pull: None,
            seeking: false,
            discont: false,
            seek_seqnum: None,
            last_raw_line: Vec::new(),
            replay_last_line: false,
            need_flush_stop: false,
        }
    }
}

fn parse_timecode(
    framerate: gst::Fraction,
    drop_frame: bool,
    tc: TimeCode,
) -> Result<ValidVideoTimeCode, gst::FlowError> {
    let timecode = gst_video::VideoTimeCode::new(
        framerate,
        None,
        if drop_frame {
            gst_video::VideoTimeCodeFlags::DROP_FRAME
        } else {
            gst_video::VideoTimeCodeFlags::empty()
        },
        tc.hours,
        tc.minutes,
        tc.seconds,
        tc.frames,
        0,
    );

    timecode.try_into().map_err(|_| gst::FlowError::Error)
}

fn parse_timecode_rate(
    timecode_rate: Option<(u8, bool)>,
) -> Result<(gst::Fraction, bool), gst::FlowError> {
    let (framerate, drop_frame) = match timecode_rate {
        Some((rate, false)) => (gst::Fraction::new(rate as i32, 1), false),
        Some((rate, true)) => (gst::Fraction::new(rate as i32 * 1000, 1001), true),
        None => {
            return Err(gst::FlowError::Error);
        }
    };

    Ok((framerate, drop_frame))
}

impl State {
    #[allow(clippy::type_complexity)]
    fn line(&mut self, drain: bool) -> Result<Option<MccLine>, (&[u8], nom::error::Error<&[u8]>)> {
        let line = if self.replay_last_line {
            self.replay_last_line = false;
            &self.last_raw_line
        } else {
            match self.reader.line_with_drain(drain) {
                None => {
                    return Ok(None);
                }
                Some(line) => {
                    self.last_raw_line = line.to_vec();
                    line
                }
            }
        };

        self.parser
            .parse_line(line, !self.seeking)
            .map(Option::Some)
            .map_err(|err| (line, err))
    }

    fn handle_timecode(
        &mut self,
        imp: &MccParse,
        framerate: gst::Fraction,
        drop_frame: bool,
        tc: TimeCode,
    ) -> Result<ValidVideoTimeCode, gst::FlowError> {
        match parse_timecode(framerate, drop_frame, tc) {
            Ok(timecode) => Ok(timecode),
            Err(timecode) => {
                let last_timecode =
                    self.last_timecode
                        .as_ref()
                        .map(Clone::clone)
                        .ok_or_else(|| {
                            gst::element_imp_error!(
                                imp,
                                gst::StreamError::Decode,
                                ["Invalid first timecode {:?}", timecode]
                            );

                            gst::FlowError::Error
                        })?;

                gst::warning!(
                    CAT,
                    imp: imp,
                    "Invalid timecode {:?}, using previous {:?}",
                    timecode,
                    last_timecode
                );

                Ok(last_timecode)
            }
        }
    }

    /// Calculate a timestamp from the timecode and make sure to
    /// not produce timestamps jumping backwards
    fn update_timestamp(&mut self, imp: &MccParse, timecode: &gst_video::ValidVideoTimeCode) {
        let nsecs = timecode.time_since_daily_jam();
        if self.start_position.is_none() {
            self.start_position = Some(nsecs);
        }
        let start_position = self.start_position.expect("checked above");

        let nsecs = nsecs.checked_sub(start_position).unwrap_or_else(|| {
            gst::fixme!(
                CAT,
                imp: imp,
                "New position {} < start position {}",
                nsecs,
                start_position,
            );
            start_position
        });

        if self
            .last_position
            .map_or(true, |last_position| nsecs >= last_position)
        {
            self.last_position = Some(nsecs);
        } else {
            gst::fixme!(
                CAT,
                imp: imp,
                "New position {} < last position {}",
                nsecs,
                self.last_position.display(),
            );
        }
    }

    fn add_buffer_metadata(
        &mut self,
        imp: &MccParse,
        buffer: &mut gst::buffer::Buffer,
        timecode: &gst_video::ValidVideoTimeCode,
        framerate: gst::Fraction,
    ) {
        let buffer = buffer.get_mut().unwrap();
        gst_video::VideoTimeCodeMeta::add(buffer, timecode);

        self.update_timestamp(imp, timecode);

        buffer.set_pts(self.last_position);

        if self.discont {
            buffer.set_flags(gst::BufferFlags::DISCONT);
            self.discont = false;
        }

        buffer.set_duration(
            gst::ClockTime::SECOND.mul_div_ceil(framerate.denom() as u64, framerate.numer() as u64),
        );
    }

    fn create_events(
        &mut self,
        imp: &MccParse,
        format: Option<Format>,
        framerate: gst::Fraction,
    ) -> Vec<gst::Event> {
        let mut events = Vec::new();

        if self.need_flush_stop {
            let mut b = gst::event::FlushStop::builder(true);

            if let Some(seek_seqnum) = self.seek_seqnum {
                b = b.seqnum(seek_seqnum);
            }

            events.push(b.build());
            self.need_flush_stop = false;
        }

        if let Some(pull) = &mut self.pull {
            if pull.need_stream_start {
                events.push(gst::event::StreamStart::new(&pull.stream_id));
                pull.need_stream_start = false;
            }
        }

        if let Some(format) = format {
            if self.format != Some(format) {
                self.format = Some(format);

                let caps = match format {
                    Format::Cea708Cdp => gst::Caps::builder("closedcaption/x-cea-708")
                        .field("format", "cdp")
                        .field("framerate", framerate)
                        .build(),
                    Format::Cea608 => gst::Caps::builder("closedcaption/x-cea-608")
                        .field("format", "s334-1a")
                        .field("framerate", framerate)
                        .build(),
                };

                events.push(gst::event::Caps::new(&caps));
                gst::info!(CAT, imp: imp, "Caps changed to {:?}", &caps);
            }
        }

        if self.need_segment {
            let mut b = gst::event::Segment::builder(&self.segment);

            if let Some(seek_seqnum) = self.seek_seqnum {
                b = b.seqnum(seek_seqnum);
            }

            events.push(b.build());
            self.need_segment = false;
        }

        events.append(&mut self.pending_events);
        events
    }
}

pub struct MccParse {
    srcpad: gst::Pad,
    sinkpad: gst::Pad,
    state: Mutex<State>,
}

#[derive(Debug)]
struct OffsetVec {
    vec: Vec<u8>,
    offset: usize,
    len: usize,
}

impl AsRef<[u8]> for OffsetVec {
    fn as_ref(&self) -> &[u8] {
        &self.vec[self.offset..(self.offset + self.len)]
    }
}

impl AsMut<[u8]> for OffsetVec {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.vec[self.offset..(self.offset + self.len)]
    }
}

impl MccParse {
    fn handle_buffer(
        &self,
        buffer: Option<gst::Buffer>,
        scan_tc_rate: bool,
    ) -> Result<gst::FlowSuccess, gst::FlowError> {
        let mut state = self.state.lock().unwrap();

        let drain = if let Some(buffer) = buffer {
            let buffer = buffer.into_mapped_buffer_readable().map_err(|_| {
                gst::element_imp_error!(
                    self,
                    gst::ResourceError::Read,
                    ["Failed to map buffer readable"]
                );

                gst::FlowError::Error
            })?;

            state.reader.push(buffer);
            false
        } else {
            true
        };

        loop {
            let line = state.line(drain);
            match line {
                Ok(Some(MccLine::Caption(tc, Some(data)))) => {
                    assert!(!state.seeking);

                    gst::debug!(
                        CAT,
                        imp: self,
                        "Got caption buffer with timecode {:?} and size {}",
                        tc,
                        data.len()
                    );

                    if scan_tc_rate {
                        gst::element_imp_error!(
                            self,
                            gst::StreamError::Decode,
                            ["Found caption line while scanning for timecode rate"]
                        );

                        break Err(gst::FlowError::Error);
                    }

                    if data.len() < 3 {
                        gst::debug!(CAT, imp: self, "Too small caption packet: {}", data.len(),);
                        continue;
                    }

                    let format = match (data[0], data[1]) {
                        (0x61, 0x01) => Format::Cea708Cdp,
                        (0x61, 0x02) => Format::Cea608,
                        (did, sdid) => {
                            gst::debug!(CAT, imp: self, "Unknown DID {:x} SDID {:x}", did, sdid);
                            continue;
                        }
                    };

                    let len = data[2];
                    if data.len() < 3 + len as usize {
                        gst::debug!(
                            CAT,
                            imp: self,
                            "Too small caption packet: {} < {}",
                            data.len(),
                            3 + len,
                        );
                        continue;
                    }

                    state = self.handle_line(tc, data, format, state)?;
                }
                Ok(Some(MccLine::Caption(tc, None))) => {
                    assert!(state.seeking);

                    if scan_tc_rate {
                        gst::element_imp_error!(
                            self,
                            gst::StreamError::Decode,
                            ["Found caption line while scanning for timecode rate"]
                        );

                        break Err(gst::FlowError::Error);
                    }

                    state = self.handle_skipped_line(tc, state)?;
                }
                Ok(Some(MccLine::TimeCodeRate(rate, df))) => {
                    gst::debug!(
                        CAT,
                        imp: self,
                        "Got timecode rate {} (drop frame {})",
                        rate,
                        df
                    );
                    state.timecode_rate = Some((rate, df));

                    if scan_tc_rate {
                        break Ok(gst::FlowSuccess::Ok);
                    }
                }
                Ok(Some(line)) => {
                    gst::debug!(CAT, imp: self, "Got line '{:?}'", line);
                }
                Err((line, err)) => {
                    gst::element_imp_error!(
                        self,
                        gst::StreamError::Decode,
                        ["Couldn't parse line '{:?}': {:?}", line, err]
                    );

                    break Err(gst::FlowError::Error);
                }
                Ok(None) => {
                    if scan_tc_rate {
                        gst::element_imp_error!(
                            self,
                            gst::StreamError::Decode,
                            ["Found end of input while scanning for timecode rate"]
                        );

                        break Err(gst::FlowError::Error);
                    }

                    if drain && state.pull.is_some() {
                        break Err(gst::FlowError::Eos);
                    }
                    break Ok(gst::FlowSuccess::Ok);
                }
            }
        }
    }

    fn handle_skipped_line(
        &self,
        tc: TimeCode,
        mut state: MutexGuard<State>,
    ) -> Result<MutexGuard<State>, gst::FlowError> {
        let (framerate, drop_frame) = parse_timecode_rate(state.timecode_rate)?;
        let timecode = state.handle_timecode(self, framerate, drop_frame, tc)?;
        let nsecs = timecode.time_since_daily_jam();

        state.last_timecode = Some(timecode);

        if state
            .segment
            .start()
            .map_or(false, |seg_start| nsecs >= seg_start)
        {
            state.seeking = false;
            state.discont = true;
            state.replay_last_line = true;
            state.need_flush_stop = true;
        }

        drop(state);

        Ok(self.state.lock().unwrap())
    }

    fn handle_line(
        &self,
        tc: TimeCode,
        data: Vec<u8>,
        format: Format,
        mut state: MutexGuard<State>,
    ) -> Result<MutexGuard<State>, gst::FlowError> {
        let (framerate, drop_frame) = parse_timecode_rate(state.timecode_rate)?;
        let events = state.create_events(self, Some(format), framerate);
        let timecode = state.handle_timecode(self, framerate, drop_frame, tc)?;

        let len = data[2] as usize;
        let mut buffer = gst::Buffer::from_mut_slice(OffsetVec {
            vec: data,
            offset: 3,
            len,
        });

        state.add_buffer_metadata(self, &mut buffer, &timecode, framerate);

        // Update the last_timecode to the current one
        state.last_timecode = Some(timecode);

        let send_eos = state
            .segment
            .stop()
            .opt_lt(buffer.pts().opt_add(buffer.duration()))
            .unwrap_or(false);

        // Drop our state mutex while we push out buffers or events
        drop(state);

        for event in events {
            gst::debug!(CAT, imp: self, "Pushing event {:?}", event);
            self.srcpad.push_event(event);
        }

        self.srcpad.push(buffer).map_err(|err| {
            if err != gst::FlowError::Flushing && err != gst::FlowError::Eos {
                gst::error!(CAT, imp: self, "Pushing buffer returned {:?}", err);
            }
            err
        })?;

        if send_eos {
            return Err(gst::FlowError::Eos);
        }

        Ok(self.state.lock().unwrap())
    }

    fn sink_activate(&self, pad: &gst::Pad) -> Result<(), gst::LoggableError> {
        let mode = {
            let mut query = gst::query::Scheduling::new();
            let mut state = self.state.lock().unwrap();

            state.pull = None;

            if !pad.peer_query(&mut query) {
                gst::debug!(CAT, obj: pad, "Scheduling query failed on peer");
                gst::PadMode::Push
            } else if query
                .has_scheduling_mode_with_flags(gst::PadMode::Pull, gst::SchedulingFlags::SEEKABLE)
            {
                gst::debug!(CAT, obj: pad, "Activating in Pull mode");

                state.pull = Some(PullState::new(self, &self.srcpad));

                gst::PadMode::Pull
            } else {
                gst::debug!(CAT, obj: pad, "Activating in Push mode");
                gst::PadMode::Push
            }
        };

        pad.activate_mode(mode, true)?;
        Ok(())
    }

    fn start_task(&self) -> Result<(), gst::LoggableError> {
        let imp = self.ref_counted();
        let res = self.sinkpad.start_task(move || {
            imp.loop_fn();
        });
        if res.is_err() {
            return Err(gst::loggable_error!(CAT, "Failed to start pad task"));
        }
        Ok(())
    }

    fn sink_activatemode(
        &self,
        _pad: &gst::Pad,
        mode: gst::PadMode,
        active: bool,
    ) -> Result<(), gst::LoggableError> {
        if mode == gst::PadMode::Pull {
            if active {
                self.start_task()?;
            } else {
                let _ = self.sinkpad.stop_task();
            }
        }

        Ok(())
    }

    fn scan_duration(&self) -> Result<Option<ValidVideoTimeCode>, gst::LoggableError> {
        gst::debug!(CAT, imp: self, "Scanning duration");

        /* First let's query the bytes duration upstream */
        let mut q = gst::query::Duration::new(gst::Format::Bytes);

        if !self.sinkpad.peer_query(&mut q) {
            return Err(gst::loggable_error!(
                CAT,
                "Failed to query upstream duration"
            ));
        }

        let size = match q.result() {
            gst::GenericFormattedValue::Bytes(Some(size)) => *size,
            _ => {
                return Err(gst::loggable_error!(
                    CAT,
                    "Failed to query upstream duration"
                ));
            }
        };

        let mut offset = size;
        let mut buffers = Vec::new();
        let mut last_tc = None;

        loop {
            let scan_size = cmp::min(offset, 4096);

            offset -= scan_size;

            match self.sinkpad.pull_range(offset, scan_size as u32) {
                Ok(buffer) => {
                    buffers.push(buffer);
                }
                Err(flow) => {
                    return Err(gst::loggable_error!(
                        CAT,
                        "Failed to pull buffer while scanning duration: {:?}",
                        flow
                    ));
                }
            }

            let mut reader = LineReader::new();
            let mut parser = MccParser::new_scan_captions();

            for buf in buffers.iter().rev() {
                let buf = buf
                    .clone()
                    .into_mapped_buffer_readable()
                    .map_err(|_| gst::loggable_error!(CAT, "Failed to map buffer readable"))?;

                reader.push(buf);
            }

            while let Some(line) = reader.line_with_drain(true) {
                if let Ok(MccLine::Caption(tc, None)) =
                    parser.parse_line(line, false).map_err(|err| (line, err))
                {
                    let state = self.state.lock().unwrap();
                    let (framerate, drop_frame) = parse_timecode_rate(state.timecode_rate)
                        .map_err(|_| gst::loggable_error!(CAT, "Failed to parse timecode rate"))?;
                    if let Ok(mut timecode) = parse_timecode(framerate, drop_frame, tc) {
                        /* We're looking for the total duration */
                        timecode.increment_frame();
                        last_tc = Some(timecode);
                    }
                }
                /* We ignore everything else including errors */
            }

            if last_tc.is_some() || offset == 0 {
                gst::debug!(CAT, imp: self, "Duration scan done, last_tc: {:?}", last_tc);
                break (Ok(last_tc));
            }
        }
    }

    fn push_eos(&self) {
        let mut state = self.state.lock().unwrap();

        if state.seeking {
            state.need_flush_stop = true;
        }

        match parse_timecode_rate(state.timecode_rate) {
            Ok((framerate, _)) => {
                let mut events = state.create_events(self, None, framerate);
                let mut eos_event = gst::event::Eos::builder();

                if let Some(seek_seqnum) = state.seek_seqnum {
                    eos_event = eos_event.seqnum(seek_seqnum);
                }

                events.push(eos_event.build());

                // Drop our state mutex while we push out events
                drop(state);

                for event in events {
                    gst::debug!(CAT, imp: self, "Pushing event {:?}", event);
                    self.srcpad.push_event(event);
                }
            }
            Err(_) => {
                gst::element_imp_error!(
                    self,
                    gst::StreamError::Failed,
                    ["Streaming stopped, failed to parse timecode rate"]
                );
            }
        }
    }

    fn loop_fn(&self) {
        let mut state = self.state.lock().unwrap();
        let State {
            timecode_rate: ref tc_rate,
            ref mut pull,
            ..
        } = *state;
        let mut pull = pull.as_mut().unwrap();
        let scan_tc_rate = tc_rate.is_none() && pull.duration.is_none();
        let offset = pull.offset;

        pull.offset += 4096;

        drop(state);

        let buffer = match self.sinkpad.pull_range(offset, 4096) {
            Ok(buffer) => Some(buffer),
            Err(gst::FlowError::Eos) => None,
            Err(gst::FlowError::Flushing) => {
                gst::debug!(CAT, obj: self.sinkpad, "Pausing after pulling buffer, reason: flushing");

                let _ = self.sinkpad.pause_task();
                return;
            }
            Err(flow) => {
                gst::error!(CAT, obj: self.sinkpad, "Failed to pull, reason: {:?}", flow);

                gst::element_imp_error!(
                    self,
                    gst::StreamError::Failed,
                    ["Streaming stopped, failed to pull buffer"]
                );

                let _ = self.sinkpad.pause_task();
                return;
            }
        };

        match self.handle_buffer(buffer, scan_tc_rate) {
            Ok(_) => {
                let tc_rate = self.state.lock().unwrap().timecode_rate;
                if scan_tc_rate && tc_rate.is_some() {
                    match self.scan_duration() {
                        Ok(Some(tc)) => {
                            let mut state = self.state.lock().unwrap();
                            let mut pull = state.pull.as_mut().unwrap();
                            pull.duration = Some(tc.time_since_daily_jam());
                        }
                        Ok(None) => {
                            let mut state = self.state.lock().unwrap();
                            let mut pull = state.pull.as_mut().unwrap();
                            pull.duration = Some(gst::ClockTime::ZERO);
                        }
                        Err(err) => {
                            err.log();

                            gst::element_imp_error!(
                                self,
                                gst::StreamError::Decode,
                                ["Failed to scan duration"]
                            );

                            let _ = self.sinkpad.pause_task();
                        }
                    }
                }
            }
            Err(flow) => {
                match flow {
                    gst::FlowError::Flushing => {
                        gst::debug!(CAT, imp: self, "Pausing after flow {:?}", flow);
                    }
                    gst::FlowError::Eos => {
                        self.push_eos();

                        gst::debug!(CAT, imp: self, "Pausing after flow {:?}", flow);
                    }
                    _ => {
                        self.push_eos();

                        gst::error!(CAT, imp: self, "Pausing after flow {:?}", flow);

                        gst::element_imp_error!(
                            self,
                            gst::StreamError::Failed,
                            ["Streaming stopped, reason: {:?}", flow]
                        );
                    }
                }

                let _ = self.sinkpad.pause_task();
            }
        }
    }

    fn sink_chain(
        &self,
        pad: &gst::Pad,
        buffer: gst::Buffer,
    ) -> Result<gst::FlowSuccess, gst::FlowError> {
        gst::log!(CAT, obj: pad, "Handling buffer {:?}", buffer);

        self.handle_buffer(Some(buffer), false)
    }

    fn flush(&self, mut state: MutexGuard<State>) -> MutexGuard<State> {
        state.reader.clear();
        state.parser.reset();
        if let Some(pull) = &mut state.pull {
            pull.offset = 0;
        }
        state.segment = gst::FormattedSegment::new();
        state.need_segment = true;
        state.pending_events.clear();
        state.start_position = Some(gst::ClockTime::ZERO);
        state.last_position = None;
        state.last_timecode = None;
        state.timecode_rate = None;
        state.last_raw_line = [].to_vec();

        drop(state);

        self.state.lock().unwrap()
    }

    fn sink_event(&self, pad: &gst::Pad, event: gst::Event) -> bool {
        use gst::EventView;

        gst::log!(CAT, obj: pad, "Handling event {:?}", event);

        match event.view() {
            EventView::Caps(_) => {
                // We send a proper caps event from the chain function later
                gst::log!(CAT, obj: pad, "Dropping caps event");
                true
            }
            EventView::Segment(_) => {
                // We send a gst::Format::Time segment event later when needed
                gst::log!(CAT, obj: pad, "Dropping segment event");
                true
            }
            EventView::FlushStop(_) => {
                let state = self.state.lock().unwrap();
                let state = self.flush(state);
                drop(state);

                gst::Pad::event_default(pad, Some(&*self.obj()), event)
            }
            EventView::Eos(_) => {
                gst::log!(CAT, obj: pad, "Draining");
                if let Err(err) = self.handle_buffer(None, false) {
                    gst::error!(CAT, obj: pad, "Failed to drain parser: {:?}", err);
                }
                gst::Pad::event_default(pad, Some(&*self.obj()), event)
            }
            _ => {
                if event.is_sticky()
                    && !self.srcpad.has_current_caps()
                    && event.type_() > gst::EventType::Caps
                {
                    gst::log!(CAT, obj: pad, "Deferring sticky event until we have caps");
                    let mut state = self.state.lock().unwrap();
                    state.pending_events.push(event);
                    true
                } else {
                    gst::Pad::event_default(pad, Some(&*self.obj()), event)
                }
            }
        }
    }

    fn perform_seek(&self, event: &gst::event::Seek) -> bool {
        if self.state.lock().unwrap().pull.is_none() {
            gst::error!(CAT, imp: self, "seeking is only supported in pull mode");
            return false;
        }

        let (rate, flags, start_type, start, stop_type, stop) = event.get();

        let mut start: Option<gst::ClockTime> = match start.try_into() {
            Ok(start) => start,
            Err(_) => {
                gst::error!(CAT, imp: self, "seek has invalid format");
                return false;
            }
        };

        let mut stop: Option<gst::ClockTime> = match stop.try_into() {
            Ok(stop) => stop,
            Err(_) => {
                gst::error!(CAT, imp: self, "seek has invalid format");
                return false;
            }
        };

        if !flags.contains(gst::SeekFlags::FLUSH) {
            gst::error!(CAT, imp: self, "only flushing seeks are supported");
            return false;
        }

        if start_type == gst::SeekType::End || stop_type == gst::SeekType::End {
            gst::error!(CAT, imp: self, "Relative seeks are not supported");
            return false;
        }

        let seek_seqnum = event.seqnum();

        let event = gst::event::FlushStart::builder()
            .seqnum(seek_seqnum)
            .build();

        gst::debug!(CAT, imp: self, "Sending event {:?} upstream", event);
        self.sinkpad.push_event(event);

        let event = gst::event::FlushStart::builder()
            .seqnum(seek_seqnum)
            .build();

        gst::debug!(CAT, imp: self, "Pushing event {:?}", event);
        self.srcpad.push_event(event);

        let _ = self.sinkpad.pause_task();

        let mut state = self.state.lock().unwrap();
        let pull = state.pull.as_ref().unwrap();

        if start_type == gst::SeekType::Set {
            start = start.opt_min(pull.duration).or(start);
        }

        if stop_type == gst::SeekType::Set {
            stop = stop.opt_min(pull.duration).or(stop);
        }

        state.seeking = true;
        state.seek_seqnum = Some(seek_seqnum);

        state = self.flush(state);

        let event = gst::event::FlushStop::builder(true)
            .seqnum(seek_seqnum)
            .build();

        /* Drop our state while we push a serialized event upstream */
        drop(state);

        gst::debug!(CAT, imp: self, "Sending event {:?} upstream", event);
        self.sinkpad.push_event(event);

        state = self.state.lock().unwrap();

        state
            .segment
            .do_seek(rate, flags, start_type, start, stop_type, stop);

        match self.start_task() {
            Err(error) => {
                error.log();
                false
            }
            _ => true,
        }
    }

    fn src_event(&self, pad: &gst::Pad, event: gst::Event) -> bool {
        use gst::EventView;

        gst::log!(CAT, obj: pad, "Handling event {:?}", event);
        match event.view() {
            EventView::Seek(e) => self.perform_seek(e),
            _ => gst::Pad::event_default(pad, Some(&*self.obj()), event),
        }
    }

    fn src_query(&self, pad: &gst::Pad, query: &mut gst::QueryRef) -> bool {
        use gst::QueryViewMut;

        gst::log!(CAT, obj: pad, "Handling query {:?}", query);

        match query.view_mut() {
            QueryViewMut::Seeking(q) => {
                let state = self.state.lock().unwrap();

                let fmt = q.format();

                if fmt == gst::Format::Time {
                    if let Some(pull) = state.pull.as_ref() {
                        q.set(true, gst::ClockTime::ZERO, pull.duration);
                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            QueryViewMut::Position(q) => {
                // For Time answer ourselves, otherwise forward
                if q.format() == gst::Format::Time {
                    let state = self.state.lock().unwrap();
                    q.set(state.last_position);
                    true
                } else {
                    self.sinkpad.peer_query(query)
                }
            }
            QueryViewMut::Duration(q) => {
                // For Time answer ourselves, otherwise forward
                let state = self.state.lock().unwrap();
                if q.format() == gst::Format::Time {
                    if let Some(pull) = state.pull.as_ref() {
                        if pull.duration.is_some() {
                            q.set(state.pull.as_ref().unwrap().duration);
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    self.sinkpad.peer_query(query)
                }
            }
            _ => gst::Pad::query_default(pad, Some(&*self.obj()), query),
        }
    }
}

#[glib::object_subclass]
impl ObjectSubclass for MccParse {
    const NAME: &'static str = "GstMccParse";
    type Type = super::MccParse;
    type ParentType = gst::Element;

    fn with_class(klass: &Self::Class) -> Self {
        let templ = klass.pad_template("sink").unwrap();
        let sinkpad = gst::Pad::builder_from_template(&templ)
            .activate_function(|pad, parent| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || Err(gst::loggable_error!(CAT, "Panic activating sink pad")),
                    |parse| parse.sink_activate(pad),
                )
            })
            .activatemode_function(|pad, parent, mode, active| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || {
                        Err(gst::loggable_error!(
                            CAT,
                            "Panic activating sink pad with mode"
                        ))
                    },
                    |parse| parse.sink_activatemode(pad, mode, active),
                )
            })
            .chain_function(|pad, parent, buffer| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || Err(gst::FlowError::Error),
                    |parse| parse.sink_chain(pad, buffer),
                )
            })
            .event_function(|pad, parent, event| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || false,
                    |parse| parse.sink_event(pad, event),
                )
            })
            .build();

        let templ = klass.pad_template("src").unwrap();
        let srcpad = gst::Pad::builder_from_template(&templ)
            .event_function(|pad, parent, event| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || false,
                    |parse| parse.src_event(pad, event),
                )
            })
            .query_function(|pad, parent, query| {
                MccParse::catch_panic_pad_function(
                    parent,
                    || false,
                    |parse| parse.src_query(pad, query),
                )
            })
            .build();

        Self {
            srcpad,
            sinkpad,
            state: Mutex::new(State::default()),
        }
    }
}

impl ObjectImpl for MccParse {
    fn constructed(&self) {
        self.parent_constructed();

        let obj = self.obj();
        obj.add_pad(&self.sinkpad).unwrap();
        obj.add_pad(&self.srcpad).unwrap();
    }
}

impl GstObjectImpl for MccParse {}

impl ElementImpl for MccParse {
    fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
        static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
            gst::subclass::ElementMetadata::new(
                "Mcc Parse",
                "Parser/ClosedCaption",
                "Parses MCC Closed Caption Files",
                "Sebastian Dröge <sebastian@centricular.com>",
            )
        });

        Some(&*ELEMENT_METADATA)
    }

    fn pad_templates() -> &'static [gst::PadTemplate] {
        static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
            let mut caps = gst::Caps::new_empty();
            {
                let caps = caps.get_mut().unwrap();
                let framerate = gst::FractionRange::new(
                    gst::Fraction::new(1, std::i32::MAX),
                    gst::Fraction::new(std::i32::MAX, 1),
                );

                let s = gst::Structure::builder("closedcaption/x-cea-708")
                    .field("format", "cdp")
                    .field("framerate", framerate)
                    .build();
                caps.append_structure(s);

                let s = gst::Structure::builder("closedcaption/x-cea-608")
                    .field("format", "s334-1a")
                    .field("framerate", framerate)
                    .build();
                caps.append_structure(s);
            }
            let src_pad_template = gst::PadTemplate::new(
                "src",
                gst::PadDirection::Src,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();

            let caps = gst::Caps::builder("application/x-mcc")
                .field("version", gst::List::new([1i32, 2i32]))
                .build();
            let sink_pad_template = gst::PadTemplate::new(
                "sink",
                gst::PadDirection::Sink,
                gst::PadPresence::Always,
                &caps,
            )
            .unwrap();

            vec![src_pad_template, sink_pad_template]
        });

        PAD_TEMPLATES.as_ref()
    }

    fn change_state(
        &self,
        transition: gst::StateChange,
    ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
        gst::trace!(CAT, imp: self, "Changing state {:?}", transition);

        match transition {
            gst::StateChange::ReadyToPaused | gst::StateChange::PausedToReady => {
                // Reset the whole state
                let mut state = self.state.lock().unwrap();
                *state = State::default();
            }
            _ => (),
        }

        self.parent_change_state(transition)
    }
}