My task is to create HLS live stream from jpeg frames using gstreamer. Frames are continously added to my temporary directory (/tmp/frames). I can't use hlssink plugin because encoding runs faster than new frames appears and pipeline stops than reaches last frame at the moment.
So my solution was to write script which will use simple filesink plugin and manually maintain playlist file. In Python it looks like this:
# pipeline function
def convert_frames_to_video_pipeline(dir_of_frames: Path, start_frame_index: int, video_files_location: Path, frame_filename_template: typing.Text, video_file_num: int):
filename = f"file{video_file_num}.mp4"
frames_per_sec = 25
omxh264_pipeline = f"gst-launch-1.0 multifilesrc location={dir_of_frames / frame_filename_template} start-index={start_frame_index} caps=\"image/jpeg,framerate={frames_per_sec}/1\" !" \
" jpegdec ! videoconvert ! videorate ! omxh264enc ! h264parse ! mpegtsmux ! " \
f" filesink location={video_files_location / filename}"
compl_process = subprocess.run(omxh264_pipeline, shell=True)
return filename
# maintain playlist file function
def update_playlist(filename: typing.Text, video_dir: Path, videofiles_names: typing.List, last_video_file_num: int):
ext_x_version = 4
videofile_duration = 4.
# generate playlist file
file_lines = ["#EXTM3U"]
file_lines.append(f"#EXT-X-VERSION:{ext_x_version}")
file_lines.append(f'#EXT-X-TARGETDURATION:{float(videofile_duration)}')
file_lines.append(f'#EXT-X-MEDIA-SEQUENCE:{last_video_file_num - len(videofiles_names) + 1}')
for videofile_name in videofiles_names:
file_lines.append(f'#EXTINF:{float(videofile_duration)},')
file_lines.append(videofile_name)
with open(video_dir / filename, 'w') as playlist_file:
playlist_file.write('\n'.join(file_lines))
Both functions runs every couple of seconds to produce new mp4 segment for HLS and to update playlist file. Playlist file template I get from Apple official instructions. Example of playlist follows:
#EXTM3U
#EXT-X-VERSION:4
#EXT-X-TARGETDURATION:4.0
#EXT-X-MEDIA-SEQUENCE:416
#EXTINF:4.0,
file416.mp4
#EXTINF:4.0,
file417.mp4
#EXTINF:4.0,
file418.mp4
#EXTINF:4.0,
file419.mp4
#EXTINF:4.0,
file420.mp4
The problem is that none of players I used (HLS.js, VLC, MPV) won't play playlist correctly. They play some of the segments then loading of new segments stops forever. HLS.js says that
MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX
and MPV warns that [ffmpeg/demuxer] mpegts: DTS 324108000 < 324172800 out of order [ffmpeg/demuxer] hls: DTS 324108000 < 324172800 out of order
and Invalid video timestamp: 0.720000 -> 0.000000
.