forked from FFmpeg/FFmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhlsenc.c
3186 lines (2817 loc) · 115 KB
/
hlsenc.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
/*
* Apple HTTP Live Streaming segmenter
* Copyright (c) 2012, Luca Barbato
* Copyright (c) 2017 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"
#include <float.h>
#include <stdint.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if CONFIG_GCRYPT
#include <gcrypt.h>
#elif CONFIG_OPENSSL
#include <openssl/rand.h>
#endif
#include "libavutil/avassert.h"
#include "libavutil/mathematics.h"
#include "libavutil/parseutils.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/random_seed.h"
#include "libavutil/opt.h"
#include "libavutil/log.h"
#include "libavutil/time.h"
#include "libavutil/time_internal.h"
#include "avformat.h"
#include "avio_internal.h"
#include "avc.h"
#if CONFIG_HTTP_PROTOCOL
#include "http.h"
#endif
#include "hlsplaylist.h"
#include "internal.h"
#include "os_support.h"
typedef enum {
HLS_START_SEQUENCE_AS_START_NUMBER = 0,
HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2, // YYYYMMDDhhmmss
HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH = 3,
HLS_START_SEQUENCE_LAST, // unused
} StartSequenceSourceType;
typedef enum {
CODEC_ATTRIBUTE_WRITTEN = 0,
CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN,
} CodecAttributeStatus;
#define KEYSIZE 16
#define LINE_BUFFER_SIZE MAX_URL_SIZE
#define HLS_MICROSECOND_UNIT 1000000
#define BUFSIZE (16 * 1024)
#define POSTFIX_PATTERN "_%d"
typedef struct HLSSegment {
char filename[MAX_URL_SIZE];
char sub_filename[MAX_URL_SIZE];
double duration; /* in seconds */
int discont;
int64_t pos;
int64_t size;
int64_t keyframe_pos;
int64_t keyframe_size;
unsigned var_stream_idx;
char key_uri[LINE_BUFFER_SIZE + 1];
char iv_string[KEYSIZE*2 + 1];
struct HLSSegment *next;
double discont_program_date_time;
} HLSSegment;
typedef enum HLSFlags {
// Generate a single media file and use byte ranges in the playlist.
HLS_SINGLE_FILE = (1 << 0),
HLS_DELETE_SEGMENTS = (1 << 1),
HLS_ROUND_DURATIONS = (1 << 2),
HLS_DISCONT_START = (1 << 3),
HLS_OMIT_ENDLIST = (1 << 4),
HLS_SPLIT_BY_TIME = (1 << 5),
HLS_APPEND_LIST = (1 << 6),
HLS_PROGRAM_DATE_TIME = (1 << 7),
HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
HLS_TEMP_FILE = (1 << 11),
HLS_PERIODIC_REKEY = (1 << 12),
HLS_INDEPENDENT_SEGMENTS = (1 << 13),
HLS_I_FRAMES_ONLY = (1 << 14),
} HLSFlags;
typedef enum {
SEGMENT_TYPE_MPEGTS,
SEGMENT_TYPE_FMP4,
} SegmentType;
typedef struct VariantStream {
unsigned var_stream_idx;
unsigned number;
int64_t sequence;
const AVOutputFormat *oformat;
const AVOutputFormat *vtt_oformat;
AVIOContext *out;
AVIOContext *out_single_file;
int packets_written;
int init_range_length;
uint8_t *temp_buffer;
uint8_t *init_buffer;
AVFormatContext *avf;
AVFormatContext *vtt_avf;
int has_video;
int has_subtitle;
int new_start;
int start_pts_from_audio;
double dpp; // duration per packet
int64_t start_pts;
int64_t end_pts;
int64_t video_lastpos;
int64_t video_keyframe_pos;
int64_t video_keyframe_size;
double duration; // last segment duration computed so far, in seconds
int64_t start_pos; // last segment starting position
int64_t size; // last segment size
int nb_entries;
int discontinuity_set;
int discontinuity;
int reference_stream_index;
HLSSegment *segments;
HLSSegment *last_segment;
HLSSegment *old_segments;
char *basename_tmp;
char *basename;
char *vtt_basename;
char *vtt_m3u8_name;
char *m3u8_name;
double initial_prog_date_time;
char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
char *fmp4_init_filename;
char *base_output_dirname;
int encrypt_started;
char key_file[LINE_BUFFER_SIZE + 1];
char key_uri[LINE_BUFFER_SIZE + 1];
char key_string[KEYSIZE*2 + 1];
char iv_string[KEYSIZE*2 + 1];
AVStream **streams;
char codec_attr[128];
CodecAttributeStatus attr_status;
unsigned int nb_streams;
int m3u8_created; /* status of media play-list creation */
int is_default; /* default status of audio group */
const char *language; /* audio language name */
const char *agroup; /* audio group name */
const char *sgroup; /* subtitle group name */
const char *ccgroup; /* closed caption group name */
const char *varname; /* variant name */
} VariantStream;
typedef struct ClosedCaptionsStream {
const char *ccgroup; /* closed caption group name */
const char *instreamid; /* closed captions INSTREAM-ID */
const char *language; /* closed captions language */
} ClosedCaptionsStream;
typedef struct HLSContext {
const AVClass *class; // Class for private options.
int64_t start_sequence;
uint32_t start_sequence_source_type; // enum StartSequenceSourceType
int64_t time; // Set by a private option.
int64_t init_time; // Set by a private option.
int max_nb_segments; // Set by a private option.
int hls_delete_threshold; // Set by a private option.
uint32_t flags; // enum HLSFlags
uint32_t pl_type; // enum PlaylistType
char *segment_filename;
char *fmp4_init_filename;
int segment_type;
int resend_init_file; ///< resend init file into disk after refresh m3u8
int use_localtime; ///< flag to expand filename with localtime
int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
int allowcache;
int64_t recording_time;
int64_t max_seg_size; // every segment file max size
char *baseurl;
char *vtt_format_options_str;
char *subtitle_filename;
AVDictionary *format_options;
int encrypt;
char *key;
char *key_url;
char *iv;
char *key_basename;
int encrypt_started;
char *key_info_file;
char key_file[LINE_BUFFER_SIZE + 1];
char key_uri[LINE_BUFFER_SIZE + 1];
char key_string[KEYSIZE*2 + 1];
char iv_string[KEYSIZE*2 + 1];
AVDictionary *vtt_format_options;
char *method;
char *user_agent;
VariantStream *var_streams;
unsigned int nb_varstreams;
ClosedCaptionsStream *cc_streams;
unsigned int nb_ccstreams;
int master_m3u8_created; /* status of master play-list creation */
char *master_m3u8_url; /* URL of the master m3u8 file */
int version; /* HLS version */
char *var_stream_map; /* user specified variant stream map string */
char *cc_stream_map; /* user specified closed caption streams map string */
char *master_pl_name;
unsigned int master_publish_rate;
int http_persistent;
AVIOContext *m3u8_out;
AVIOContext *sub_m3u8_out;
int64_t timeout;
int ignore_io_errors;
char *headers;
int has_default_key; /* has DEFAULT field of var_stream_map */
int has_video_m3u8; /* has video stream m3u8 list */
} HLSContext;
static int strftime_expand(const char *fmt, char **dest)
{
int r = 1;
time_t now0;
struct tm *tm, tmpbuf;
char *buf;
buf = av_mallocz(MAX_URL_SIZE);
if (!buf)
return AVERROR(ENOMEM);
time(&now0);
tm = localtime_r(&now0, &tmpbuf);
r = strftime(buf, MAX_URL_SIZE, fmt, tm);
if (!r) {
av_free(buf);
return AVERROR(EINVAL);
}
*dest = buf;
return r;
}
static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, const char *filename,
AVDictionary **options)
{
HLSContext *hls = 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 || !hls->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 int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
{
HLSContext *hls = s->priv_data;
int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
int ret = 0;
if (!*pb)
return ret;
if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
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);
ret = ff_http_get_shutdown_status(http_url_context);
#endif
}
return ret;
}
static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
{
int http_base_proto = ff_is_http_proto(s->url);
if (c->method) {
av_dict_set(options, "method", c->method, 0);
} else if (http_base_proto) {
av_dict_set(options, "method", "PUT", 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);
if (c->headers)
av_dict_set(options, "headers", c->headers, 0);
}
static void write_codec_attr(AVStream *st, VariantStream *vs)
{
int codec_strlen = strlen(vs->codec_attr);
char attr[32];
if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
return;
if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)
return;
if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
uint8_t *data = st->codecpar->extradata;
if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
snprintf(attr, sizeof(attr),
"avc1.%02x%02x%02x", data[5], data[6], data[7]);
} else {
goto fail;
}
} else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
uint8_t *data = st->codecpar->extradata;
int profile = FF_PROFILE_UNKNOWN;
int level = FF_LEVEL_UNKNOWN;
if (st->codecpar->profile != FF_PROFILE_UNKNOWN)
profile = st->codecpar->profile;
if (st->codecpar->level != FF_LEVEL_UNKNOWN)
level = st->codecpar->level;
/* check the boundary of data which from current position is small than extradata_size */
while (data && (data - st->codecpar->extradata + 19) < st->codecpar->extradata_size) {
/* get HEVC SPS NAL and seek to profile_tier_level */
if (!(data[0] | data[1] | data[2]) && data[3] == 1 && ((data[4] & 0x7E) == 0x42)) {
uint8_t *rbsp_buf;
int remain_size = 0;
int rbsp_size = 0;
/* skip start code + nalu header */
data += 6;
/* process by reference General NAL unit syntax */
remain_size = st->codecpar->extradata_size - (data - st->codecpar->extradata);
rbsp_buf = ff_nal_unit_extract_rbsp(data, remain_size, &rbsp_size, 0);
if (!rbsp_buf)
return;
if (rbsp_size < 13) {
av_freep(&rbsp_buf);
break;
}
/* skip sps_video_parameter_set_id u(4),
* sps_max_sub_layers_minus1 u(3),
* and sps_temporal_id_nesting_flag u(1) */
profile = rbsp_buf[1] & 0x1f;
/* skip 8 + 8 + 32 + 4 + 43 + 1 bit */
level = rbsp_buf[12];
av_freep(&rbsp_buf);
break;
}
data++;
}
if (st->codecpar->codec_tag == MKTAG('h','v','c','1') &&
profile != FF_PROFILE_UNKNOWN &&
level != FF_LEVEL_UNKNOWN) {
snprintf(attr, sizeof(attr), "%s.%d.4.L%d.B01", av_fourcc2str(st->codecpar->codec_tag), profile, level);
} else
goto fail;
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
snprintf(attr, sizeof(attr), "mp4a.40.33");
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
snprintf(attr, sizeof(attr), "mp4a.40.34");
} else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
/* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
snprintf(attr, sizeof(attr), "mp4a.40.2");
} else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
snprintf(attr, sizeof(attr), "ac-3");
} else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
snprintf(attr, sizeof(attr), "ec-3");
} else {
goto fail;
}
// Don't write the same attribute multiple times
if (!av_stristr(vs->codec_attr, attr)) {
snprintf(vs->codec_attr + codec_strlen,
sizeof(vs->codec_attr) - codec_strlen,
"%s%s", codec_strlen ? "," : "", attr);
}
return;
fail:
vs->codec_attr[0] = '\0';
vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;
return;
}
static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
{
const char *p;
char c;
int addchar_count;
int found_count = 0;
AVBPrint buf;
int ret;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
p = filename;
for (;;) {
c = *p;
if (c == '\0')
break;
if (c == '%' && *(p+1) == '%') // %%
addchar_count = 2;
else if (c == '%' && *(p+1) == placeholder) {
av_bprintf(&buf, "%s", datastring);
p += 2;
addchar_count = 0;
found_count ++;
} else
addchar_count = 1;
if (addchar_count > 0) {
av_bprint_append_data(&buf, p, addchar_count);
p += addchar_count;
}
}
if (!av_bprint_is_complete(&buf)) {
av_bprint_finalize(&buf, NULL);
return AVERROR(ENOMEM);
}
if ((ret = av_bprint_finalize(&buf, s)) < 0)
return ret;
return found_count;
}
static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
{
const char *p;
char c;
int nd, addchar_count;
int found_count = 0;
AVBPrint buf;
int ret;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
p = filename;
for (;;) {
c = *p;
if (c == '\0')
break;
if (c == '%' && *(p+1) == '%') // %%
addchar_count = 2;
else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
nd = 0;
addchar_count = 1;
while (av_isdigit(*(p + addchar_count))) {
nd = nd * 10 + *(p + addchar_count) - '0';
addchar_count++;
}
if (*(p + addchar_count) == placeholder) {
av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
p += (addchar_count + 1);
addchar_count = 0;
found_count++;
}
} else
addchar_count = 1;
av_bprint_append_data(&buf, p, addchar_count);
p += addchar_count;
}
if (!av_bprint_is_complete(&buf)) {
av_bprint_finalize(&buf, NULL);
return AVERROR(ENOMEM);
}
if ((ret = av_bprint_finalize(&buf, s)) < 0)
return ret;
return found_count;
}
static void write_styp(AVIOContext *pb)
{
avio_wb32(pb, 24);
ffio_wfourcc(pb, "styp");
ffio_wfourcc(pb, "msdh");
avio_wb32(pb, 0); /* minor */
ffio_wfourcc(pb, "msdh");
ffio_wfourcc(pb, "msix");
}
static int flush_dynbuf(VariantStream *vs, int *range_length)
{
AVFormatContext *ctx = vs->avf;
if (!ctx->pb) {
return AVERROR(EINVAL);
}
// flush
av_write_frame(ctx, NULL);
// write out to file
*range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
ctx->pb = NULL;
avio_write(vs->out, vs->temp_buffer, *range_length);
avio_flush(vs->out);
// re-open buffer
return avio_open_dyn_buf(&ctx->pb);
}
static void reflush_dynbuf(VariantStream *vs, int *range_length)
{
// re-open buffer
avio_write(vs->out, vs->temp_buffer, *range_length);
}
#if HAVE_DOS_PATHS
#define SEPARATOR '\\'
#else
#define SEPARATOR '/'
#endif
static int hls_delete_file(HLSContext *hls, AVFormatContext *avf,
const char *path, const char *proto)
{
if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
AVDictionary *opt = NULL;
AVIOContext *out = NULL;
int ret;
set_http_options(avf, &opt, hls);
av_dict_set(&opt, "method", "DELETE", 0);
ret = avf->io_open(avf, &out, path, AVIO_FLAG_WRITE, &opt);
av_dict_free(&opt);
if (ret < 0)
return hls->ignore_io_errors ? 1 : ret;
ff_format_io_close(avf, &out);
} else if (unlink(path) < 0) {
av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
path, strerror(errno));
}
return 0;
}
static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
VariantStream *vs)
{
HLSSegment *segment, *previous_segment = NULL;
float playlist_duration = 0.0f;
int ret = 0;
int segment_cnt = 0;
AVBPrint path;
const char *dirname = NULL;
char *dirname_r = NULL;
char *dirname_repl = NULL;
const char *vtt_dirname = NULL;
char *vtt_dirname_r = NULL;
const char *proto = NULL;
av_bprint_init(&path, 0, AV_BPRINT_SIZE_UNLIMITED);
segment = vs->segments;
while (segment) {
playlist_duration += segment->duration;
segment = segment->next;
}
segment = vs->old_segments;
segment_cnt = 0;
while (segment) {
playlist_duration -= segment->duration;
previous_segment = segment;
segment = previous_segment->next;
segment_cnt++;
if (playlist_duration <= -previous_segment->duration) {
previous_segment->next = NULL;
break;
}
if (segment_cnt >= hls->hls_delete_threshold) {
previous_segment->next = NULL;
break;
}
}
if (segment && !hls->use_localtime_mkdir) {
dirname_r = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
dirname = av_dirname(dirname_r);
}
/* if %v is present in the file's directory
* all segment belongs to the same variant, so do it only once before the loop*/
if (dirname && av_stristr(dirname, "%v")) {
if (!vs->varname) {
if (replace_int_data_in_filename(&dirname_repl, dirname, 'v', segment->var_stream_idx) < 1) {
ret = AVERROR(EINVAL);
goto fail;
}
} else {
if (replace_str_data_in_filename(&dirname_repl, dirname, 'v', vs->varname) < 1) {
ret = AVERROR(EINVAL);
goto fail;
}
}
dirname = dirname_repl;
}
while (segment) {
av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
segment->filename);
if (!hls->use_localtime_mkdir) // segment->filename contains basename only
av_bprintf(&path, "%s%c", dirname, SEPARATOR);
av_bprintf(&path, "%s", segment->filename);
if (!av_bprint_is_complete(&path)) {
ret = AVERROR(ENOMEM);
goto fail;
}
proto = avio_find_protocol_name(s->url);
if (ret = hls_delete_file(hls, vs->avf, path.str, proto))
goto fail;
if ((segment->sub_filename[0] != '\0')) {
vtt_dirname_r = av_strdup(vs->vtt_avf->url);
vtt_dirname = av_dirname(vtt_dirname_r);
av_bprint_clear(&path);
av_bprintf(&path, "%s%c%s", vtt_dirname, SEPARATOR,
segment->sub_filename);
av_freep(&vtt_dirname_r);
if (!av_bprint_is_complete(&path)) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (ret = hls_delete_file(hls, vs->vtt_avf, path.str, proto))
goto fail;
}
av_bprint_clear(&path);
previous_segment = segment;
segment = previous_segment->next;
av_freep(&previous_segment);
}
fail:
av_bprint_finalize(&path, NULL);
av_freep(&dirname_r);
av_freep(&dirname_repl);
return ret;
}
static int randomize(uint8_t *buf, int len)
{
#if CONFIG_GCRYPT
gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
return 0;
#elif CONFIG_OPENSSL
if (RAND_bytes(buf, len))
return 0;
#else
return AVERROR(ENOSYS);
#endif
return AVERROR(EINVAL);
}
static int do_encrypt(AVFormatContext *s, VariantStream *vs)
{
HLSContext *hls = s->priv_data;
int ret;
int len;
AVIOContext *pb;
uint8_t key[KEYSIZE];
char * key_basename_source = (hls->master_m3u8_url) ? hls->master_m3u8_url : s->url;
len = strlen(key_basename_source) + 4 + 1;
hls->key_basename = av_mallocz(len);
if (!hls->key_basename)
return AVERROR(ENOMEM);
av_strlcpy(hls->key_basename, key_basename_source, len);
av_strlcat(hls->key_basename, ".key", len);
if (hls->key_url) {
av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
} else {
av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
}
if (!*hls->iv_string) {
uint8_t iv[16] = { 0 };
char buf[33];
if (!hls->iv) {
AV_WB64(iv + 8, vs->sequence);
} else {
memcpy(iv, hls->iv, sizeof(iv));
}
ff_data_to_hex(buf, iv, sizeof(iv), 0);
memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
}
if (!*hls->key_uri) {
av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
return AVERROR(EINVAL);
}
if (!*hls->key_file) {
av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
return AVERROR(EINVAL);
}
if (!*hls->key_string) {
AVDictionary *options = NULL;
if (!hls->key) {
if ((ret = randomize(key, sizeof(key))) < 0) {
av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
return ret;
}
} else {
memcpy(key, hls->key, sizeof(key));
}
ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
set_http_options(s, &options, hls);
ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, &options);
av_dict_free(&options);
if (ret < 0)
return ret;
avio_seek(pb, 0, SEEK_CUR);
avio_write(pb, key, KEYSIZE);
avio_close(pb);
}
return 0;
}
static int hls_encryption_start(AVFormatContext *s, VariantStream *vs)
{
HLSContext *hls = s->priv_data;
int ret;
AVIOContext *pb;
uint8_t key[KEYSIZE];
AVDictionary *options = NULL;
set_http_options(s, &options, hls);
ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, &options);
av_dict_free(&options);
if (ret < 0) {
av_log(hls, AV_LOG_ERROR,
"error opening key info file %s\n", hls->key_info_file);
return ret;
}
ff_get_line(pb, vs->key_uri, sizeof(vs->key_uri));
vs->key_uri[strcspn(vs->key_uri, "\r\n")] = '\0';
ff_get_line(pb, vs->key_file, sizeof(vs->key_file));
vs->key_file[strcspn(vs->key_file, "\r\n")] = '\0';
ff_get_line(pb, vs->iv_string, sizeof(vs->iv_string));
vs->iv_string[strcspn(vs->iv_string, "\r\n")] = '\0';
ff_format_io_close(s, &pb);
if (!*vs->key_uri) {
av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
return AVERROR(EINVAL);
}
if (!*vs->key_file) {
av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
return AVERROR(EINVAL);
}
set_http_options(s, &options, hls);
ret = s->io_open(s, &pb, vs->key_file, AVIO_FLAG_READ, &options);
av_dict_free(&options);
if (ret < 0) {
av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", vs->key_file);
return ret;
}
ret = avio_read(pb, key, sizeof(key));
ff_format_io_close(s, &pb);
if (ret != sizeof(key)) {
av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", vs->key_file);
if (ret >= 0 || ret == AVERROR_EOF)
ret = AVERROR(EINVAL);
return ret;
}
ff_data_to_hex(vs->key_string, key, sizeof(key), 0);
return 0;
}
static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
{
AVDictionary *options = NULL;
HLSContext *hls = s->priv_data;
AVFormatContext *oc;
AVFormatContext *vtt_oc = NULL;
int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
int remaining_options;
int i, ret;
ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
if (ret < 0)
return ret;
oc = vs->avf;
oc->url = av_strdup("");
if (!oc->url)
return AVERROR(ENOMEM);
oc->interrupt_callback = s->interrupt_callback;
oc->max_delay = s->max_delay;
oc->opaque = s->opaque;
oc->io_open = s->io_open;
oc->io_close = s->io_close;
oc->io_close2 = s->io_close2;
oc->strict_std_compliance = s->strict_std_compliance;
av_dict_copy(&oc->metadata, s->metadata, 0);
if (vs->vtt_oformat) {
ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
if (ret < 0)
return ret;
vtt_oc = vs->vtt_avf;
av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
}
for (i = 0; i < vs->nb_streams; i++) {
AVStream *st;
AVFormatContext *loc;
if (vs->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
loc = vtt_oc;
else
loc = oc;
if (!(st = avformat_new_stream(loc, NULL)))
return AVERROR(ENOMEM);
avcodec_parameters_copy(st->codecpar, vs->streams[i]->codecpar);
if (!oc->oformat->codec_tag ||
av_codec_get_id (oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
av_codec_get_tag(oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_id) <= 0) {
st->codecpar->codec_tag = vs->streams[i]->codecpar->codec_tag;
} else {
st->codecpar->codec_tag = 0;
}
st->sample_aspect_ratio = vs->streams[i]->sample_aspect_ratio;
st->time_base = vs->streams[i]->time_base;
av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
}
vs->start_pos = 0;
vs->new_start = 1;
if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
if (hls->http_persistent > 0) {
//TODO: Support fragment fmp4 for http persistent in HLS muxer.
av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
}
if (hls->max_seg_size > 0) {
av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
return AVERROR_PATCHWELCOME;
}
}
if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
return ret;
if (hls->segment_type == SEGMENT_TYPE_FMP4) {
set_http_options(s, &options, hls);
if (byterange_mode) {
ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
} else {
ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
}
av_dict_free(&options);
}
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
return ret;
}
av_dict_copy(&options, hls->format_options, 0);
if (hls->segment_type == SEGMENT_TYPE_FMP4) {
av_dict_set(&options, "fflags", "-autobsf", 0);
av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
} else {
/* We only require one PAT/PMT per segment. */
char period[21];
snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
av_dict_set(&options, "sdt_period", period, AV_DICT_DONT_OVERWRITE);
av_dict_set(&options, "pat_period", period, AV_DICT_DONT_OVERWRITE);
}
ret = avformat_init_output(oc, &options);
remaining_options = av_dict_count(options);
av_dict_free(&options);
if (ret < 0)
return ret;
if (remaining_options) {
av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n");
return AVERROR(EINVAL);
}
avio_flush(oc->pb);
return 0;
}
static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
{
while (segment) {
if (!av_strcasecmp(segment->filename,filename))
return segment;
segment = segment->next;
}
return (HLSSegment *) NULL;
}
static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls,
VariantStream *vs, HLSSegment *en,
double duration, int64_t pos, int64_t size)
{
if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
strlen(vs->current_segment_final_filename_fmt)) {
char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
if (!new_url) {
return AVERROR(ENOMEM);
}
ff_format_set_url(vs->avf, new_url);
if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
char *filename = NULL;
if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
av_log(hls, AV_LOG_ERROR,
"Invalid second level segment filename template '%s', "
"you can try to remove second_level_segment_size flag\n",
vs->avf->url);
av_freep(&filename);
return AVERROR(EINVAL);
}
ff_format_set_url(vs->avf, filename);
}
if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
char *filename = NULL;
if (replace_int_data_in_filename(&filename, vs->avf->url,
't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
av_log(hls, AV_LOG_ERROR,
"Invalid second level segment filename template '%s', "
"you can try to remove second_level_segment_time flag\n",
vs->avf->url);