forked from FFmpeg/FFmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashenc.c
2431 lines (2161 loc) · 95.5 KB
/
dashenc.c
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
/*
* MPEG-DASH ISO BMFF segmenter
* Copyright (c) 2014 Martin Storsjo
* Copyright (c) 2018 Akamai Technologies, Inc.
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "libavutil/avassert.h"
#include "libavutil/avutil.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/rational.h"
#include "libavutil/time.h"
#include "libavutil/time_internal.h"
#include "av1.h"
#include "avc.h"
#include "avformat.h"
#include "avio_internal.h"
#include "hlsplaylist.h"
#if CONFIG_HTTP_PROTOCOL
#include "http.h"
#endif
#include "internal.h"
#include "isom.h"
#include "os_support.h"
#include "url.h"
#include "vpcc.h"
#include "dash.h"
typedef enum {
SEGMENT_TYPE_AUTO = 0,
SEGMENT_TYPE_MP4,
SEGMENT_TYPE_WEBM,
SEGMENT_TYPE_NB
} SegmentType;
enum {
FRAG_TYPE_NONE = 0,
FRAG_TYPE_EVERY_FRAME,
FRAG_TYPE_DURATION,
FRAG_TYPE_PFRAMES,
FRAG_TYPE_NB
};
#define MPD_PROFILE_DASH 1
#define MPD_PROFILE_DVB 2
typedef struct Segment {
char file[1024];
int64_t start_pos;
int range_length, index_length;
int64_t time;
double prog_date_time;
int64_t duration;
int n;
} Segment;
typedef struct AdaptationSet {
int id;
char *descriptor;
int64_t seg_duration;
int64_t frag_duration;
int frag_type;
enum AVMediaType media_type;
AVDictionary *metadata;
AVRational min_frame_rate, max_frame_rate;
int ambiguous_frame_rate;
int64_t max_frag_duration;
int max_width, max_height;
int nb_streams;
AVRational par;
int trick_idx;
} AdaptationSet;
typedef struct OutputStream {
AVFormatContext *ctx;
int ctx_inited, as_idx;
AVIOContext *out;
AVCodecParserContext *parser;
AVCodecContext *parser_avctx;
int packets_written;
char initfile[1024];
int64_t init_start_pos, pos;
int init_range_length;
int nb_segments, segments_size, segment_index;
int64_t seg_duration;
int64_t frag_duration;
int64_t last_duration;
Segment **segments;
int64_t first_pts, start_pts, max_pts;
int64_t last_dts, last_pts;
int last_flags;
int bit_rate;
int first_segment_bit_rate;
SegmentType segment_type; /* segment type selected for this particular stream */
const char *format_name;
const char *extension_name;
const char *single_file_name; /* file names selected for this particular stream */
const char *init_seg_name;
const char *media_seg_name;
char codec_str[100];
int written_len;
char filename[1024];
char full_path[1024];
char temp_path[1024];
double availability_time_offset;
AVProducerReferenceTime producer_reference_time;
char producer_reference_time_str[100];
int total_pkt_size;
int64_t total_pkt_duration;
int muxer_overhead;
int frag_type;
int64_t gop_size;
AVRational sar;
int coding_dependency;
} OutputStream;
typedef struct DASHContext {
const AVClass *class; /* Class for private options. */
char *adaptation_sets;
AdaptationSet *as;
int nb_as;
int window_size;
int extra_window_size;
int64_t seg_duration;
int64_t frag_duration;
int remove_at_exit;
int use_template;
int use_timeline;
int single_file;
OutputStream *streams;
int has_video;
int64_t last_duration;
int64_t total_duration;
char availability_start_time[100];
time_t start_time_s;
int64_t presentation_time_offset;
char dirname[1024];
const char *single_file_name; /* file names as specified in options */
const char *init_seg_name;
const char *media_seg_name;
const char *utc_timing_url;
const char *method;
const char *user_agent;
AVDictionary *http_opts;
int hls_playlist;
const char *hls_master_name;
int http_persistent;
int master_playlist_created;
AVIOContext *mpd_out;
AVIOContext *m3u8_out;
int streaming;
int64_t timeout;
int index_correction;
AVDictionary *format_options;
int global_sidx;
SegmentType segment_type_option; /* segment type as specified in options */
int ignore_io_errors;
int lhls;
int ldash;
int master_publish_rate;
int nr_of_streams_to_flush;
int nr_of_streams_flushed;
int frag_type;
int write_prft;
int64_t max_gop_size;
int64_t max_segment_duration;
int profile;
int64_t target_latency;
int target_latency_refid;
AVRational min_playback_rate;
AVRational max_playback_rate;
int64_t update_period;
} DASHContext;
static struct codec_string {
int id;
const char *str;
} codecs[] = {
{ AV_CODEC_ID_VP8, "vp8" },
{ AV_CODEC_ID_VP9, "vp9" },
{ AV_CODEC_ID_VORBIS, "vorbis" },
{ AV_CODEC_ID_OPUS, "opus" },
{ AV_CODEC_ID_FLAC, "flac" },
{ 0, NULL }
};
static struct format_string {
SegmentType segment_type;
const char *str;
} formats[] = {
{ SEGMENT_TYPE_AUTO, "auto" },
{ SEGMENT_TYPE_MP4, "mp4" },
{ SEGMENT_TYPE_WEBM, "webm" },
{ 0, NULL }
};
static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
AVDictionary **options) {
DASHContext *c = s->priv_data;
int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
int err = AVERROR_MUXER_NOT_FOUND;
if (!*pb || !http_base_proto || !c->http_persistent) {
err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
#if CONFIG_HTTP_PROTOCOL
} else {
URLContext *http_url_context = ffio_geturlcontext(*pb);
av_assert0(http_url_context);
err = ff_http_do_new_request(http_url_context, filename);
if (err < 0)
ff_format_io_close(s, pb);
#endif
}
return err;
}
static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
DASHContext *c = s->priv_data;
int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
if (!*pb)
return;
if (!http_base_proto || !c->http_persistent) {
ff_format_io_close(s, pb);
#if CONFIG_HTTP_PROTOCOL
} else {
URLContext *http_url_context = ffio_geturlcontext(*pb);
av_assert0(http_url_context);
avio_flush(*pb);
ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
#endif
}
}
static const char *get_format_str(SegmentType segment_type) {
int i;
for (i = 0; i < SEGMENT_TYPE_NB; i++)
if (formats[i].segment_type == segment_type)
return formats[i].str;
return NULL;
}
static const char *get_extension_str(SegmentType type, int single_file)
{
switch (type) {
case SEGMENT_TYPE_MP4: return single_file ? "mp4" : "m4s";
case SEGMENT_TYPE_WEBM: return "webm";
default: return NULL;
}
}
static int handle_io_open_error(AVFormatContext *s, int err, char *url) {
DASHContext *c = s->priv_data;
char errbuf[AV_ERROR_MAX_STRING_SIZE];
av_strerror(err, errbuf, sizeof(errbuf));
av_log(s, c->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
"Unable to open %s for writing: %s\n", url, errbuf);
return c->ignore_io_errors ? 0 : err;
}
static inline SegmentType select_segment_type(SegmentType segment_type, enum AVCodecID codec_id)
{
if (segment_type == SEGMENT_TYPE_AUTO) {
if (codec_id == AV_CODEC_ID_OPUS || codec_id == AV_CODEC_ID_VORBIS ||
codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_VP9) {
segment_type = SEGMENT_TYPE_WEBM;
} else {
segment_type = SEGMENT_TYPE_MP4;
}
}
return segment_type;
}
static int init_segment_types(AVFormatContext *s)
{
DASHContext *c = s->priv_data;
int has_mp4_streams = 0;
for (int i = 0; i < s->nb_streams; ++i) {
OutputStream *os = &c->streams[i];
SegmentType segment_type = select_segment_type(
c->segment_type_option, s->streams[i]->codecpar->codec_id);
os->segment_type = segment_type;
os->format_name = get_format_str(segment_type);
if (!os->format_name) {
av_log(s, AV_LOG_ERROR, "Could not select DASH segment type for stream %d\n", i);
return AVERROR_MUXER_NOT_FOUND;
}
os->extension_name = get_extension_str(segment_type, c->single_file);
if (!os->extension_name) {
av_log(s, AV_LOG_ERROR, "Could not get extension type for stream %d\n", i);
return AVERROR_MUXER_NOT_FOUND;
}
has_mp4_streams |= segment_type == SEGMENT_TYPE_MP4;
}
if (c->hls_playlist && !has_mp4_streams) {
av_log(s, AV_LOG_WARNING, "No mp4 streams, disabling HLS manifest generation\n");
c->hls_playlist = 0;
}
return 0;
}
static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
AVRational *frame_rate, char *str, int size) {
VPCC vpcc;
int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
if (ret == 0) {
av_strlcatf(str, size, "vp09.%02d.%02d.%02d",
vpcc.profile, vpcc.level, vpcc.bitdepth);
} else {
// Default to just vp9 in case of error while finding out profile or level
av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
av_strlcpy(str, "vp9", size);
}
return;
}
static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
AVRational *frame_rate, char *str, int size)
{
const AVCodecTag *tags[2] = { NULL, NULL };
uint32_t tag;
int i;
// common Webm codecs are not part of RFC 6381
for (i = 0; codecs[i].id; i++)
if (codecs[i].id == par->codec_id) {
if (codecs[i].id == AV_CODEC_ID_VP9) {
set_vp9_codec_str(s, par, frame_rate, str, size);
} else {
av_strlcpy(str, codecs[i].str, size);
}
return;
}
// for codecs part of RFC 6381
if (par->codec_type == AVMEDIA_TYPE_VIDEO)
tags[0] = ff_codec_movvideo_tags;
else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
tags[0] = ff_codec_movaudio_tags;
else
return;
tag = par->codec_tag;
if (!tag)
tag = av_codec_get_tag(tags, par->codec_id);
if (!tag)
return;
if (size < 5)
return;
AV_WL32(str, tag);
str[4] = '\0';
if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
uint32_t oti;
tags[0] = ff_mp4_obj_type;
oti = av_codec_get_tag(tags, par->codec_id);
if (oti)
av_strlcatf(str, size, ".%02"PRIx32, oti);
else
return;
if (tag == MKTAG('m', 'p', '4', 'a')) {
if (par->extradata_size >= 2) {
int aot = par->extradata[0] >> 3;
if (aot == 31)
aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
av_strlcatf(str, size, ".%d", aot);
}
} else if (tag == MKTAG('m', 'p', '4', 'v')) {
// Unimplemented, should output ProfileLevelIndication as a decimal number
av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
}
} else if (!strcmp(str, "avc1")) {
uint8_t *tmpbuf = NULL;
uint8_t *extradata = par->extradata;
int extradata_size = par->extradata_size;
if (!extradata_size)
return;
if (extradata[0] != 1) {
AVIOContext *pb;
if (avio_open_dyn_buf(&pb) < 0)
return;
if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
ffio_free_dyn_buf(&pb);
return;
}
extradata_size = avio_close_dyn_buf(pb, &extradata);
tmpbuf = extradata;
}
if (extradata_size >= 4)
av_strlcatf(str, size, ".%02x%02x%02x",
extradata[1], extradata[2], extradata[3]);
av_free(tmpbuf);
} else if (!strcmp(str, "av01")) {
AV1SequenceParameters seq;
if (!par->extradata_size)
return;
if (ff_av1_parse_seq_header(&seq, par->extradata, par->extradata_size) < 0)
return;
av_strlcatf(str, size, ".%01u.%02u%s.%02u",
seq.profile, seq.level, seq.tier ? "H" : "M", seq.bitdepth);
if (seq.color_description_present_flag)
av_strlcatf(str, size, ".%01u.%01u%01u%01u.%02u.%02u.%02u.%01u",
seq.monochrome,
seq.chroma_subsampling_x, seq.chroma_subsampling_y, seq.chroma_sample_position,
seq.color_primaries, seq.transfer_characteristics, seq.matrix_coefficients,
seq.color_range);
}
}
static int flush_dynbuf(DASHContext *c, OutputStream *os, int *range_length)
{
uint8_t *buffer;
if (!os->ctx->pb) {
return AVERROR(EINVAL);
}
// flush
av_write_frame(os->ctx, NULL);
avio_flush(os->ctx->pb);
if (!c->single_file) {
// write out to file
*range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
os->ctx->pb = NULL;
if (os->out)
avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
os->written_len = 0;
av_free(buffer);
// re-open buffer
return avio_open_dyn_buf(&os->ctx->pb);
} else {
*range_length = avio_tell(os->ctx->pb) - os->pos;
return 0;
}
}
static void set_http_options(AVDictionary **options, DASHContext *c)
{
if (c->method)
av_dict_set(options, "method", c->method, 0);
av_dict_copy(options, c->http_opts, 0);
if (c->user_agent)
av_dict_set(options, "user_agent", c->user_agent, 0);
if (c->http_persistent)
av_dict_set_int(options, "multiple_requests", 1, 0);
if (c->timeout >= 0)
av_dict_set_int(options, "timeout", c->timeout, 0);
}
static void get_hls_playlist_name(char *playlist_name, int string_size,
const char *base_url, int id) {
if (base_url)
snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
else
snprintf(playlist_name, string_size, "media_%d.m3u8", id);
}
static void get_start_index_number(OutputStream *os, DASHContext *c,
int *start_index, int *start_number) {
*start_index = 0;
*start_number = 1;
if (c->window_size) {
*start_index = FFMAX(os->nb_segments - c->window_size, 0);
*start_number = FFMAX(os->segment_index - c->window_size, 1);
}
}
static void write_hls_media_playlist(OutputStream *os, AVFormatContext *s,
int representation_id, int final,
char *prefetch_url) {
DASHContext *c = s->priv_data;
int timescale = os->ctx->streams[0]->time_base.den;
char temp_filename_hls[1024];
char filename_hls[1024];
AVDictionary *http_opts = NULL;
int target_duration = 0;
int ret = 0;
const char *proto = avio_find_protocol_name(c->dirname);
int use_rename = proto && !strcmp(proto, "file");
int i, start_index, start_number;
double prog_date_time = 0;
get_start_index_number(os, c, &start_index, &start_number);
if (!c->hls_playlist || start_index >= os->nb_segments ||
os->segment_type != SEGMENT_TYPE_MP4)
return;
get_hls_playlist_name(filename_hls, sizeof(filename_hls),
c->dirname, representation_id);
snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
set_http_options(&http_opts, c);
ret = dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
av_dict_free(&http_opts);
if (ret < 0) {
handle_io_open_error(s, ret, temp_filename_hls);
return;
}
for (i = start_index; i < os->nb_segments; i++) {
Segment *seg = os->segments[i];
double duration = (double) seg->duration / timescale;
if (target_duration <= duration)
target_duration = lrint(duration);
}
ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
start_number, PLAYLIST_TYPE_NONE, 0);
ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
os->init_range_length, os->init_start_pos);
for (i = start_index; i < os->nb_segments; i++) {
Segment *seg = os->segments[i];
if (fabs(prog_date_time) < 1e-7) {
if (os->nb_segments == 1)
prog_date_time = c->start_time_s;
else
prog_date_time = seg->prog_date_time;
}
seg->prog_date_time = prog_date_time;
ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
(double) seg->duration / timescale, 0,
seg->range_length, seg->start_pos, NULL,
c->single_file ? os->initfile : seg->file,
&prog_date_time, 0, 0, 0);
if (ret < 0) {
av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
}
}
if (prefetch_url)
avio_printf(c->m3u8_out, "#EXT-X-PREFETCH:%s\n", prefetch_url);
if (final)
ff_hls_write_end_list(c->m3u8_out);
dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
if (use_rename)
ff_rename(temp_filename_hls, filename_hls, os->ctx);
}
static int flush_init_segment(AVFormatContext *s, OutputStream *os)
{
DASHContext *c = s->priv_data;
int ret, range_length;
ret = flush_dynbuf(c, os, &range_length);
if (ret < 0)
return ret;
os->pos = os->init_range_length = range_length;
if (!c->single_file) {
char filename[1024];
snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
dashenc_io_close(s, &os->out, filename);
}
return 0;
}
static void dash_free(AVFormatContext *s)
{
DASHContext *c = s->priv_data;
int i, j;
if (c->as) {
for (i = 0; i < c->nb_as; i++) {
av_dict_free(&c->as[i].metadata);
av_freep(&c->as[i].descriptor);
}
av_freep(&c->as);
c->nb_as = 0;
}
if (!c->streams)
return;
for (i = 0; i < s->nb_streams; i++) {
OutputStream *os = &c->streams[i];
if (os->ctx && os->ctx->pb) {
if (!c->single_file)
ffio_free_dyn_buf(&os->ctx->pb);
else
avio_close(os->ctx->pb);
}
ff_format_io_close(s, &os->out);
avformat_free_context(os->ctx);
avcodec_free_context(&os->parser_avctx);
av_parser_close(os->parser);
for (j = 0; j < os->nb_segments; j++)
av_free(os->segments[j]);
av_free(os->segments);
av_freep(&os->single_file_name);
av_freep(&os->init_seg_name);
av_freep(&os->media_seg_name);
}
av_freep(&c->streams);
ff_format_io_close(s, &c->mpd_out);
ff_format_io_close(s, &c->m3u8_out);
}
static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
int representation_id, int final)
{
DASHContext *c = s->priv_data;
int i, start_index, start_number;
get_start_index_number(os, c, &start_index, &start_number);
if (c->use_template) {
int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
if (!c->use_timeline) {
avio_printf(out, "duration=\"%"PRId64"\" ", os->seg_duration);
if (c->streaming && os->availability_time_offset)
avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
os->availability_time_offset);
}
if (c->streaming && os->availability_time_offset && !final)
avio_printf(out, "availabilityTimeComplete=\"false\" ");
avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\"", os->init_seg_name, os->media_seg_name, c->use_timeline ? start_number : 1);
if (c->presentation_time_offset)
avio_printf(out, " presentationTimeOffset=\"%"PRId64"\"", c->presentation_time_offset);
avio_printf(out, ">\n");
if (c->use_timeline) {
int64_t cur_time = 0;
avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
for (i = start_index; i < os->nb_segments; ) {
Segment *seg = os->segments[i];
int repeat = 0;
avio_printf(out, "\t\t\t\t\t\t<S ");
if (i == start_index || seg->time != cur_time) {
cur_time = seg->time;
avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
}
avio_printf(out, "d=\"%"PRId64"\" ", seg->duration);
while (i + repeat + 1 < os->nb_segments &&
os->segments[i + repeat + 1]->duration == seg->duration &&
os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
repeat++;
if (repeat > 0)
avio_printf(out, "r=\"%d\" ", repeat);
avio_printf(out, "/>\n");
i += 1 + repeat;
cur_time += (1 + repeat) * seg->duration;
}
avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
}
avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
} else if (c->single_file) {
avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, FFMIN(os->seg_duration, os->last_duration), start_number);
avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
for (i = start_index; i < os->nb_segments; i++) {
Segment *seg = os->segments[i];
avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
if (seg->index_length)
avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
avio_printf(out, "/>\n");
}
avio_printf(out, "\t\t\t\t</SegmentList>\n");
} else {
avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, FFMIN(os->seg_duration, os->last_duration), start_number);
avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
for (i = start_index; i < os->nb_segments; i++) {
Segment *seg = os->segments[i];
avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
}
avio_printf(out, "\t\t\t\t</SegmentList>\n");
}
if (!c->lhls || final) {
write_hls_media_playlist(os, s, representation_id, final, NULL);
}
}
static char *xmlescape(const char *str) {
int outlen = strlen(str)*3/2 + 6;
char *out = av_realloc(NULL, outlen + 1);
int pos = 0;
if (!out)
return NULL;
for (; *str; str++) {
if (pos + 6 > outlen) {
char *tmp;
outlen = 2 * outlen + 6;
tmp = av_realloc(out, outlen + 1);
if (!tmp) {
av_free(out);
return NULL;
}
out = tmp;
}
if (*str == '&') {
memcpy(&out[pos], "&", 5);
pos += 5;
} else if (*str == '<') {
memcpy(&out[pos], "<", 4);
pos += 4;
} else if (*str == '>') {
memcpy(&out[pos], ">", 4);
pos += 4;
} else if (*str == '\'') {
memcpy(&out[pos], "'", 6);
pos += 6;
} else if (*str == '\"') {
memcpy(&out[pos], """, 6);
pos += 6;
} else {
out[pos++] = *str;
}
}
out[pos] = '\0';
return out;
}
static void write_time(AVIOContext *out, int64_t time)
{
int seconds = time / AV_TIME_BASE;
int fractions = time % AV_TIME_BASE;
int minutes = seconds / 60;
int hours = minutes / 60;
seconds %= 60;
minutes %= 60;
avio_printf(out, "PT");
if (hours)
avio_printf(out, "%dH", hours);
if (hours || minutes)
avio_printf(out, "%dM", minutes);
avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
}
static void format_date(char *buf, int size, int64_t time_us)
{
struct tm *ptm, tmbuf;
int64_t time_ms = time_us / 1000;
const time_t time_s = time_ms / 1000;
int millisec = time_ms - (time_s * 1000);
ptm = gmtime_r(&time_s, &tmbuf);
if (ptm) {
int len;
if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm)) {
buf[0] = '\0';
return;
}
len = strlen(buf);
snprintf(buf + len, size - len, ".%03dZ", millisec);
}
}
static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
int final)
{
DASHContext *c = s->priv_data;
AdaptationSet *as = &c->as[as_index];
AVDictionaryEntry *lang, *role;
int i;
avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"%s\" startWithSAP=\"1\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
else if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && !av_cmp_q(as->min_frame_rate, as->max_frame_rate))
avio_printf(out, " frameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
if (as->media_type == AVMEDIA_TYPE_VIDEO) {
avio_printf(out, " maxWidth=\"%d\" maxHeight=\"%d\"", as->max_width, as->max_height);
avio_printf(out, " par=\"%d:%d\"", as->par.num, as->par.den);
}
lang = av_dict_get(as->metadata, "language", NULL, 0);
if (lang)
avio_printf(out, " lang=\"%s\"", lang->value);
avio_printf(out, ">\n");
if (!final && c->ldash && as->max_frag_duration && !(c->profile & MPD_PROFILE_DVB))
avio_printf(out, "\t\t\t<Resync dT=\"%"PRId64"\" type=\"0\"/>\n", as->max_frag_duration);
if (as->trick_idx >= 0)
avio_printf(out, "\t\t\t<EssentialProperty id=\"%d\" schemeIdUri=\"http://dashif.org/guidelines/trickmode\" value=\"%d\"/>\n", as->id, as->trick_idx);
role = av_dict_get(as->metadata, "role", NULL, 0);
if (role)
avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
if (as->descriptor)
avio_printf(out, "\t\t\t%s\n", as->descriptor);
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
OutputStream *os = &c->streams[i];
char bandwidth_str[64] = {'\0'};
if (os->as_idx - 1 != as_index)
continue;
if (os->bit_rate > 0)
snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"", os->bit_rate);
else if (final) {
int average_bit_rate = os->pos * 8 * AV_TIME_BASE / c->total_duration;
snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"", average_bit_rate);
} else if (os->first_segment_bit_rate > 0)
snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"", os->first_segment_bit_rate);
if (as->media_type == AVMEDIA_TYPE_VIDEO) {
avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
if (st->codecpar->field_order == AV_FIELD_UNKNOWN)
avio_printf(out, " scanType=\"unknown\"");
else if (st->codecpar->field_order != AV_FIELD_PROGRESSIVE)
avio_printf(out, " scanType=\"interlaced\"");
avio_printf(out, " sar=\"%d:%d\"", os->sar.num, os->sar.den);
if (st->avg_frame_rate.num && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
if (as->trick_idx >= 0) {
AdaptationSet *tas = &c->as[as->trick_idx];
if (!as->ambiguous_frame_rate && !tas->ambiguous_frame_rate)
avio_printf(out, " maxPlayoutRate=\"%d\"", FFMAX((int)av_q2d(av_div_q(tas->min_frame_rate, as->min_frame_rate)), 1));
}
if (!os->coding_dependency)
avio_printf(out, " codingDependency=\"false\"");
avio_printf(out, ">\n");
} else {
avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
s->streams[i]->codecpar->channels);
}
if (!final && c->write_prft && os->producer_reference_time_str[0]) {
avio_printf(out, "\t\t\t\t<ProducerReferenceTime id=\"%d\" inband=\"true\" type=\"%s\" wallClockTime=\"%s\" presentationTime=\"%"PRId64"\">\n",
i, os->producer_reference_time.flags ? "captured" : "encoder", os->producer_reference_time_str, c->presentation_time_offset);
avio_printf(out, "\t\t\t\t\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
avio_printf(out, "\t\t\t\t</ProducerReferenceTime>\n");
}
if (!final && c->ldash && os->gop_size && os->frag_type != FRAG_TYPE_NONE && !(c->profile & MPD_PROFILE_DVB) &&
(os->frag_type != FRAG_TYPE_DURATION || os->frag_duration != os->seg_duration))
avio_printf(out, "\t\t\t\t<Resync dT=\"%"PRId64"\" type=\"1\"/>\n", os->gop_size);
output_segment_list(os, out, s, i, final);
avio_printf(out, "\t\t\t</Representation>\n");
}
avio_printf(out, "\t\t</AdaptationSet>\n");
return 0;
}
static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
{
DASHContext *c = s->priv_data;
void *mem;
if (c->profile & MPD_PROFILE_DVB && (c->nb_as + 1) > 16) {
av_log(s, AV_LOG_ERROR, "DVB-DASH profile allows a max of 16 Adaptation Sets\n");
return AVERROR(EINVAL);
}
mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
if (!mem)
return AVERROR(ENOMEM);
c->as = mem;
++c->nb_as;
*as = &c->as[c->nb_as - 1];
memset(*as, 0, sizeof(**as));
(*as)->media_type = type;
(*as)->frag_type = -1;
(*as)->trick_idx = -1;
return 0;
}
static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
{
DASHContext *c = s->priv_data;
AdaptationSet *as = &c->as[as_idx - 1];
OutputStream *os = &c->streams[i];
if (as->media_type != s->streams[i]->codecpar->codec_type) {
av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
return AVERROR(EINVAL);
} else if (os->as_idx) {
av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
return AVERROR(EINVAL);
}
if (c->profile & MPD_PROFILE_DVB && (as->nb_streams + 1) > 16) {
av_log(s, AV_LOG_ERROR, "DVB-DASH profile allows a max of 16 Representations per Adaptation Set\n");
return AVERROR(EINVAL);
}
os->as_idx = as_idx;
++as->nb_streams;
return 0;
}
static int parse_adaptation_sets(AVFormatContext *s)
{
DASHContext *c = s->priv_data;
const char *p = c->adaptation_sets;
enum { new_set, parse_default, parsing_streams, parse_seg_duration, parse_frag_duration } state;
AdaptationSet *as;
int i, n, ret;
// default: one AdaptationSet for each stream
if (!p) {
for (i = 0; i < s->nb_streams; i++) {
if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
return ret;
as->id = i;
c->streams[i].as_idx = c->nb_as;
++as->nb_streams;
}
goto end;
}
// syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
// option id=0,descriptor=descriptor_str,streams=0,1,2 and so on
// option id=0,seg_duration=2.5,frag_duration=0.5,streams=0,1,2
// id=1,trick_id=0,seg_duration=10,frag_type=none,streams=3 and so on
// descriptor is useful to the scheme defined by ISO/IEC 23009-1:2014/Amd.2:2015
// descriptor_str should be a self-closing xml tag.
// seg_duration and frag_duration have the same syntax as the global options of
// the same name, and the former have precedence over them if set.
state = new_set;
while (*p) {
if (*p == ' ') {
p++;
continue;
} else if (state == new_set && av_strstart(p, "id=", &p)) {
char id_str[10], *end_str;
n = strcspn(p, ",");
snprintf(id_str, sizeof(id_str), "%.*s", n, p);
i = strtol(id_str, &end_str, 10);
if (id_str == end_str || i < 0 || i > c->nb_as) {
av_log(s, AV_LOG_ERROR, "\"%s\" is not a valid value for an AdaptationSet id\n", id_str);
return AVERROR(EINVAL);
}
if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
return ret;
as->id = i;
p += n;
if (*p)
p++;
state = parse_default;
} else if (state != new_set && av_strstart(p, "seg_duration=", &p)) {
state = parse_seg_duration;
} else if (state != new_set && av_strstart(p, "frag_duration=", &p)) {
state = parse_frag_duration;
} else if (state == parse_seg_duration || state == parse_frag_duration) {
char str[32];
int64_t usecs = 0;
n = strcspn(p, ",");
snprintf(str, sizeof(str), "%.*s", n, p);
p += n;
if (*p)
p++;
ret = av_parse_time(&usecs, str, 1);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "Unable to parse option value \"%s\" as duration\n", str);
return ret;
}