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