Abhishek Mehandiratta
Abhishek Mehandiratta

Reputation: 314

Auto delete .ts and .m3u8 files once client receives all .ts files

So I created an express server that gets an mp3 file (which is stored locally right now, but will be taken from mongo db later) and uses ffmpeg to make .m3u8 and .ts files. The files are successfully sent to the client and there are no errors while playing it on the client. I used hls.js to play these files in Chrome. But the server still has those files stored locally. Is there any way the server can know when to delete these files that it stored locally? There are a lot of files generated by ffmpeg so I can't just let them stay there forever.

I used the ffmpeg part of code from hls-server github repo.

my server file

index.js

// just used to run ffmpeg for conversion
var command = ffmpeg('inp.mp3')
  .on('start', function (commandLine) {
    console.log('command', commandLine);
  }).addOptions([
    '-c:a aac',
    '-b:a 64k',
    '-vn',
    '-hls_list_size 0',
    '-segment_time 10',
  ]).output('files\\output.m3u8');

var express = require('express');
var app = express();
// express middleware to serve individual .ts and .m3u8 files when requested
app.use(express.static('./files/'));

app.get('/', function (req, res) {
  command.on('end', function () {
    console.log('done');
    res.write(`
    <script src="https://cdn.jsdelivr.net/hls.js/latest/hls.min.js"></script>
    <script>
      function onLevelLoaded (event, data) {
        var level_duration = data.details.totalduration;
        console.log(level_duration, data);
      }
      if(Hls.isSupported()) {
        var audio = new Audio();
        var hls = new Hls();
        // requesting files from here
        hls.loadSource('http://localhost:8000/output.m3u8');
        hls.attachMedia(audio);
        hls.on(Hls.Events.LEVEL_LOADED, onLevelLoaded);
        hls.on(Hls.Events.FRAG_BUFFERED, (e, d) => {
          console.log(e, d);
        });
      }
    </script>
    `);
    res.end();
  }).run();
});

app.listen(8000);

Upvotes: 3

Views: 5487

Answers (2)

cieunteung
cieunteung

Reputation: 1791

you can use hls_delete_threshold

"-hls_time 10",
"-hls_list_size 3",
"-hls_delete_threshold 3", 
"-hls_flags delete_segments"

hls_delete_threshold size

Set the number of unreferenced segments to keep on disk before hls_flags delete_segments deletes them. Increase this to allow continue clients to download segments which were recently referenced in the playlist. Default value is 1, meaning segments older than hls_list_size+1 will be deleted.

Upvotes: 4

014
014

Reputation: 1

This is what I do in my ffmpeg process: -hls_list_size 6 -hls_flags delete_segments

That effectively rolls them. It automatically deletes the oldest one when creating a new one.

Now, I might be doing something wrong because I retain more than 6 files, but it certainly is deleting most of them.

Upvotes: 0

Related Questions