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

imp.rs « src « hlssink3 « net - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cf089d36d54086fa4a2f42dfab4e5573e5282158 (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
// Copyright (C) 2021 Rafael Caricio <rafael@caricio.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 crate::playlist::{Playlist, SegmentFormatter};
use crate::HlsSink3PlaylistType;
use chrono::{DateTime, Duration, Utc};
use gio::prelude::*;
use glib::subclass::prelude::*;
use gst::glib::once_cell::sync::Lazy;
use gst::prelude::*;
use gst::subclass::prelude::*;
use m3u8_rs::MediaPlaylistType;
use std::fs;
use std::io::Write;
use std::path;
use std::sync::{Arc, Mutex};

const DEFAULT_LOCATION: &str = "segment%05d.ts";
const DEFAULT_PLAYLIST_LOCATION: &str = "playlist.m3u8";
const DEFAULT_MAX_NUM_SEGMENT_FILES: u32 = 10;
const DEFAULT_TARGET_DURATION: u32 = 15;
const DEFAULT_PLAYLIST_LENGTH: u32 = 5;
const DEFAULT_PLAYLIST_TYPE: HlsSink3PlaylistType = HlsSink3PlaylistType::Unspecified;
const DEFAULT_I_FRAMES_ONLY_PLAYLIST: bool = false;
const DEFAULT_PROGRAM_DATE_TIME_TAG: bool = false;
const DEFAULT_CLOCK_TRACKING_FOR_PDT: bool = true;
const DEFAULT_SEND_KEYFRAME_REQUESTS: bool = true;

const SIGNAL_GET_PLAYLIST_STREAM: &str = "get-playlist-stream";
const SIGNAL_GET_FRAGMENT_STREAM: &str = "get-fragment-stream";
const SIGNAL_DELETE_FRAGMENT: &str = "delete-fragment";

static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
    gst::DebugCategory::new("hlssink3", gst::DebugColorFlags::empty(), Some("HLS sink"))
});

impl From<HlsSink3PlaylistType> for Option<MediaPlaylistType> {
    fn from(pl_type: HlsSink3PlaylistType) -> Self {
        use HlsSink3PlaylistType::*;
        match pl_type {
            Unspecified => None,
            Event => Some(MediaPlaylistType::Event),
            Vod => Some(MediaPlaylistType::Vod),
        }
    }
}

impl From<Option<&MediaPlaylistType>> for HlsSink3PlaylistType {
    fn from(inner_pl_type: Option<&MediaPlaylistType>) -> Self {
        use HlsSink3PlaylistType::*;
        match inner_pl_type {
            None | Some(MediaPlaylistType::Other(_)) => Unspecified,
            Some(MediaPlaylistType::Event) => Event,
            Some(MediaPlaylistType::Vod) => Vod,
        }
    }
}

struct Settings {
    location: String,
    segment_formatter: SegmentFormatter,
    playlist_location: String,
    playlist_root: Option<String>,
    playlist_length: u32,
    playlist_type: Option<MediaPlaylistType>,
    max_num_segment_files: usize,
    target_duration: u32,
    i_frames_only: bool,
    enable_program_date_time: bool,
    pdt_follows_pipeline_clock: bool,
    send_keyframe_requests: bool,

    splitmuxsink: gst::Element,
    giostreamsink: gst::Element,
    video_sink: bool,
    audio_sink: bool,
}

impl Default for Settings {
    fn default() -> Self {
        let splitmuxsink = gst::ElementFactory::make("splitmuxsink")
            .name("split_mux_sink")
            .build()
            .expect("Could not make element splitmuxsink");
        let giostreamsink = gst::ElementFactory::make("giostreamsink")
            .name("giostream_sink")
            .build()
            .expect("Could not make element giostreamsink");
        Self {
            location: String::from(DEFAULT_LOCATION),
            segment_formatter: SegmentFormatter::new(DEFAULT_LOCATION).unwrap(),
            playlist_location: String::from(DEFAULT_PLAYLIST_LOCATION),
            playlist_root: None,
            playlist_length: DEFAULT_PLAYLIST_LENGTH,
            playlist_type: None,
            max_num_segment_files: DEFAULT_MAX_NUM_SEGMENT_FILES as usize,
            target_duration: DEFAULT_TARGET_DURATION,
            send_keyframe_requests: DEFAULT_SEND_KEYFRAME_REQUESTS,
            i_frames_only: DEFAULT_I_FRAMES_ONLY_PLAYLIST,
            enable_program_date_time: DEFAULT_PROGRAM_DATE_TIME_TAG,
            pdt_follows_pipeline_clock: DEFAULT_CLOCK_TRACKING_FOR_PDT,

            splitmuxsink,
            giostreamsink,
            video_sink: false,
            audio_sink: false,
        }
    }
}

pub(crate) struct StartedState {
    base_date_time: Option<DateTime<Utc>>,
    pdt_base_running_time: Option<gst::ClockTime>,
    playlist: Playlist,
    fragment_opened_at: Option<gst::ClockTime>,
    fragment_running_time: Option<gst::ClockTime>,
    current_segment_location: Option<String>,
    old_segment_locations: Vec<String>,
}

impl StartedState {
    fn new(
        target_duration: f32,
        playlist_type: Option<MediaPlaylistType>,
        i_frames_only: bool,
    ) -> Self {
        Self {
            base_date_time: None,
            pdt_base_running_time: None,
            playlist: Playlist::new(target_duration, playlist_type, i_frames_only),
            current_segment_location: None,
            fragment_opened_at: None,
            fragment_running_time: None,
            old_segment_locations: Vec::new(),
        }
    }

    fn fragment_duration_since(&self, fragment_closed: gst::ClockTime) -> f32 {
        let segment_duration = fragment_closed - self.fragment_opened_at.unwrap();
        segment_duration.mseconds() as f32 / 1_000f32
    }
}

#[allow(clippy::large_enum_variant)]
enum State {
    Stopped,
    Started(StartedState),
}

impl Default for State {
    fn default() -> Self {
        Self::Stopped
    }
}

#[derive(Default)]
pub struct HlsSink3 {
    settings: Arc<Mutex<Settings>>,
    state: Arc<Mutex<State>>,
}

impl HlsSink3 {
    fn start(&self) {
        gst::info!(CAT, imp: self, "Starting");

        let (target_duration, playlist_type, i_frames_only) = {
            let settings = self.settings.lock().unwrap();
            (
                settings.target_duration as f32,
                settings.playlist_type.clone(),
                settings.i_frames_only,
            )
        };

        let mut state = self.state.lock().unwrap();
        if let State::Stopped = *state {
            *state = State::Started(StartedState::new(
                target_duration,
                playlist_type,
                i_frames_only,
            ));
        }
    }

    fn on_format_location(&self, fragment_id: u32) -> Result<String, String> {
        gst::info!(
            CAT,
            imp: self,
            "Starting the formatting of the fragment-id: {}",
            fragment_id
        );

        // TODO: Create method in state to simplify this boilerplate: `let state = self.state.started()?`
        let mut state_guard = self.state.lock().unwrap();
        let state = match &mut *state_guard {
            State::Stopped => return Err("Not in Started state".to_string()),
            State::Started(s) => s,
        };

        let settings = self.settings.lock().unwrap();
        let segment_file_location = settings.segment_formatter.segment(fragment_id);
        gst::trace!(
            CAT,
            imp: self,
            "Segment location formatted: {}",
            segment_file_location
        );

        state.current_segment_location = Some(segment_file_location.clone());

        let fragment_stream = self
            .obj()
            .emit_by_name::<Option<gio::OutputStream>>(
                SIGNAL_GET_FRAGMENT_STREAM,
                &[&segment_file_location],
            )
            .ok_or_else(|| String::from("Error while getting fragment stream"))?;

        settings
            .giostreamsink
            .set_property("stream", &fragment_stream);

        gst::info!(
            CAT,
            imp: self,
            "New segment location: {:?}",
            state.current_segment_location.as_ref()
        );
        Ok(segment_file_location)
    }

    fn new_file_stream<P>(&self, location: &P) -> Result<gio::OutputStream, String>
    where
        P: AsRef<path::Path>,
    {
        let file = fs::File::create(location).map_err(move |err| {
            let error_msg = gst::error_msg!(
                gst::ResourceError::OpenWrite,
                [
                    "Could not open file {} for writing: {}",
                    location.as_ref().to_str().unwrap(),
                    err.to_string(),
                ]
            );
            self.post_error_message(error_msg);
            err.to_string()
        })?;
        Ok(gio::WriteOutputStream::new(file).upcast())
    }

    fn delete_fragment<P>(&self, location: &P)
    where
        P: AsRef<path::Path>,
    {
        let _ = fs::remove_file(location).map_err(|err| {
            gst::warning!(
                CAT,
                imp: self,
                "Could not delete segment file: {}",
                err.to_string()
            );
        });
    }

    fn write_playlist(
        &self,
        fragment_closed_at: Option<gst::ClockTime>,
        date_time: Option<DateTime<Utc>>,
    ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
        gst::info!(CAT, imp: self, "Preparing to write new playlist");

        let mut state_guard = self.state.lock().unwrap();
        let state = match &mut *state_guard {
            State::Stopped => return Err(gst::StateChangeError),
            State::Started(s) => s,
        };

        gst::info!(CAT, imp: self, "COUNT {}", state.playlist.len());

        // Only add fragment if it's complete.
        if let Some(fragment_closed) = fragment_closed_at {
            let segment_filename = self.segment_filename(state);
            state.playlist.add_segment(
                segment_filename.clone(),
                state.fragment_duration_since(fragment_closed),
                date_time,
            );
            state.old_segment_locations.push(segment_filename);
        }

        let (playlist_location, max_num_segments, max_playlist_length) = {
            let settings = self.settings.lock().unwrap();
            (
                settings.playlist_location.clone(),
                settings.max_num_segment_files,
                settings.playlist_length as usize,
            )
        };

        state.playlist.update_playlist_state(max_playlist_length);

        // Acquires the playlist file handle so we can update it with new content. By default, this
        // is expected to be the same file every time.
        let mut playlist_stream = self
            .obj()
            .emit_by_name::<Option<gio::OutputStream>>(
                SIGNAL_GET_PLAYLIST_STREAM,
                &[&playlist_location],
            )
            .ok_or_else(|| {
                gst::error!(
                    CAT,
                    imp: self,
                    "Could not get stream to write playlist content",
                );
                gst::StateChangeError
            })?
            .into_write();

        state
            .playlist
            .write_to(&mut playlist_stream)
            .map_err(|err| {
                gst::error!(
                    CAT,
                    imp: self,
                    "Could not write new playlist: {}",
                    err.to_string()
                );
                gst::StateChangeError
            })?;
        playlist_stream.flush().map_err(|err| {
            gst::error!(
                CAT,
                imp: self,
                "Could not flush playlist: {}",
                err.to_string()
            );
            gst::StateChangeError
        })?;

        if state.playlist.is_type_undefined() {
            // Cleanup old segments from filesystem
            if state.old_segment_locations.len() > max_num_segments {
                for _ in 0..state.old_segment_locations.len() - max_num_segments {
                    let old_segment_location = state.old_segment_locations.remove(0);
                    if !self
                        .obj()
                        .emit_by_name::<bool>(SIGNAL_DELETE_FRAGMENT, &[&old_segment_location])
                    {
                        gst::error!(CAT, imp: self, "Could not delete fragment");
                    }
                }
            }
        }

        gst::debug!(CAT, imp: self, "Wrote new playlist file!");
        Ok(gst::StateChangeSuccess::Success)
    }

    fn segment_filename(&self, state: &mut StartedState) -> String {
        assert!(state.current_segment_location.is_some());
        let segment_filename = path_basename(state.current_segment_location.take().unwrap());

        let settings = self.settings.lock().unwrap();
        if let Some(playlist_root) = &settings.playlist_root {
            format!("{playlist_root}/{segment_filename}")
        } else {
            segment_filename
        }
    }

    fn write_final_playlist(&self) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
        gst::debug!(CAT, imp: self, "Preparing to write final playlist");
        self.write_playlist(None, None)
    }

    fn stop(&self) {
        gst::debug!(CAT, imp: self, "Stopping");

        let mut state = self.state.lock().unwrap();
        if let State::Started(_) = *state {
            *state = State::Stopped;
        }

        gst::debug!(CAT, imp: self, "Stopped");
    }
}

#[glib::object_subclass]
impl ObjectSubclass for HlsSink3 {
    const NAME: &'static str = "GstHlsSink3";
    type Type = super::HlsSink3;
    type ParentType = gst::Bin;
}

impl BinImpl for HlsSink3 {
    #[allow(clippy::single_match)]
    fn handle_message(&self, msg: gst::Message) {
        use gst::MessageView;

        match msg.view() {
            MessageView::Element(msg) => {
                let event_is_from_splitmuxsink = {
                    let settings = self.settings.lock().unwrap();

                    msg.src() == Some(settings.splitmuxsink.upcast_ref())
                };
                if !event_is_from_splitmuxsink {
                    return;
                }

                let s = msg.structure().unwrap();
                match s.name().as_str() {
                    "splitmuxsink-fragment-opened" => {
                        if let Ok(new_fragment_opened_at) = s.get::<gst::ClockTime>("running-time")
                        {
                            let mut state = self.state.lock().unwrap();
                            match &mut *state {
                                State::Stopped => {}
                                State::Started(state) => {
                                    state.fragment_opened_at = Some(new_fragment_opened_at)
                                }
                            };
                        }
                    }
                    "splitmuxsink-fragment-closed" => {
                        let s = msg.structure().unwrap();

                        let settings = self.settings.lock().unwrap();
                        let mut state_guard = self.state.lock().unwrap();
                        let state = match &mut *state_guard {
                            State::Stopped => {
                                gst::element_error!(
                                    self.obj(),
                                    gst::StreamError::Failed,
                                    ("Fragment closed in wrong state"),
                                    ["Fragment closed but element is in stopped state"]
                                );
                                return;
                            }
                            State::Started(state) => state,
                        };

                        let fragment_pts = state
                            .fragment_running_time
                            .expect("fragment running time must be set by format-location-full");

                        if state.pdt_base_running_time.is_none() {
                            state.pdt_base_running_time = state.fragment_running_time;
                        }
                        // Calculate the mapping from running time to UTC
                        // calculate base_date_time for each segment for !pdt_follows_pipeline_clock
                        // when pdt_follows_pipeline_clock is set, we calculate the base time every time
                        // this avoids the drift between pdt tag and external clock (if gst clock has skew w.r.t external clock)
                        if state.base_date_time.is_none() || !settings.pdt_follows_pipeline_clock {
                            let now_utc = Utc::now();
                            let now_gst = settings.giostreamsink.clock().unwrap().time().unwrap();
                            let pts_clock_time =
                                fragment_pts + settings.giostreamsink.base_time().unwrap();

                            let diff = now_gst.checked_sub(pts_clock_time).expect("time between fragments running time and current running time overflow");
                            let pts_utc = now_utc
                                .checked_sub_signed(Duration::nanoseconds(diff.nseconds() as i64))
                                .expect("offsetting the utc with gstreamer clock-diff overflow");

                            state.base_date_time = Some(pts_utc);
                        }

                        let fragment_date_time = if settings.enable_program_date_time
                            && state.pdt_base_running_time.is_some()
                        {
                            // Add the diff of running time to UTC time
                            // date_time = first_segment_utc + (current_seg_running_time - first_seg_running_time)
                            state
                                .base_date_time
                                .unwrap()
                                .checked_add_signed(Duration::nanoseconds(
                                    state
                                        .fragment_running_time
                                        .opt_checked_sub(state.pdt_base_running_time)
                                        .unwrap()
                                        .unwrap()
                                        .nseconds() as i64,
                                ))
                        } else {
                            None
                        };
                        drop(state_guard);
                        drop(settings);

                        if let Ok(fragment_closed_at) = s.get::<gst::ClockTime>("running-time") {
                            let _ =
                                self.write_playlist(Some(fragment_closed_at), fragment_date_time);
                        }
                    }
                    _ => {}
                }
            }
            _ => self.parent_handle_message(msg),
        }
    }
}

impl ObjectImpl for HlsSink3 {
    fn properties() -> &'static [glib::ParamSpec] {
        static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
            vec![
                glib::ParamSpecString::builder("location")
                    .nick("File Location")
                    .blurb("Location of the file to write")
                    .default_value(Some(DEFAULT_LOCATION))
                    .build(),
                glib::ParamSpecString::builder("playlist-location")
                    .nick("Playlist Location")
                    .blurb("Location of the playlist to write.")
                    .default_value(Some(DEFAULT_PLAYLIST_LOCATION))
                    .build(),
                glib::ParamSpecString::builder("playlist-root")
                    .nick("Playlist Root")
                    .blurb("Base path for the segments in the playlist file.")
                    .build(),
                glib::ParamSpecUInt::builder("max-files")
                    .nick("Max files")
                    .blurb("Maximum number of files to keep on disk. Once the maximum is reached, old files start to be deleted to make room for new ones.")
                    .build(),
                glib::ParamSpecUInt::builder("target-duration")
                    .nick("Target duration")
                    .blurb("The target duration in seconds of a segment/file. (0 - disabled, useful for management of segment duration by the streaming server)")
                    .default_value(DEFAULT_TARGET_DURATION)
                    .build(),
                glib::ParamSpecUInt::builder("playlist-length")
                    .nick("Playlist length")
                    .blurb("Length of HLS playlist. To allow players to conform to section 6.3.3 of the HLS specification, this should be at least 3. If set to 0, the playlist will be infinite.")
                    .default_value(DEFAULT_PLAYLIST_LENGTH)
                    .build(),
                glib::ParamSpecEnum::builder_with_default("playlist-type", DEFAULT_PLAYLIST_TYPE)
                    .nick("Playlist Type")
                    .blurb("The type of the playlist to use. When VOD type is set, the playlist will be live until the pipeline ends execution.")
                    .build(),
                glib::ParamSpecBoolean::builder("i-frames-only")
                    .nick("I-Frames only playlist")
                    .blurb("Each video segments is single iframe, So put EXT-X-I-FRAMES-ONLY tag in the playlist")
                    .default_value(DEFAULT_I_FRAMES_ONLY_PLAYLIST)
                    .build(),
                glib::ParamSpecBoolean::builder("enable-program-date-time")
                    .nick("add EXT-X-PROGRAM-DATE-TIME tag")
                    .blurb("put EXT-X-PROGRAM-DATE-TIME tag in the playlist")
                    .default_value(DEFAULT_PROGRAM_DATE_TIME_TAG)
                    .build(),
                glib::ParamSpecBoolean::builder("pdt-follows-pipeline-clock")
                    .nick("Whether Program-Date-Time should follow the pipeline clock")
                    .blurb("As there might be drift between the wallclock and pipeline clock, this controls whether the Program-Date-Time markers should follow the pipeline clock rate (true), or be skewed to match the wallclock rate (false).")
                    .default_value(DEFAULT_CLOCK_TRACKING_FOR_PDT)
                    .build(),
                glib::ParamSpecBoolean::builder("send-keyframe-requests")
                    .nick("Send Keyframe Requests")
                    .blurb("Send keyframe requests to ensure correct fragmentation. If this is disabled then the input must have keyframes in regular intervals.")
                    .default_value(DEFAULT_SEND_KEYFRAME_REQUESTS)
                    .build(),
            ]
        });

        PROPERTIES.as_ref()
    }

    fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
        let mut settings = self.settings.lock().unwrap();
        match pspec.name() {
            "location" => {
                settings.location = value
                    .get::<Option<String>>()
                    .expect("type checked upstream")
                    .unwrap_or_else(|| DEFAULT_LOCATION.into());
                settings.segment_formatter = SegmentFormatter::new(&settings.location).expect(
                    "A string containing `%03d` pattern must be used (can be any number from 0-9)",
                );
                settings
                    .splitmuxsink
                    .set_property("location", &settings.location);
            }
            "playlist-location" => {
                settings.playlist_location = value
                    .get::<Option<String>>()
                    .expect("type checked upstream")
                    .unwrap_or_else(|| String::from(DEFAULT_PLAYLIST_LOCATION));
            }
            "playlist-root" => {
                settings.playlist_root = value
                    .get::<Option<String>>()
                    .expect("type checked upstream");
            }
            "max-files" => {
                let max_files: u32 = value.get().expect("type checked upstream");
                settings.max_num_segment_files = max_files as usize;
            }
            "target-duration" => {
                settings.target_duration = value.get().expect("type checked upstream");
                settings
                    .splitmuxsink
                    .set_property("max-size-time", (settings.target_duration as u64).seconds());
            }
            "playlist-length" => {
                settings.playlist_length = value.get().expect("type checked upstream");
            }
            "playlist-type" => {
                settings.playlist_type = value
                    .get::<HlsSink3PlaylistType>()
                    .expect("type checked upstream")
                    .into();
            }
            "i-frames-only" => {
                settings.i_frames_only = value.get().expect("type checked upstream");
                if settings.i_frames_only && settings.audio_sink {
                    gst::element_error!(
                        self.obj(),
                        gst::StreamError::WrongType,
                        ("Invalid configuration"),
                        ["Audio not allowed for i-frames-only-stream"]
                    );
                }
            }
            "enable-program-date-time" => {
                settings.enable_program_date_time = value.get().expect("type checked upstream");
            }
            "pdt-follows-pipeline-clock" => {
                settings.pdt_follows_pipeline_clock = value.get().expect("type checked upstream");
            }
            "send-keyframe-requests" => {
                settings.send_keyframe_requests = value.get().expect("type checked upstream");
                settings
                    .splitmuxsink
                    .set_property("send-keyframe-requests", settings.send_keyframe_requests);
            }
            _ => unimplemented!(),
        };
    }

    fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
        let settings = self.settings.lock().unwrap();
        match pspec.name() {
            "location" => settings.location.to_value(),
            "playlist-location" => settings.playlist_location.to_value(),
            "playlist-root" => settings.playlist_root.to_value(),
            "max-files" => {
                let max_files = settings.max_num_segment_files as u32;
                max_files.to_value()
            }
            "target-duration" => settings.target_duration.to_value(),
            "playlist-length" => settings.playlist_length.to_value(),
            "playlist-type" => {
                let playlist_type: HlsSink3PlaylistType = settings.playlist_type.as_ref().into();
                playlist_type.to_value()
            }
            "i-frames-only" => settings.i_frames_only.to_value(),
            "enable-program-date-time" => settings.enable_program_date_time.to_value(),
            "pdt-follows-pipeline-clock" => settings.pdt_follows_pipeline_clock.to_value(),
            "send-keyframe-requests" => settings.send_keyframe_requests.to_value(),
            _ => unimplemented!(),
        }
    }

    fn signals() -> &'static [glib::subclass::Signal] {
        static SIGNALS: Lazy<Vec<glib::subclass::Signal>> = Lazy::new(|| {
            vec![
                glib::subclass::Signal::builder(SIGNAL_GET_PLAYLIST_STREAM)
                    .param_types([String::static_type()])
                    .return_type::<Option<gio::OutputStream>>()
                    .class_handler(|_, args| {
                        let element = args[0]
                            .get::<super::HlsSink3>()
                            .expect("playlist-stream signal arg");
                        let playlist_location =
                            args[1].get::<String>().expect("playlist-stream signal arg");
                        let hlssink3 = element.imp();

                        Some(hlssink3.new_file_stream(&playlist_location).ok().to_value())
                    })
                    .accumulator(|_hint, ret, value| {
                        // First signal handler wins
                        *ret = value.clone();
                        false
                    })
                    .build(),
                glib::subclass::Signal::builder(SIGNAL_GET_FRAGMENT_STREAM)
                    .param_types([String::static_type()])
                    .return_type::<Option<gio::OutputStream>>()
                    .class_handler(|_, args| {
                        let element = args[0]
                            .get::<super::HlsSink3>()
                            .expect("fragment-stream signal arg");
                        let fragment_location =
                            args[1].get::<String>().expect("fragment-stream signal arg");
                        let hlssink3 = element.imp();

                        Some(hlssink3.new_file_stream(&fragment_location).ok().to_value())
                    })
                    .accumulator(|_hint, ret, value| {
                        // First signal handler wins
                        *ret = value.clone();
                        false
                    })
                    .build(),
                glib::subclass::Signal::builder(SIGNAL_DELETE_FRAGMENT)
                    .param_types([String::static_type()])
                    .return_type::<bool>()
                    .class_handler(|_, args| {
                        let element = args[0].get::<super::HlsSink3>().expect("signal arg");
                        let fragment_location = args[1].get::<String>().expect("signal arg");
                        let hlssink3 = element.imp();

                        hlssink3.delete_fragment(&fragment_location);
                        Some(true.to_value())
                    })
                    .accumulator(|_hint, ret, value| {
                        // First signal handler wins
                        *ret = value.clone();
                        false
                    })
                    .build(),
            ]
        });

        SIGNALS.as_ref()
    }

    fn constructed(&self) {
        self.parent_constructed();

        let obj = self.obj();
        obj.set_element_flags(gst::ElementFlags::SINK);
        obj.set_suppressed_flags(gst::ElementFlags::SINK | gst::ElementFlags::SOURCE);

        let settings = self.settings.lock().unwrap();

        let mux = gst::ElementFactory::make("mpegtsmux")
            .name("mpeg-ts_mux")
            .build()
            .expect("Could not make element mpegtsmux");

        let location: Option<String> = None;
        settings.splitmuxsink.set_properties(&[
            ("location", &location),
            (
                "max-size-time",
                &(settings.target_duration as u64).seconds(),
            ),
            ("send-keyframe-requests", &settings.send_keyframe_requests),
            ("muxer", &mux),
            ("sink", &settings.giostreamsink),
            ("reset-muxer", &false),
        ]);

        obj.add(&settings.splitmuxsink).unwrap();
        let state = self.state.clone();
        settings
            .splitmuxsink
            .connect("format-location-full", false, {
                let self_weak = self.downgrade();
                move |args| {
                    let self_ = match self_weak.upgrade() {
                        Some(self_) => self_,
                        None => return Some(None::<String>.to_value()),
                    };
                    let fragment_id = args[1].get::<u32>().unwrap();
                    gst::info!(CAT, imp: self_, "Got fragment-id: {}", fragment_id);

                    let mut state_guard = state.lock().unwrap();
                    let state = match &mut *state_guard {
                        State::Stopped => {
                            gst::error!(
                                CAT,
                                imp: self_,
                                "on format location called with Stopped state"
                            );
                            return Some("unknown_segment".to_value());
                        }
                        State::Started(s) => s,
                    };

                    let sample = args[2].get::<gst::Sample>().unwrap();
                    let buffer = sample.buffer();
                    if let Some(buffer) = buffer {
                        let segment = sample
                            .segment()
                            .expect("segment not available")
                            .downcast_ref::<gst::ClockTime>()
                            .expect("no time segment");
                        state.fragment_running_time =
                            segment.to_running_time(buffer.pts().unwrap());
                    } else {
                        gst::warning!(
                            CAT,
                            imp: self_,
                            "buffer null for fragment-id: {}",
                            fragment_id
                        );
                    }
                    drop(state_guard);

                    match self_.on_format_location(fragment_id) {
                        Ok(segment_location) => Some(segment_location.to_value()),
                        Err(err) => {
                            gst::error!(CAT, imp: self_, "on format-location handler: {}", err);
                            Some("unknown_segment".to_value())
                        }
                    }
                }
            });
    }
}

impl GstObjectImpl for HlsSink3 {}

impl ElementImpl for HlsSink3 {
    fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
        static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
            gst::subclass::ElementMetadata::new(
                "HTTP Live Streaming sink",
                "Sink/Muxer",
                "HTTP Live Streaming sink",
                "Alessandro Decina <alessandro.d@gmail.com>, \
                Sebastian Dröge <sebastian@centricular.com>, \
                Rafael Caricio <rafael@caricio.com>",
            )
        });

        Some(&*ELEMENT_METADATA)
    }

    fn pad_templates() -> &'static [gst::PadTemplate] {
        static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
            let caps = gst::Caps::new_any();
            let video_pad_template = gst::PadTemplate::new(
                "video",
                gst::PadDirection::Sink,
                gst::PadPresence::Request,
                &caps,
            )
            .unwrap();

            let caps = gst::Caps::new_any();
            let audio_pad_template = gst::PadTemplate::new(
                "audio",
                gst::PadDirection::Sink,
                gst::PadPresence::Request,
                &caps,
            )
            .unwrap();

            vec![video_pad_template, audio_pad_template]
        });

        PAD_TEMPLATES.as_ref()
    }

    fn change_state(
        &self,
        transition: gst::StateChange,
    ) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
        if let gst::StateChange::NullToReady = transition {
            self.start();
        }

        let ret = self.parent_change_state(transition)?;

        match transition {
            gst::StateChange::PlayingToPaused => {
                let mut state = self.state.lock().unwrap();
                match &mut *state {
                    State::Stopped => (),
                    State::Started(state) => {
                        // reset mapping from rt to utc. during pause
                        // rt is stopped but utc keep moving so need to
                        // calculate the mapping again
                        state.pdt_base_running_time = None;
                        state.base_date_time = None
                    }
                }
            }
            gst::StateChange::PausedToReady => {
                let write_final = {
                    let mut state = self.state.lock().unwrap();
                    match &mut *state {
                        State::Stopped => false,
                        State::Started(state) => {
                            if state.playlist.is_rendering() {
                                state.playlist.stop();
                                true
                            } else {
                                false
                            }
                        }
                    }
                };

                if write_final {
                    // Don't fail transitioning to READY if this fails
                    let _ = self.write_final_playlist();
                }
            }
            gst::StateChange::ReadyToNull => {
                self.stop();
            }
            _ => (),
        }

        Ok(ret)
    }

    fn request_new_pad(
        &self,
        templ: &gst::PadTemplate,
        _name: Option<&str>,
        _caps: Option<&gst::Caps>,
    ) -> Option<gst::Pad> {
        let mut settings = self.settings.lock().unwrap();
        match templ.name_template() {
            "audio" => {
                if settings.audio_sink {
                    gst::debug!(
                        CAT,
                        imp: self,
                        "requested_new_pad: audio pad is already set"
                    );
                    return None;
                }
                if settings.i_frames_only {
                    gst::element_error!(
                        self.obj(),
                        gst::StreamError::WrongType,
                        ("Invalid configuration"),
                        ["Audio not allowed for i-frames-only-stream"]
                    );
                    return None;
                }

                let peer_pad = settings.splitmuxsink.request_pad_simple("audio_0").unwrap();
                let sink_pad = gst::GhostPad::from_template_with_target(templ, &peer_pad).unwrap();
                self.obj().add_pad(&sink_pad).unwrap();
                sink_pad.set_active(true).unwrap();
                settings.audio_sink = true;

                Some(sink_pad.upcast())
            }
            "video" => {
                if settings.video_sink {
                    gst::debug!(
                        CAT,
                        imp: self,
                        "requested_new_pad: video pad is already set"
                    );
                    return None;
                }
                let peer_pad = settings.splitmuxsink.request_pad_simple("video").unwrap();

                let sink_pad = gst::GhostPad::from_template_with_target(templ, &peer_pad).unwrap();
                self.obj().add_pad(&sink_pad).unwrap();
                sink_pad.set_active(true).unwrap();
                settings.video_sink = true;

                Some(sink_pad.upcast())
            }
            other_name => {
                gst::debug!(
                    CAT,
                    imp: self,
                    "requested_new_pad: name \"{}\" is not audio or video",
                    other_name
                );
                None
            }
        }
    }

    fn release_pad(&self, pad: &gst::Pad) {
        let mut settings = self.settings.lock().unwrap();

        if !settings.audio_sink && !settings.video_sink {
            return;
        }

        let ghost_pad = pad.downcast_ref::<gst::GhostPad>().unwrap();
        if let Some(peer) = ghost_pad.target() {
            settings.splitmuxsink.release_request_pad(&peer);
        }

        pad.set_active(false).unwrap();
        self.obj().remove_pad(pad).unwrap();

        if "audio" == ghost_pad.name() {
            settings.audio_sink = false;
        } else {
            settings.video_sink = false;
        }
    }
}

/// The content of the last item of a path separated by `/` character.
fn path_basename(name: impl AsRef<str>) -> String {
    name.as_ref().split('/').last().unwrap().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_extract_basenames() {
        for (input, output) in [
            ("", ""),
            ("value", "value"),
            ("/my/nice/path.ts", "path.ts"),
            ("file.ts", "file.ts"),
            ("https://localhost/output/file.vtt", "file.vtt"),
        ] {
            assert_eq!(path_basename(input), output);
        }
    }
}