1 /*
2  * Live smooth streaming fragmenter
3  * Copyright (c) 2012 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "config.h"
23 
24 #include <float.h>
25 
26 #include "avformat.h"
27 #include "internal.h"
28 #include "os_support.h"
29 
30 #if HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 
34 #include "avc.h"
35 #include "url.h"
36 #include "isom.h"
37 
38 #include "libavutil/opt.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/intreadwrite.h"
42 
43 typedef struct {
44     char file[1024];
45     char infofile[1024];
46     int64_t start_time, duration;
47     int n;
48     int64_t start_pos, size;
49 } Fragment;
50 
51 typedef struct {
52     AVFormatContext *ctx;
53     int ctx_inited;
54     char dirname[1024];
55     uint8_t iobuf[32768];
56     URLContext *out;  // Current output stream where all output is written
57     URLContext *out2; // Auxiliary output stream where all output is also written
58     URLContext *tail_out; // The actual main output stream, if we're currently seeked back to write elsewhere
59     int64_t tail_pos, cur_pos, cur_start_pos;
60     int packets_written;
61     const char *stream_type_tag;
62     int nb_fragments, fragments_size, fragment_index;
63     Fragment **fragments;
64 
65     const char *fourcc;
66     char *private_str;
67     int packet_size;
68     int audio_tag;
69 } OutputStream;
70 
71 typedef struct {
72     const AVClass *class;  /* Class for private options. */
73     int window_size;
74     int extra_window_size;
75     int lookahead_count;
76     int min_frag_duration;
77     int remove_at_exit;
78     OutputStream *streams;
79     int has_video, has_audio;
80     int nb_fragments;
81 } SmoothStreamingContext;
82 
ism_write(void * opaque,uint8_t * buf,int buf_size)83 static int ism_write(void *opaque, uint8_t *buf, int buf_size)
84 {
85     OutputStream *os = opaque;
86     if (os->out)
87         ffurl_write(os->out, buf, buf_size);
88     if (os->out2)
89         ffurl_write(os->out2, buf, buf_size);
90     os->cur_pos += buf_size;
91     if (os->cur_pos >= os->tail_pos)
92         os->tail_pos = os->cur_pos;
93     return buf_size;
94 }
95 
ism_seek(void * opaque,int64_t offset,int whence)96 static int64_t ism_seek(void *opaque, int64_t offset, int whence)
97 {
98     OutputStream *os = opaque;
99     int i;
100     if (whence != SEEK_SET)
101         return AVERROR(ENOSYS);
102     if (os->tail_out) {
103         if (os->out) {
104             ffurl_close(os->out);
105         }
106         if (os->out2) {
107             ffurl_close(os->out2);
108         }
109         os->out = os->tail_out;
110         os->out2 = NULL;
111         os->tail_out = NULL;
112     }
113     if (offset >= os->cur_start_pos) {
114         if (os->out)
115             ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
116         os->cur_pos = offset;
117         return offset;
118     }
119     for (i = os->nb_fragments - 1; i >= 0; i--) {
120         Fragment *frag = os->fragments[i];
121         if (offset >= frag->start_pos && offset < frag->start_pos + frag->size) {
122             int ret;
123             AVDictionary *opts = NULL;
124             os->tail_out = os->out;
125             av_dict_set(&opts, "truncate", "0", 0);
126             ret = ffurl_open(&os->out, frag->file, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
127             av_dict_free(&opts);
128             if (ret < 0) {
129                 os->out = os->tail_out;
130                 os->tail_out = NULL;
131                 return ret;
132             }
133             av_dict_set(&opts, "truncate", "0", 0);
134             ffurl_open(&os->out2, frag->infofile, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
135             av_dict_free(&opts);
136             ffurl_seek(os->out, offset - frag->start_pos, SEEK_SET);
137             if (os->out2)
138                 ffurl_seek(os->out2, offset - frag->start_pos, SEEK_SET);
139             os->cur_pos = offset;
140             return offset;
141         }
142     }
143     return AVERROR(EIO);
144 }
145 
get_private_data(OutputStream * os)146 static void get_private_data(OutputStream *os)
147 {
148     AVCodecContext *codec = os->ctx->streams[0]->codec;
149     uint8_t *ptr = codec->extradata;
150     int size = codec->extradata_size;
151     int i;
152     if (codec->codec_id == AV_CODEC_ID_H264) {
153         ff_avc_write_annexb_extradata(ptr, &ptr, &size);
154         if (!ptr)
155             ptr = codec->extradata;
156     }
157     if (!ptr)
158         return;
159     os->private_str = av_mallocz(2*size + 1);
160     if (!os->private_str)
161         goto fail;
162     for (i = 0; i < size; i++)
163         snprintf(&os->private_str[2*i], 3, "%02x", ptr[i]);
164 fail:
165     if (ptr != codec->extradata)
166         av_free(ptr);
167 }
168 
ism_free(AVFormatContext * s)169 static void ism_free(AVFormatContext *s)
170 {
171     SmoothStreamingContext *c = s->priv_data;
172     int i, j;
173     if (!c->streams)
174         return;
175     for (i = 0; i < s->nb_streams; i++) {
176         OutputStream *os = &c->streams[i];
177         ffurl_close(os->out);
178         ffurl_close(os->out2);
179         ffurl_close(os->tail_out);
180         os->out = os->out2 = os->tail_out = NULL;
181         if (os->ctx && os->ctx_inited)
182             av_write_trailer(os->ctx);
183         if (os->ctx && os->ctx->pb)
184             av_free(os->ctx->pb);
185         if (os->ctx)
186             avformat_free_context(os->ctx);
187         av_free(os->private_str);
188         for (j = 0; j < os->nb_fragments; j++)
189             av_free(os->fragments[j]);
190         av_free(os->fragments);
191     }
192     av_freep(&c->streams);
193 }
194 
output_chunk_list(OutputStream * os,AVIOContext * out,int final,int skip,int window_size)195 static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
196 {
197     int removed = 0, i, start = 0;
198     if (os->nb_fragments <= 0)
199         return;
200     if (os->fragments[0]->n > 0)
201         removed = 1;
202     if (final)
203         skip = 0;
204     if (window_size)
205         start = FFMAX(os->nb_fragments - skip - window_size, 0);
206     for (i = start; i < os->nb_fragments - skip; i++) {
207         Fragment *frag = os->fragments[i];
208         if (!final || removed)
209             avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
210         else
211             avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
212     }
213 }
214 
write_manifest(AVFormatContext * s,int final)215 static int write_manifest(AVFormatContext *s, int final)
216 {
217     SmoothStreamingContext *c = s->priv_data;
218     AVIOContext *out;
219     char filename[1024], temp_filename[1024];
220     int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
221     int64_t duration = 0;
222 
223     snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
224     snprintf(temp_filename, sizeof(temp_filename), "%s/Manifest.tmp", s->filename);
225     ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
226     if (ret < 0) {
227         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
228         return ret;
229     }
230     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
231     for (i = 0; i < s->nb_streams; i++) {
232         OutputStream *os = &c->streams[i];
233         if (os->nb_fragments > 0) {
234             Fragment *last = os->fragments[os->nb_fragments - 1];
235             duration = last->start_time + last->duration;
236         }
237         if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
238             video_chunks = os->nb_fragments;
239             video_streams++;
240         } else {
241             audio_chunks = os->nb_fragments;
242             audio_streams++;
243         }
244     }
245     if (!final) {
246         duration = 0;
247         video_chunks = audio_chunks = 0;
248     }
249     if (c->window_size) {
250         video_chunks = FFMIN(video_chunks, c->window_size);
251         audio_chunks = FFMIN(audio_chunks, c->window_size);
252     }
253     avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
254     if (!final)
255         avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
256     avio_printf(out, ">\n");
257     if (c->has_video) {
258         int last = -1, index = 0;
259         avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
260         for (i = 0; i < s->nb_streams; i++) {
261             OutputStream *os = &c->streams[i];
262             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
263                 continue;
264             last = i;
265             avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->width, s->streams[i]->codec->height, os->private_str);
266             index++;
267         }
268         output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
269         avio_printf(out, "</StreamIndex>\n");
270     }
271     if (c->has_audio) {
272         int last = -1, index = 0;
273         avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
274         for (i = 0; i < s->nb_streams; i++) {
275             OutputStream *os = &c->streams[i];
276             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
277                 continue;
278             last = i;
279             avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->sample_rate, s->streams[i]->codec->channels, os->packet_size, os->audio_tag, os->private_str);
280             index++;
281         }
282         output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
283         avio_printf(out, "</StreamIndex>\n");
284     }
285     avio_printf(out, "</SmoothStreamingMedia>\n");
286     avio_flush(out);
287     avio_close(out);
288     rename(temp_filename, filename);
289     return 0;
290 }
291 
ism_write_header(AVFormatContext * s)292 static int ism_write_header(AVFormatContext *s)
293 {
294     SmoothStreamingContext *c = s->priv_data;
295     int ret = 0, i;
296     AVOutputFormat *oformat;
297 
298     if (mkdir(s->filename, 0777) == -1 && errno != EEXIST) {
299         av_log(s, AV_LOG_ERROR, "mkdir failed\n");
300         ret = AVERROR(errno);
301         goto fail;
302     }
303 
304     oformat = av_guess_format("ismv", NULL, NULL);
305     if (!oformat) {
306         ret = AVERROR_MUXER_NOT_FOUND;
307         goto fail;
308     }
309 
310     c->streams = av_mallocz_array(s->nb_streams, sizeof(*c->streams));
311     if (!c->streams) {
312         ret = AVERROR(ENOMEM);
313         goto fail;
314     }
315 
316     for (i = 0; i < s->nb_streams; i++) {
317         OutputStream *os = &c->streams[i];
318         AVFormatContext *ctx;
319         AVStream *st;
320         AVDictionary *opts = NULL;
321 
322         if (!s->streams[i]->codec->bit_rate) {
323             av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
324             ret = AVERROR(EINVAL);
325             goto fail;
326         }
327         snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codec->bit_rate);
328         if (mkdir(os->dirname, 0777) == -1 && errno != EEXIST) {
329             ret = AVERROR(errno);
330             av_log(s, AV_LOG_ERROR, "mkdir failed\n");
331             goto fail;
332         }
333 
334         ctx = avformat_alloc_context();
335         if (!ctx) {
336             ret = AVERROR(ENOMEM);
337             goto fail;
338         }
339         os->ctx = ctx;
340         ctx->oformat = oformat;
341         ctx->interrupt_callback = s->interrupt_callback;
342 
343         if (!(st = avformat_new_stream(ctx, NULL))) {
344             ret = AVERROR(ENOMEM);
345             goto fail;
346         }
347         avcodec_copy_context(st->codec, s->streams[i]->codec);
348         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
349 
350         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, ism_write, ism_seek);
351         if (!ctx->pb) {
352             ret = AVERROR(ENOMEM);
353             goto fail;
354         }
355 
356         av_dict_set_int(&opts, "ism_lookahead", c->lookahead_count, 0);
357         av_dict_set(&opts, "movflags", "frag_custom", 0);
358         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
359              goto fail;
360         }
361         os->ctx_inited = 1;
362         avio_flush(ctx->pb);
363         av_dict_free(&opts);
364         s->streams[i]->time_base = st->time_base;
365         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
366             c->has_video = 1;
367             os->stream_type_tag = "video";
368             if (st->codec->codec_id == AV_CODEC_ID_H264) {
369                 os->fourcc = "H264";
370             } else if (st->codec->codec_id == AV_CODEC_ID_VC1) {
371                 os->fourcc = "WVC1";
372             } else {
373                 av_log(s, AV_LOG_ERROR, "Unsupported video codec\n");
374                 ret = AVERROR(EINVAL);
375                 goto fail;
376             }
377         } else {
378             c->has_audio = 1;
379             os->stream_type_tag = "audio";
380             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
381                 os->fourcc = "AACL";
382                 os->audio_tag = 0xff;
383             } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
384                 os->fourcc = "WMAP";
385                 os->audio_tag = 0x0162;
386             } else {
387                 av_log(s, AV_LOG_ERROR, "Unsupported audio codec\n");
388                 ret = AVERROR(EINVAL);
389                 goto fail;
390             }
391             os->packet_size = st->codec->block_align ? st->codec->block_align : 4;
392         }
393         get_private_data(os);
394     }
395 
396     if (!c->has_video && c->min_frag_duration <= 0) {
397         av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");
398         ret = AVERROR(EINVAL);
399     }
400     ret = write_manifest(s, 0);
401 
402 fail:
403     if (ret)
404         ism_free(s);
405     return ret;
406 }
407 
parse_fragment(AVFormatContext * s,const char * filename,int64_t * start_ts,int64_t * duration,int64_t * moof_size,int64_t size)408 static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)
409 {
410     AVIOContext *in;
411     int ret;
412     uint32_t len;
413     if ((ret = avio_open2(&in, filename, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
414         return ret;
415     ret = AVERROR(EIO);
416     *moof_size = avio_rb32(in);
417     if (*moof_size < 8 || *moof_size > size)
418         goto fail;
419     if (avio_rl32(in) != MKTAG('m','o','o','f'))
420         goto fail;
421     len = avio_rb32(in);
422     if (len > *moof_size)
423         goto fail;
424     if (avio_rl32(in) != MKTAG('m','f','h','d'))
425         goto fail;
426     avio_seek(in, len - 8, SEEK_CUR);
427     avio_rb32(in); /* traf size */
428     if (avio_rl32(in) != MKTAG('t','r','a','f'))
429         goto fail;
430     while (avio_tell(in) < *moof_size) {
431         uint32_t len = avio_rb32(in);
432         uint32_t tag = avio_rl32(in);
433         int64_t end = avio_tell(in) + len - 8;
434         if (len < 8 || len >= *moof_size)
435             goto fail;
436         if (tag == MKTAG('u','u','i','d')) {
437             static const uint8_t tfxd[] = {
438                 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
439                 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
440             };
441             uint8_t uuid[16];
442             avio_read(in, uuid, 16);
443             if (!memcmp(uuid, tfxd, 16) && len >= 8 + 16 + 4 + 16) {
444                 avio_seek(in, 4, SEEK_CUR);
445                 *start_ts = avio_rb64(in);
446                 *duration = avio_rb64(in);
447                 ret = 0;
448                 break;
449             }
450         }
451         avio_seek(in, end, SEEK_SET);
452     }
453 fail:
454     avio_close(in);
455     return ret;
456 }
457 
add_fragment(OutputStream * os,const char * file,const char * infofile,int64_t start_time,int64_t duration,int64_t start_pos,int64_t size)458 static int add_fragment(OutputStream *os, const char *file, const char *infofile, int64_t start_time, int64_t duration, int64_t start_pos, int64_t size)
459 {
460     int err;
461     Fragment *frag;
462     if (os->nb_fragments >= os->fragments_size) {
463         os->fragments_size = (os->fragments_size + 1) * 2;
464         if ((err = av_reallocp(&os->fragments, sizeof(*os->fragments) *
465                                os->fragments_size)) < 0) {
466             os->fragments_size = 0;
467             os->nb_fragments = 0;
468             return err;
469         }
470     }
471     frag = av_mallocz(sizeof(*frag));
472     if (!frag)
473         return AVERROR(ENOMEM);
474     av_strlcpy(frag->file, file, sizeof(frag->file));
475     av_strlcpy(frag->infofile, infofile, sizeof(frag->infofile));
476     frag->start_time = start_time;
477     frag->duration = duration;
478     frag->start_pos = start_pos;
479     frag->size = size;
480     frag->n = os->fragment_index;
481     os->fragments[os->nb_fragments++] = frag;
482     os->fragment_index++;
483     return 0;
484 }
485 
copy_moof(AVFormatContext * s,const char * infile,const char * outfile,int64_t size)486 static int copy_moof(AVFormatContext *s, const char* infile, const char *outfile, int64_t size)
487 {
488     AVIOContext *in, *out;
489     int ret = 0;
490     if ((ret = avio_open2(&in, infile, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
491         return ret;
492     if ((ret = avio_open2(&out, outfile, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL)) < 0) {
493         avio_close(in);
494         return ret;
495     }
496     while (size > 0) {
497         uint8_t buf[8192];
498         int n = FFMIN(size, sizeof(buf));
499         n = avio_read(in, buf, n);
500         if (n <= 0) {
501             ret = AVERROR(EIO);
502             break;
503         }
504         avio_write(out, buf, n);
505         size -= n;
506     }
507     avio_flush(out);
508     avio_close(out);
509     avio_close(in);
510     return ret;
511 }
512 
ism_flush(AVFormatContext * s,int final)513 static int ism_flush(AVFormatContext *s, int final)
514 {
515     SmoothStreamingContext *c = s->priv_data;
516     int i, ret = 0;
517 
518     for (i = 0; i < s->nb_streams; i++) {
519         OutputStream *os = &c->streams[i];
520         char filename[1024], target_filename[1024], header_filename[1024];
521         int64_t start_pos = os->tail_pos, size;
522         int64_t start_ts, duration, moof_size;
523         if (!os->packets_written)
524             continue;
525 
526         snprintf(filename, sizeof(filename), "%s/temp", os->dirname);
527         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
528         if (ret < 0)
529             break;
530         os->cur_start_pos = os->tail_pos;
531         av_write_frame(os->ctx, NULL);
532         avio_flush(os->ctx->pb);
533         os->packets_written = 0;
534         if (!os->out || os->tail_out)
535             return AVERROR(EIO);
536 
537         ffurl_close(os->out);
538         os->out = NULL;
539         size = os->tail_pos - start_pos;
540         if ((ret = parse_fragment(s, filename, &start_ts, &duration, &moof_size, size)) < 0)
541             break;
542         snprintf(header_filename, sizeof(header_filename), "%s/FragmentInfo(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
543         snprintf(target_filename, sizeof(target_filename), "%s/Fragments(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
544         copy_moof(s, filename, header_filename, moof_size);
545         rename(filename, target_filename);
546         add_fragment(os, target_filename, header_filename, start_ts, duration, start_pos, size);
547     }
548 
549     if (c->window_size || (final && c->remove_at_exit)) {
550         for (i = 0; i < s->nb_streams; i++) {
551             OutputStream *os = &c->streams[i];
552             int j;
553             int remove = os->nb_fragments - c->window_size - c->extra_window_size - c->lookahead_count;
554             if (final && c->remove_at_exit)
555                 remove = os->nb_fragments;
556             if (remove > 0) {
557                 for (j = 0; j < remove; j++) {
558                     unlink(os->fragments[j]->file);
559                     unlink(os->fragments[j]->infofile);
560                     av_free(os->fragments[j]);
561                 }
562                 os->nb_fragments -= remove;
563                 memmove(os->fragments, os->fragments + remove, os->nb_fragments * sizeof(*os->fragments));
564             }
565             if (final && c->remove_at_exit)
566                 rmdir(os->dirname);
567         }
568     }
569 
570     if (ret >= 0)
571         ret = write_manifest(s, final);
572     return ret;
573 }
574 
ism_write_packet(AVFormatContext * s,AVPacket * pkt)575 static int ism_write_packet(AVFormatContext *s, AVPacket *pkt)
576 {
577     SmoothStreamingContext *c = s->priv_data;
578     AVStream *st = s->streams[pkt->stream_index];
579     OutputStream *os = &c->streams[pkt->stream_index];
580     int64_t end_dts = (c->nb_fragments + LLN(1)) * c->min_frag_duration;
581     int ret;
582 
583     if (st->first_dts == AV_NOPTS_VALUE)
584         st->first_dts = pkt->dts;
585 
586 	if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
587         av_compare_ts(pkt->dts - st->first_dts, st->time_base,
588                       end_dts, AV_TIME_BASE_Q) >= 0 &&
589         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
590 
591         if ((ret = ism_flush(s, 0)) < 0)
592             return ret;
593         c->nb_fragments++;
594     }
595 
596     os->packets_written++;
597     return ff_write_chained(os->ctx, 0, pkt, s, 0);
598 }
599 
ism_write_trailer(AVFormatContext * s)600 static int ism_write_trailer(AVFormatContext *s)
601 {
602     SmoothStreamingContext *c = s->priv_data;
603     ism_flush(s, 1);
604 
605     if (c->remove_at_exit) {
606         char filename[1024];
607         snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
608         unlink(filename);
609         rmdir(s->filename);
610     }
611 
612     ism_free(s);
613     return 0;
614 }
615 
616 #define OFFSET(x) offsetof(SmoothStreamingContext, x)
617 #define E AV_OPT_FLAG_ENCODING_PARAM
618 static const AVOption options[] = {
619 	{ "window_size", "number of fragments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
620     { "extra_window_size", "number of fragments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
621     { "lookahead_count", "number of lookahead fragments", OFFSET(lookahead_count), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, E },
622     { "min_frag_duration", "minimum fragment duration (in microseconds)", OFFSET(min_frag_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
623     { "remove_at_exit", "remove all fragments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
624 	{ NULL },
625 };
626 
627 static const AVClass ism_class = {
628 	.class_name = "smooth streaming muxer",
629     .item_name  = av_default_item_name,
630     .option     = options,
631     .version    = LIBAVUTIL_VERSION_INT,
632 };
633 
634 AVOutputFormat ff_smoothstreaming_muxer = {
635 	.name           = "smoothstreaming",
636     .long_name      = NULL_IF_CONFIG_SMALL("Smooth Streaming Muxer"),
637     .priv_data_size = sizeof(SmoothStreamingContext),
638     .audio_codec    = AV_CODEC_ID_AAC,
639     .video_codec    = AV_CODEC_ID_H264,
640     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
641     .write_header   = ism_write_header,
642     .write_packet   = ism_write_packet,
643     .write_trailer  = ism_write_trailer,
644     .codec_tag      = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
645     .priv_class     = &ism_class,
646 };
647