FFmpeg  4.4.5
hlsenc.c
Go to the documentation of this file.
1 /*
2  * Apple HTTP Live Streaming segmenter
3  * Copyright (c) 2012, Luca Barbato
4  * Copyright (c) 2017 Akamai Technologies, Inc.
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include "config.h"
24 #include <float.h>
25 #include <stdint.h>
26 #if HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 
30 #if CONFIG_GCRYPT
31 #include <gcrypt.h>
32 #elif CONFIG_OPENSSL
33 #include <openssl/rand.h>
34 #endif
35 
36 #include "libavutil/avassert.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/random_seed.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/log.h"
44 #include "libavutil/time.h"
46 
47 #include "avformat.h"
48 #include "avio_internal.h"
49 #include "avc.h"
50 #if CONFIG_HTTP_PROTOCOL
51 #include "http.h"
52 #endif
53 #include "hlsplaylist.h"
54 #include "internal.h"
55 #include "os_support.h"
56 
57 typedef enum {
64 
65 typedef enum {
69 
70 #define KEYSIZE 16
71 #define LINE_BUFFER_SIZE MAX_URL_SIZE
72 #define HLS_MICROSECOND_UNIT 1000000
73 #define BUFSIZE (16 * 1024)
74 #define POSTFIX_PATTERN "_%d"
75 
76 typedef struct HLSSegment {
79  double duration; /* in seconds */
80  int discont;
85  unsigned var_stream_idx;
86 
88  char iv_string[KEYSIZE*2 + 1];
89 
90  struct HLSSegment *next;
92 } HLSSegment;
93 
94 typedef enum HLSFlags {
95  // Generate a single media file and use byte ranges in the playlist.
96  HLS_SINGLE_FILE = (1 << 0),
97  HLS_DELETE_SEGMENTS = (1 << 1),
98  HLS_ROUND_DURATIONS = (1 << 2),
99  HLS_DISCONT_START = (1 << 3),
100  HLS_OMIT_ENDLIST = (1 << 4),
101  HLS_SPLIT_BY_TIME = (1 << 5),
102  HLS_APPEND_LIST = (1 << 6),
104  HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
105  HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
106  HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
107  HLS_TEMP_FILE = (1 << 11),
108  HLS_PERIODIC_REKEY = (1 << 12),
110  HLS_I_FRAMES_ONLY = (1 << 14),
111 } HLSFlags;
112 
113 typedef enum {
116 } SegmentType;
117 
118 typedef struct VariantStream {
119  unsigned var_stream_idx;
120  unsigned number;
130 
133 
138  double dpp; // duration per packet
144  double duration; // last segment duration computed so far, in seconds
145  int64_t start_pos; // last segment starting position
146  int64_t size; // last segment size
151 
155 
157  char *basename;
160  char *m3u8_name;
161 
163  char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
164 
167 
169 
172  char key_string[KEYSIZE*2 + 1];
173  char iv_string[KEYSIZE*2 + 1];
174 
176  char codec_attr[128];
178  unsigned int nb_streams;
179  int m3u8_created; /* status of media play-list creation */
180  int is_default; /* default status of audio group */
181  const char *language; /* audio lauguage name */
182  const char *agroup; /* audio group name */
183  const char *sgroup; /* subtitle group name */
184  const char *ccgroup; /* closed caption group name */
185  const char *varname; /* variant name */
186 } VariantStream;
187 
188 typedef struct ClosedCaptionsStream {
189  const char *ccgroup; /* closed caption group name */
190  const char *instreamid; /* closed captions INSTREAM-ID */
191  const char *language; /* closed captions langauge */
193 
194 typedef struct HLSContext {
195  const AVClass *class; // Class for private options.
197  uint32_t start_sequence_source_type; // enum StartSequenceSourceType
198 
199  int64_t time; // Set by a private option.
200  int64_t init_time; // Set by a private option.
201  int max_nb_segments; // Set by a private option.
202  int hls_delete_threshold; // Set by a private option.
203 #if FF_API_HLS_WRAP
204  int wrap; // Set by a private option.
205 #endif
206  uint32_t flags; // enum HLSFlags
207  uint32_t pl_type; // enum PlaylistType
211  int resend_init_file; ///< resend init file into disk after refresh m3u8
212 
213  int use_localtime; ///< flag to expand filename with localtime
214  int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
217  int64_t max_seg_size; // every segment file max size
218 
219  char *baseurl;
223 
224  int encrypt;
225  char *key;
226  char *key_url;
227  char *iv;
230 
234  char key_string[KEYSIZE*2 + 1];
235  char iv_string[KEYSIZE*2 + 1];
237 
238  char *method;
239  char *user_agent;
240 
242  unsigned int nb_varstreams;
244  unsigned int nb_ccstreams;
245 
246  int master_m3u8_created; /* status of master play-list creation */
247  char *master_m3u8_url; /* URL of the master m3u8 file */
248  int version; /* HLS version */
249  char *var_stream_map; /* user specified variant stream map string */
250  char *cc_stream_map; /* user specified closed caption streams map string */
252  unsigned int master_publish_rate;
253  int http_persistent;
258  char *headers;
259  int has_default_key; /* has DEFAULT field of var_stream_map */
260  int has_video_m3u8; /* has video stream m3u8 list */
261 } HLSContext;
262 
263 static int strftime_expand(const char *fmt, char **dest)
264 {
265  int r = 1;
266  time_t now0;
267  struct tm *tm, tmpbuf;
268  char *buf;
269 
270  buf = av_mallocz(MAX_URL_SIZE);
271  if (!buf)
272  return AVERROR(ENOMEM);
273 
274  time(&now0);
275  tm = localtime_r(&now0, &tmpbuf);
276  r = strftime(buf, MAX_URL_SIZE, fmt, tm);
277  if (!r) {
278  av_free(buf);
279  return AVERROR(EINVAL);
280  }
281  *dest = buf;
282 
283  return r;
284 }
285 
286 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
288 {
289  HLSContext *hls = s->priv_data;
290  int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
291  int err = AVERROR_MUXER_NOT_FOUND;
292  if (!*pb || !http_base_proto || !hls->http_persistent) {
293  err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
294 #if CONFIG_HTTP_PROTOCOL
295  } else {
296  URLContext *http_url_context = ffio_geturlcontext(*pb);
297  av_assert0(http_url_context);
298  err = ff_http_do_new_request(http_url_context, filename);
299  if (err < 0)
300  ff_format_io_close(s, pb);
301 
302 #endif
303  }
304  return err;
305 }
306 
307 static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
308 {
309  HLSContext *hls = s->priv_data;
310  int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
311  int ret = 0;
312  if (!*pb)
313  return ret;
314  if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
315  ff_format_io_close(s, pb);
316 #if CONFIG_HTTP_PROTOCOL
317  } else {
318  URLContext *http_url_context = ffio_geturlcontext(*pb);
319  av_assert0(http_url_context);
320  avio_flush(*pb);
321  ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
322  ret = ff_http_get_shutdown_status(http_url_context);
323 #endif
324  }
325  return ret;
326 }
327 
329 {
330  int http_base_proto = ff_is_http_proto(s->url);
331 
332  if (c->method) {
333  av_dict_set(options, "method", c->method, 0);
334  } else if (http_base_proto) {
335  av_dict_set(options, "method", "PUT", 0);
336  }
337  if (c->user_agent)
338  av_dict_set(options, "user_agent", c->user_agent, 0);
339  if (c->http_persistent)
340  av_dict_set_int(options, "multiple_requests", 1, 0);
341  if (c->timeout >= 0)
342  av_dict_set_int(options, "timeout", c->timeout, 0);
343  if (c->headers)
344  av_dict_set(options, "headers", c->headers, 0);
345 }
346 
348 {
349  int codec_strlen = strlen(vs->codec_attr);
350  char attr[32];
351 
353  return;
355  return;
356 
357  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
358  uint8_t *data = st->codecpar->extradata;
359  if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
360  snprintf(attr, sizeof(attr),
361  "avc1.%02x%02x%02x", data[5], data[6], data[7]);
362  } else {
363  goto fail;
364  }
365  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
366  uint8_t *data = st->codecpar->extradata;
368  int level = FF_LEVEL_UNKNOWN;
369 
370  if (st->codecpar->profile != FF_PROFILE_UNKNOWN)
371  profile = st->codecpar->profile;
372  if (st->codecpar->level != FF_LEVEL_UNKNOWN)
373  level = st->codecpar->level;
374 
375  /* check the boundary of data which from current position is small than extradata_size */
376  while (data && (data - st->codecpar->extradata + 19) < st->codecpar->extradata_size) {
377  /* get HEVC SPS NAL and seek to profile_tier_level */
378  if (!(data[0] | data[1] | data[2]) && data[3] == 1 && ((data[4] & 0x7E) == 0x42)) {
379  uint8_t *rbsp_buf;
380  int remain_size = 0;
381  int rbsp_size = 0;
382  /* skip start code + nalu header */
383  data += 6;
384  /* process by reference General NAL unit syntax */
385  remain_size = st->codecpar->extradata_size - (data - st->codecpar->extradata);
386  rbsp_buf = ff_nal_unit_extract_rbsp(data, remain_size, &rbsp_size, 0);
387  if (!rbsp_buf)
388  return;
389  if (rbsp_size < 13) {
390  av_freep(&rbsp_buf);
391  break;
392  }
393  /* skip sps_video_parameter_set_id u(4),
394  * sps_max_sub_layers_minus1 u(3),
395  * and sps_temporal_id_nesting_flag u(1) */
396  profile = rbsp_buf[1] & 0x1f;
397  /* skip 8 + 8 + 32 + 4 + 43 + 1 bit */
398  level = rbsp_buf[12];
399  av_freep(&rbsp_buf);
400  break;
401  }
402  data++;
403  }
404  if (st->codecpar->codec_tag == MKTAG('h','v','c','1') &&
406  level != FF_LEVEL_UNKNOWN) {
407  snprintf(attr, sizeof(attr), "%s.%d.4.L%d.B01", av_fourcc2str(st->codecpar->codec_tag), profile, level);
408  } else
409  goto fail;
410  } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
411  snprintf(attr, sizeof(attr), "mp4a.40.33");
412  } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
413  snprintf(attr, sizeof(attr), "mp4a.40.34");
414  } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
415  if (st->codecpar->profile != FF_PROFILE_UNKNOWN)
416  snprintf(attr, sizeof(attr), "mp4a.40.%d", st->codecpar->profile+1);
417  else
418  // This is for backward compatibility with the previous implementation.
419  snprintf(attr, sizeof(attr), "mp4a.40.2");
420  } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
421  snprintf(attr, sizeof(attr), "ac-3");
422  } else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
423  snprintf(attr, sizeof(attr), "ec-3");
424  } else {
425  goto fail;
426  }
427  // Don't write the same attribute multiple times
428  if (!av_stristr(vs->codec_attr, attr)) {
429  snprintf(vs->codec_attr + codec_strlen,
430  sizeof(vs->codec_attr) - codec_strlen,
431  "%s%s", codec_strlen ? "," : "", attr);
432  }
433  return;
434 
435 fail:
436  vs->codec_attr[0] = '\0';
438  return;
439 }
440 
441 static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
442 {
443  const char *p;
444  char c;
445  int addchar_count;
446  int found_count = 0;
447  AVBPrint buf;
448  int ret;
449 
451 
452  p = filename;
453  for (;;) {
454  c = *p;
455  if (c == '\0')
456  break;
457  if (c == '%' && *(p+1) == '%') // %%
458  addchar_count = 2;
459  else if (c == '%' && *(p+1) == placeholder) {
460  av_bprintf(&buf, "%s", datastring);
461  p += 2;
462  addchar_count = 0;
463  found_count ++;
464  } else
465  addchar_count = 1;
466 
467  if (addchar_count > 0) {
468  av_bprint_append_data(&buf, p, addchar_count);
469  p += addchar_count;
470  }
471  }
472  if (!av_bprint_is_complete(&buf)) {
473  av_bprint_finalize(&buf, NULL);
474  return AVERROR(ENOMEM);
475  }
476  if ((ret = av_bprint_finalize(&buf, s)) < 0)
477  return ret;
478  return found_count;
479 }
480 
481 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
482 {
483  const char *p;
484  char c;
485  int nd, addchar_count;
486  int found_count = 0;
487  AVBPrint buf;
488  int ret;
489 
491 
492  p = filename;
493  for (;;) {
494  c = *p;
495  if (c == '\0')
496  break;
497  if (c == '%' && *(p+1) == '%') // %%
498  addchar_count = 2;
499  else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
500  nd = 0;
501  addchar_count = 1;
502  while (av_isdigit(*(p + addchar_count))) {
503  nd = nd * 10 + *(p + addchar_count) - '0';
504  addchar_count++;
505  }
506 
507  if (*(p + addchar_count) == placeholder) {
508  av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
509  p += (addchar_count + 1);
510  addchar_count = 0;
511  found_count++;
512  }
513 
514  } else
515  addchar_count = 1;
516 
517  av_bprint_append_data(&buf, p, addchar_count);
518  p += addchar_count;
519  }
520  if (!av_bprint_is_complete(&buf)) {
521  av_bprint_finalize(&buf, NULL);
522  return AVERROR(ENOMEM);
523  }
524  if ((ret = av_bprint_finalize(&buf, s)) < 0)
525  return ret;
526  return found_count;
527 }
528 
529 static void write_styp(AVIOContext *pb)
530 {
531  avio_wb32(pb, 24);
532  ffio_wfourcc(pb, "styp");
533  ffio_wfourcc(pb, "msdh");
534  avio_wb32(pb, 0); /* minor */
535  ffio_wfourcc(pb, "msdh");
536  ffio_wfourcc(pb, "msix");
537 }
538 
539 static int flush_dynbuf(VariantStream *vs, int *range_length)
540 {
541  AVFormatContext *ctx = vs->avf;
542 
543  if (!ctx->pb) {
544  return AVERROR(EINVAL);
545  }
546 
547  // flush
549 
550  // write out to file
551  *range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
552  ctx->pb = NULL;
553  avio_write(vs->out, vs->temp_buffer, *range_length);
554  avio_flush(vs->out);
555 
556  // re-open buffer
557  return avio_open_dyn_buf(&ctx->pb);
558 }
559 
560 static void reflush_dynbuf(VariantStream *vs, int *range_length)
561 {
562  // re-open buffer
563  avio_write(vs->out, vs->temp_buffer, *range_length);
564 }
565 
566 #if HAVE_DOS_PATHS
567 #define SEPARATOR '\\'
568 #else
569 #define SEPARATOR '/'
570 #endif
571 
573  const char *path, const char *proto)
574 {
575  if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
576  AVDictionary *opt = NULL;
577  AVIOContext *out = NULL;
578  int ret;
579  av_dict_set(&opt, "method", "DELETE", 0);
580  ret = avf->io_open(avf, &out, path, AVIO_FLAG_WRITE, &opt);
581  av_dict_free(&opt);
582  if (ret < 0)
583  return hls->ignore_io_errors ? 1 : ret;
584  ff_format_io_close(avf, &out);
585  } else if (unlink(path) < 0) {
586  av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
587  path, strerror(errno));
588  }
589  return 0;
590 }
591 
593  VariantStream *vs)
594 {
595 
596  HLSSegment *segment, *previous_segment = NULL;
597  float playlist_duration = 0.0f;
598  int ret = 0;
599  int segment_cnt = 0;
600  AVBPrint path;
601  const char *dirname = NULL;
602  char *dirname_r = NULL;
603  char *dirname_repl = NULL;
604  const char *vtt_dirname = NULL;
605  char *vtt_dirname_r = NULL;
606  const char *proto = NULL;
607 
609 
610  segment = vs->segments;
611  while (segment) {
612  playlist_duration += segment->duration;
613  segment = segment->next;
614  }
615 
616  segment = vs->old_segments;
617  segment_cnt = 0;
618  while (segment) {
619  playlist_duration -= segment->duration;
620  previous_segment = segment;
621  segment = previous_segment->next;
622  segment_cnt++;
623  if (playlist_duration <= -previous_segment->duration) {
624  previous_segment->next = NULL;
625  break;
626  }
627  if (segment_cnt >= hls->hls_delete_threshold) {
628  previous_segment->next = NULL;
629  break;
630  }
631  }
632 
633  if (segment && !hls->use_localtime_mkdir) {
634  dirname_r = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
635  dirname = av_dirname(dirname_r);
636  }
637 
638  /* if %v is present in the file's directory
639  * all segment belongs to the same variant, so do it only once before the loop*/
640  if (dirname && av_stristr(dirname, "%v")) {
641  if (!vs->varname) {
642  if (replace_int_data_in_filename(&dirname_repl, dirname, 'v', segment->var_stream_idx) < 1) {
643  ret = AVERROR(EINVAL);
644  goto fail;
645  }
646  } else {
647  if (replace_str_data_in_filename(&dirname_repl, dirname, 'v', vs->varname) < 1) {
648  ret = AVERROR(EINVAL);
649  goto fail;
650  }
651  }
652 
653  dirname = dirname_repl;
654  }
655 
656  while (segment) {
657  av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
658  segment->filename);
659  if (!hls->use_localtime_mkdir) // segment->filename contains basename only
660  av_bprintf(&path, "%s%c", dirname, SEPARATOR);
661  av_bprintf(&path, "%s", segment->filename);
662 
663  if (!av_bprint_is_complete(&path)) {
664  ret = AVERROR(ENOMEM);
665  goto fail;
666  }
667 
668  proto = avio_find_protocol_name(s->url);
669  if (ret = hls_delete_file(hls, vs->avf, path.str, proto))
670  goto fail;
671 
672  if ((segment->sub_filename[0] != '\0')) {
673  vtt_dirname_r = av_strdup(vs->vtt_avf->url);
674  vtt_dirname = av_dirname(vtt_dirname_r);
675 
676  av_bprint_clear(&path);
677  av_bprintf(&path, "%s%c%s", vtt_dirname, SEPARATOR,
678  segment->sub_filename);
679  av_freep(&vtt_dirname_r);
680 
681  if (!av_bprint_is_complete(&path)) {
682  ret = AVERROR(ENOMEM);
683  goto fail;
684  }
685 
686  if (ret = hls_delete_file(hls, vs->vtt_avf, path.str, proto))
687  goto fail;
688  }
689  av_bprint_clear(&path);
690  previous_segment = segment;
691  segment = previous_segment->next;
692  av_freep(&previous_segment);
693  }
694 
695 fail:
696  av_bprint_finalize(&path, NULL);
697  av_freep(&dirname_r);
698  av_freep(&dirname_repl);
699 
700  return ret;
701 }
702 
703 static int randomize(uint8_t *buf, int len)
704 {
705 #if CONFIG_GCRYPT
706  gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
707  return 0;
708 #elif CONFIG_OPENSSL
709  if (RAND_bytes(buf, len))
710  return 0;
711 #else
712  return AVERROR(ENOSYS);
713 #endif
714  return AVERROR(EINVAL);
715 }
716 
718 {
719  HLSContext *hls = s->priv_data;
720  int ret;
721  int len;
722  AVIOContext *pb;
724  char * key_basename_source = (hls->master_m3u8_url) ? hls->master_m3u8_url : s->url;
725 
726  len = strlen(key_basename_source) + 4 + 1;
727  hls->key_basename = av_mallocz(len);
728  if (!hls->key_basename)
729  return AVERROR(ENOMEM);
730 
731  av_strlcpy(hls->key_basename, key_basename_source, len);
732  av_strlcat(hls->key_basename, ".key", len);
733 
734  if (hls->key_url) {
735  av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
736  av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
737  } else {
738  av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
739  av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
740  }
741 
742  if (!*hls->iv_string) {
743  uint8_t iv[16] = { 0 };
744  char buf[33];
745 
746  if (!hls->iv) {
747  AV_WB64(iv + 8, vs->sequence);
748  } else {
749  memcpy(iv, hls->iv, sizeof(iv));
750  }
751  ff_data_to_hex(buf, iv, sizeof(iv), 0);
752  buf[32] = '\0';
753  memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
754  }
755 
756  if (!*hls->key_uri) {
757  av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
758  return AVERROR(EINVAL);
759  }
760 
761  if (!*hls->key_file) {
762  av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
763  return AVERROR(EINVAL);
764  }
765 
766  if (!*hls->key_string) {
768  if (!hls->key) {
769  if ((ret = randomize(key, sizeof(key))) < 0) {
770  av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
771  return ret;
772  }
773  } else {
774  memcpy(key, hls->key, sizeof(key));
775  }
776 
777  ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
778  set_http_options(s, &options, hls);
779  ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, &options);
781  if (ret < 0)
782  return ret;
783  avio_seek(pb, 0, SEEK_CUR);
784  avio_write(pb, key, KEYSIZE);
785  avio_close(pb);
786  }
787  return 0;
788 }
789 
790 
792 {
793  HLSContext *hls = s->priv_data;
794  int ret;
795  AVIOContext *pb;
798 
799  set_http_options(s, &options, hls);
800  ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, &options);
802  if (ret < 0) {
803  av_log(hls, AV_LOG_ERROR,
804  "error opening key info file %s\n", hls->key_info_file);
805  return ret;
806  }
807 
808  ff_get_line(pb, vs->key_uri, sizeof(vs->key_uri));
809  vs->key_uri[strcspn(vs->key_uri, "\r\n")] = '\0';
810 
811  ff_get_line(pb, vs->key_file, sizeof(vs->key_file));
812  vs->key_file[strcspn(vs->key_file, "\r\n")] = '\0';
813 
814  ff_get_line(pb, vs->iv_string, sizeof(vs->iv_string));
815  vs->iv_string[strcspn(vs->iv_string, "\r\n")] = '\0';
816 
817  ff_format_io_close(s, &pb);
818 
819  if (!*vs->key_uri) {
820  av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
821  return AVERROR(EINVAL);
822  }
823 
824  if (!*vs->key_file) {
825  av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
826  return AVERROR(EINVAL);
827  }
828 
829  set_http_options(s, &options, hls);
830  ret = s->io_open(s, &pb, vs->key_file, AVIO_FLAG_READ, &options);
832  if (ret < 0) {
833  av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", vs->key_file);
834  return ret;
835  }
836 
837  ret = avio_read(pb, key, sizeof(key));
838  ff_format_io_close(s, &pb);
839  if (ret != sizeof(key)) {
840  av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", vs->key_file);
841  if (ret >= 0 || ret == AVERROR_EOF)
842  ret = AVERROR(EINVAL);
843  return ret;
844  }
845  ff_data_to_hex(vs->key_string, key, sizeof(key), 0);
846 
847  return 0;
848 }
849 
851 {
853  HLSContext *hls = s->priv_data;
854  AVFormatContext *oc;
855  AVFormatContext *vtt_oc = NULL;
856  int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
857  int remaining_options;
858  int i, ret;
859 
861  if (ret < 0)
862  return ret;
863  oc = vs->avf;
864 
865  oc->url = av_strdup("");
866  if (!oc->url)
867  return AVERROR(ENOMEM);
868 
869  oc->interrupt_callback = s->interrupt_callback;
870  oc->max_delay = s->max_delay;
871  oc->opaque = s->opaque;
872  oc->io_open = s->io_open;
873  oc->io_close = s->io_close;
874  oc->strict_std_compliance = s->strict_std_compliance;
875  av_dict_copy(&oc->metadata, s->metadata, 0);
876 
877  if (vs->vtt_oformat) {
879  if (ret < 0)
880  return ret;
881  vtt_oc = vs->vtt_avf;
882  av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
883  }
884 
885  for (i = 0; i < vs->nb_streams; i++) {
886  AVStream *st;
887  AVFormatContext *loc;
889  loc = vtt_oc;
890  else
891  loc = oc;
892 
893  if (!(st = avformat_new_stream(loc, NULL)))
894  return AVERROR(ENOMEM);
896  if (!oc->oformat->codec_tag ||
900  } else {
901  st->codecpar->codec_tag = 0;
902  }
903 
905  st->time_base = vs->streams[i]->time_base;
906  av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
907  }
908 
909  vs->start_pos = 0;
910  vs->new_start = 1;
911 
912  if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
913  if (hls->http_persistent > 0) {
914  //TODO: Support fragment fmp4 for http persistent in HLS muxer.
915  av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
916  }
917  if (hls->max_seg_size > 0) {
918  av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
919  return AVERROR_PATCHWELCOME;
920  }
921  }
922 
923  if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
924  return ret;
925 
926  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
927  set_http_options(s, &options, hls);
928  if (byterange_mode) {
929  ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
930  } else {
931  ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
932  }
934  }
935  if (ret < 0) {
936  av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
937  return ret;
938  }
939 
941  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
942  av_dict_set(&options, "fflags", "-autobsf", 0);
943  av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
944  } else {
945  /* We only require one PAT/PMT per segment. */
946  char period[21];
947  snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
948  av_dict_set(&options, "sdt_period", period, AV_DICT_DONT_OVERWRITE);
949  av_dict_set(&options, "pat_period", period, AV_DICT_DONT_OVERWRITE);
950  }
951  ret = avformat_init_output(oc, &options);
952  remaining_options = av_dict_count(options);
954  if (ret < 0)
955  return ret;
956  if (remaining_options) {
957  av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n");
958  return AVERROR(EINVAL);
959  }
960  avio_flush(oc->pb);
961  return 0;
962 }
963 
964 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
965 {
966  while (segment) {
967  if (!av_strcasecmp(segment->filename,filename))
968  return segment;
969  segment = segment->next;
970  }
971  return (HLSSegment *) NULL;
972 }
973 
975  VariantStream *vs, HLSSegment *en,
976  double duration, int64_t pos, int64_t size)
977 {
980  char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
981  if (!new_url) {
982  return AVERROR(ENOMEM);
983  }
984  ff_format_set_url(vs->avf, new_url);
986  char *filename = NULL;
987  if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
988  av_log(hls, AV_LOG_ERROR,
989  "Invalid second level segment filename template '%s', "
990  "you can try to remove second_level_segment_size flag\n",
991  vs->avf->url);
992  av_freep(&filename);
993  return AVERROR(EINVAL);
994  }
995  ff_format_set_url(vs->avf, filename);
996  }
998  char *filename = NULL;
999  if (replace_int_data_in_filename(&filename, vs->avf->url,
1000  't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
1001  av_log(hls, AV_LOG_ERROR,
1002  "Invalid second level segment filename template '%s', "
1003  "you can try to remove second_level_segment_time flag\n",
1004  vs->avf->url);
1005  av_freep(&filename);
1006  return AVERROR(EINVAL);
1007  }
1008  ff_format_set_url(vs->avf, filename);
1009  }
1010  }
1011  return 0;
1012 }
1013 
1015 {
1016  int ret = 0;
1017 
1019  av_log(hls, AV_LOG_ERROR,
1020  "second_level_segment_duration hls_flag requires strftime to be true\n");
1021  ret = AVERROR(EINVAL);
1022  }
1023  if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
1024  av_log(hls, AV_LOG_ERROR,
1025  "second_level_segment_size hls_flag requires strfime to be true\n");
1026  ret = AVERROR(EINVAL);
1027  }
1029  av_log(hls, AV_LOG_ERROR,
1030  "second_level_segment_index hls_flag requires strftime to be true\n");
1031  ret = AVERROR(EINVAL);
1032  }
1033 
1034  return ret;
1035 }
1036 
1038 {
1039  const char *proto = avio_find_protocol_name(vs->basename);
1040  int segment_renaming_ok = proto && !strcmp(proto, "file");
1041  int ret = 0;
1042 
1043  if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
1044  av_log(hls, AV_LOG_ERROR,
1045  "second_level_segment_duration hls_flag works only with file protocol segment names\n");
1046  ret = AVERROR(EINVAL);
1047  }
1048  if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
1049  av_log(hls, AV_LOG_ERROR,
1050  "second_level_segment_size hls_flag works only with file protocol segment names\n");
1051  ret = AVERROR(EINVAL);
1052  }
1053 
1054  return ret;
1055 }
1056 
1057 static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
1059  strlen(vs->current_segment_final_filename_fmt)) {
1060  ff_rename(old_filename, vs->avf->url, hls);
1061  }
1062 }
1063 
1065 {
1066  if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
1067  char *filename = NULL;
1068  if (replace_int_data_in_filename(&filename,
1069 #if FF_API_HLS_WRAP
1070  oc->url, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1071 #else
1072  oc->url, 'd', vs->sequence) < 1) {
1073 #endif
1074  av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1075  "you can try to remove second_level_segment_index flag\n",
1076  oc->url);
1077  av_freep(&filename);
1078  return AVERROR(EINVAL);
1079  }
1080  ff_format_set_url(oc, filename);
1081  }
1085  if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
1086  char *filename = NULL;
1087  if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
1088  av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1089  "you can try to remove second_level_segment_size flag\n",
1090  oc->url);
1091  av_freep(&filename);
1092  return AVERROR(EINVAL);
1093  }
1094  ff_format_set_url(oc, filename);
1095  }
1096  if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
1097  char *filename = NULL;
1098  if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
1099  av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1100  "you can try to remove second_level_segment_time flag\n",
1101  oc->url);
1102  av_freep(&filename);
1103  return AVERROR(EINVAL);
1104  }
1105  ff_format_set_url(oc, filename);
1106  }
1107  }
1108  return 0;
1109 }
1110 
1111 /* Create a new segment and append it to the segment list */
1113  VariantStream *vs, double duration, int64_t pos,
1114  int64_t size)
1115 {
1116  HLSSegment *en = av_malloc(sizeof(*en));
1117  const char *filename;
1118  int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1119  int ret;
1120 
1121  if (!en)
1122  return AVERROR(ENOMEM);
1123 
1124  en->var_stream_idx = vs->var_stream_idx;
1125  ret = sls_flags_filename_process(s, hls, vs, en, duration, pos, size);
1126  if (ret < 0) {
1127  av_freep(&en);
1128  return ret;
1129  }
1130 
1131  filename = av_basename(vs->avf->url);
1132 
1133  if (hls->use_localtime_mkdir) {
1134  filename = vs->avf->url;
1135  }
1136  if ((find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
1137  && !byterange_mode) {
1138  av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
1139  }
1140  av_strlcpy(en->filename, filename, sizeof(en->filename));
1141 
1142  if (vs->has_subtitle)
1143  av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
1144  else
1145  en->sub_filename[0] = '\0';
1146 
1147  en->duration = duration;
1148  en->pos = pos;
1149  en->size = size;
1150  en->keyframe_pos = vs->video_keyframe_pos;
1152  en->next = NULL;
1153  en->discont = 0;
1154  en->discont_program_date_time = 0;
1155 
1156  if (vs->discontinuity) {
1157  en->discont = 1;
1158  vs->discontinuity = 0;
1159  }
1160 
1161  if (hls->key_info_file || hls->encrypt) {
1162  av_strlcpy(en->key_uri, vs->key_uri, sizeof(en->key_uri));
1163  av_strlcpy(en->iv_string, vs->iv_string, sizeof(en->iv_string));
1164  }
1165 
1166  if (!vs->segments)
1167  vs->segments = en;
1168  else
1169  vs->last_segment->next = en;
1170 
1171  vs->last_segment = en;
1172 
1173  // EVENT or VOD playlists imply sliding window cannot be used
1174  if (hls->pl_type != PLAYLIST_TYPE_NONE)
1175  hls->max_nb_segments = 0;
1176 
1177  if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
1178  en = vs->segments;
1180  vs->initial_prog_date_time += en->duration;
1181  vs->segments = en->next;
1182  if (en && hls->flags & HLS_DELETE_SEGMENTS &&
1183 #if FF_API_HLS_WRAP
1184  !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
1185 #else
1186  !(hls->flags & HLS_SINGLE_FILE)) {
1187 #endif
1188  en->next = vs->old_segments;
1189  vs->old_segments = en;
1190  if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
1191  return ret;
1192  } else
1193  av_freep(&en);
1194  } else
1195  vs->nb_entries++;
1196 
1197  if (hls->max_seg_size > 0) {
1198  return 0;
1199  }
1200  vs->sequence++;
1201 
1202  return 0;
1203 }
1204 
1205 static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
1206 {
1207  HLSContext *hls = s->priv_data;
1208  AVIOContext *in;
1209  int ret = 0, is_segment = 0;
1210  int64_t new_start_pos;
1211  char line[MAX_URL_SIZE];
1212  const char *ptr;
1213  const char *end;
1214  double discont_program_date_time = 0;
1215 
1216  if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
1217  &s->interrupt_callback, NULL,
1218  s->protocol_whitelist, s->protocol_blacklist)) < 0)
1219  return ret;
1220 
1221  ff_get_chomp_line(in, line, sizeof(line));
1222  if (strcmp(line, "#EXTM3U")) {
1223  ret = AVERROR_INVALIDDATA;
1224  goto fail;
1225  }
1226 
1227  vs->discontinuity = 0;
1228  while (!avio_feof(in)) {
1229  ff_get_chomp_line(in, line, sizeof(line));
1230  if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
1231  int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1232  if (tmp_sequence < vs->sequence)
1233  av_log(hls, AV_LOG_VERBOSE,
1234  "Found playlist sequence number was smaller """
1235  "than specified start sequence number: %"PRId64" < %"PRId64", "
1236  "omitting\n", tmp_sequence, hls->start_sequence);
1237  else {
1238  av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
1239  vs->sequence = tmp_sequence;
1240  }
1241  } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
1242  is_segment = 1;
1243  vs->discontinuity = 1;
1244  } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1245  is_segment = 1;
1246  vs->duration = atof(ptr);
1247  } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
1248  ptr = av_stristr(line, "URI=\"");
1249  if (ptr) {
1250  ptr += strlen("URI=\"");
1251  end = av_stristr(ptr, ",");
1252  if (end) {
1253  av_strlcpy(vs->key_uri, ptr, end - ptr);
1254  } else {
1255  av_strlcpy(vs->key_uri, ptr, sizeof(vs->key_uri));
1256  }
1257  }
1258 
1259  ptr = av_stristr(line, "IV=0x");
1260  if (ptr) {
1261  ptr += strlen("IV=0x");
1262  end = av_stristr(ptr, ",");
1263  if (end) {
1264  av_strlcpy(vs->iv_string, ptr, end - ptr);
1265  } else {
1266  av_strlcpy(vs->iv_string, ptr, sizeof(vs->iv_string));
1267  }
1268  }
1269  } else if (av_strstart(line, "#EXT-X-PROGRAM-DATE-TIME:", &ptr)) {
1270  struct tm program_date_time;
1271  int y,M,d,h,m,s;
1272  double ms;
1273  if (sscanf(ptr, "%d-%d-%dT%d:%d:%d.%lf", &y, &M, &d, &h, &m, &s, &ms) != 7) {
1274  ret = AVERROR_INVALIDDATA;
1275  goto fail;
1276  }
1277 
1278  program_date_time.tm_year = y - 1900;
1279  program_date_time.tm_mon = M - 1;
1280  program_date_time.tm_mday = d;
1281  program_date_time.tm_hour = h;
1282  program_date_time.tm_min = m;
1283  program_date_time.tm_sec = s;
1284  program_date_time.tm_isdst = -1;
1285 
1286  discont_program_date_time = mktime(&program_date_time);
1287  discont_program_date_time += (double)(ms / 1000);
1288  } else if (av_strstart(line, "#", NULL)) {
1289  continue;
1290  } else if (line[0]) {
1291  if (is_segment) {
1292  char *new_file = av_strdup(line);
1293  if (!new_file) {
1294  ret = AVERROR(ENOMEM);
1295  goto fail;
1296  }
1297  ff_format_set_url(vs->avf, new_file);
1298  is_segment = 0;
1299  new_start_pos = avio_tell(vs->avf->pb);
1300  vs->size = new_start_pos - vs->start_pos;
1301  ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
1302  vs->last_segment->discont_program_date_time = discont_program_date_time;
1303  discont_program_date_time += vs->duration;
1304  if (ret < 0)
1305  goto fail;
1306  vs->start_pos = new_start_pos;
1307  }
1308  }
1309  }
1310 
1311 fail:
1312  avio_close(in);
1313  return ret;
1314 }
1315 
1317 {
1318  HLSSegment *en;
1319 
1320  while (p) {
1321  en = p;
1322  p = p->next;
1323  av_freep(&en);
1324  }
1325 }
1326 
1328 {
1329  size_t len = strlen(oc->url);
1330  char *final_filename = av_strdup(oc->url);
1331  int ret;
1332 
1333  if (!final_filename)
1334  return AVERROR(ENOMEM);
1335  final_filename[len-4] = '\0';
1336  ret = ff_rename(oc->url, final_filename, s);
1337  oc->url[len-4] = '\0';
1338  av_freep(&final_filename);
1339  return ret;
1340 }
1341 
1342 static const char* get_relative_url(const char *master_url, const char *media_url)
1343 {
1344  const char *p = strrchr(master_url, '/');
1345  size_t base_len = 0;
1346 
1347  if (!p) p = strrchr(master_url, '\\');
1348 
1349  if (p) {
1350  base_len = p - master_url;
1351  if (av_strncasecmp(master_url, media_url, base_len)) {
1352  av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
1353  return NULL;
1354  }
1355  } else {
1356  return media_url;
1357  }
1358 
1359  return media_url + base_len + 1;
1360 }
1361 
1363 {
1365  stream,
1367  NULL
1368  );
1369 
1370  if (stream->codecpar->bit_rate)
1371  return stream->codecpar->bit_rate;
1372  else if (props)
1373  return props->max_bitrate;
1374 
1375  return 0;
1376 }
1377 
1379  VariantStream * const input_vs)
1380 {
1381  HLSContext *hls = s->priv_data;
1382  VariantStream *vs, *temp_vs;
1383  AVStream *vid_st, *aud_st;
1385  unsigned int i, j;
1386  int ret, bandwidth;
1387  const char *m3u8_rel_name = NULL;
1388  const char *vtt_m3u8_rel_name = NULL;
1389  const char *ccgroup;
1390  const char *sgroup = NULL;
1391  ClosedCaptionsStream *ccs;
1392  const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
1393  int is_file_proto = proto && !strcmp(proto, "file");
1394  int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || hls->master_publish_rate);
1395  char temp_filename[MAX_URL_SIZE];
1396 
1397  input_vs->m3u8_created = 1;
1398  if (!hls->master_m3u8_created) {
1399  /* For the first time, wait until all the media playlists are created */
1400  for (i = 0; i < hls->nb_varstreams; i++)
1401  if (!hls->var_streams[i].m3u8_created)
1402  return 0;
1403  } else {
1404  /* Keep publishing the master playlist at the configured rate */
1405  if (&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
1406  input_vs->number % hls->master_publish_rate)
1407  return 0;
1408  }
1409 
1410  set_http_options(s, &options, hls);
1411  snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", hls->master_m3u8_url);
1412  ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options);
1414  if (ret < 0) {
1415  av_log(s, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
1416  temp_filename);
1417  goto fail;
1418  }
1419 
1421 
1422  for (i = 0; i < hls->nb_ccstreams; i++) {
1423  ccs = &(hls->cc_streams[i]);
1424  avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
1425  avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
1426  avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
1427  if (ccs->language)
1428  avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
1429  avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
1430  }
1431 
1432  /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
1433  for (i = 0; i < hls->nb_varstreams; i++) {
1434  vs = &(hls->var_streams[i]);
1435 
1436  if (vs->has_video || vs->has_subtitle || !vs->agroup)
1437  continue;
1438 
1439  m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1440  if (!m3u8_rel_name) {
1441  av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1442  goto fail;
1443  }
1444 
1445  ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
1446  }
1447 
1448  /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
1449  for (i = 0; i < hls->nb_varstreams; i++) {
1450  vs = &(hls->var_streams[i]);
1451 
1452  m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1453  if (!m3u8_rel_name) {
1454  av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1455  goto fail;
1456  }
1457 
1458  vid_st = NULL;
1459  aud_st = NULL;
1460  for (j = 0; j < vs->nb_streams; j++) {
1462  vid_st = vs->streams[j];
1463  else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1464  aud_st = vs->streams[j];
1465  }
1466 
1467  if (!vid_st && !aud_st) {
1468  av_log(s, AV_LOG_WARNING, "Media stream not found\n");
1469  continue;
1470  }
1471 
1472  /**
1473  * Traverse through the list of audio only rendition streams and find
1474  * the rendition which has highest bitrate in the same audio group
1475  */
1476  if (vs->agroup) {
1477  for (j = 0; j < hls->nb_varstreams; j++) {
1478  temp_vs = &(hls->var_streams[j]);
1479  if (!temp_vs->has_video && !temp_vs->has_subtitle &&
1480  temp_vs->agroup &&
1481  !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
1482  if (!aud_st)
1483  aud_st = temp_vs->streams[0];
1484  if (temp_vs->streams[0]->codecpar->bit_rate >
1485  aud_st->codecpar->bit_rate)
1486  aud_st = temp_vs->streams[0];
1487  }
1488  }
1489  }
1490 
1491  bandwidth = 0;
1492  if (vid_st)
1493  bandwidth += get_stream_bit_rate(vid_st);
1494  if (aud_st)
1495  bandwidth += get_stream_bit_rate(aud_st);
1496  bandwidth += bandwidth / 10;
1497 
1498  ccgroup = NULL;
1499  if (vid_st && vs->ccgroup) {
1500  /* check if this group name is available in the cc map string */
1501  for (j = 0; j < hls->nb_ccstreams; j++) {
1502  ccs = &(hls->cc_streams[j]);
1503  if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
1504  ccgroup = vs->ccgroup;
1505  break;
1506  }
1507  }
1508  if (j == hls->nb_ccstreams)
1509  av_log(s, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
1510  vs->ccgroup);
1511  }
1512 
1513  if (vid_st && vs->sgroup) {
1514  sgroup = vs->sgroup;
1515  vtt_m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->vtt_m3u8_name);
1516  if (!vtt_m3u8_rel_name) {
1517  av_log(s, AV_LOG_WARNING, "Unable to find relative subtitle URL\n");
1518  break;
1519  }
1520 
1521  ff_hls_write_subtitle_rendition(hls->m3u8_out, sgroup, vtt_m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
1522  }
1523 
1524  if (!hls->has_default_key || !hls->has_video_m3u8) {
1525  ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1526  aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1527  } else {
1528  if (vid_st) {
1529  ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1530  aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1531  }
1532  }
1533  }
1534 fail:
1535  if (ret >=0)
1536  hls->master_m3u8_created = 1;
1537  hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
1538  if (use_temp_file)
1539  ff_rename(temp_filename, hls->master_m3u8_url, s);
1540 
1541  return ret;
1542 }
1543 
1544 static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
1545 {
1546  HLSContext *hls = s->priv_data;
1547  HLSSegment *en;
1548  int target_duration = 0;
1549  int ret = 0;
1550  char temp_filename[MAX_URL_SIZE];
1551  char temp_vtt_filename[MAX_URL_SIZE];
1552  int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
1553  const char *proto = avio_find_protocol_name(vs->m3u8_name);
1554  int is_file_proto = proto && !strcmp(proto, "file");
1555  int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || !(hls->pl_type == PLAYLIST_TYPE_VOD));
1556  static unsigned warned_non_file;
1557  char *key_uri = NULL;
1558  char *iv_string = NULL;
1560  double prog_date_time = vs->initial_prog_date_time;
1561  double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
1562  int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1563 
1564  hls->version = 3;
1565  if (byterange_mode) {
1566  hls->version = 4;
1567  sequence = 0;
1568  }
1569 
1570  if (hls->flags & HLS_I_FRAMES_ONLY) {
1571  hls->version = 4;
1572  }
1573 
1574  if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
1575  hls->version = 6;
1576  }
1577 
1578  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1579  hls->version = 7;
1580  }
1581 
1582  if (!is_file_proto && (hls->flags & HLS_TEMP_FILE) && !warned_non_file++)
1583  av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1584 
1585  set_http_options(s, &options, hls);
1586  snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", vs->m3u8_name);
1587  if ((ret = hlsenc_io_open(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename, &options)) < 0) {
1588  if (hls->ignore_io_errors)
1589  ret = 0;
1590  goto fail;
1591  }
1592 
1593  for (en = vs->segments; en; en = en->next) {
1594  if (target_duration <= en->duration)
1595  target_duration = lrint(en->duration);
1596  }
1597 
1598  vs->discontinuity_set = 0;
1599  ff_hls_write_playlist_header(byterange_mode ? hls->m3u8_out : vs->out, hls->version, hls->allowcache,
1600  target_duration, sequence, hls->pl_type, hls->flags & HLS_I_FRAMES_ONLY);
1601 
1602  if ((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0) {
1603  avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
1604  vs->discontinuity_set = 1;
1605  }
1606  if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
1607  avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
1608  }
1609  for (en = vs->segments; en; en = en->next) {
1610  if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1611  av_strcasecmp(en->iv_string, iv_string))) {
1612  avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1613  if (*en->iv_string)
1614  avio_printf(byterange_mode ? hls->m3u8_out : vs->out, ",IV=0x%s", en->iv_string);
1615  avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "\n");
1616  key_uri = en->key_uri;
1617  iv_string = en->iv_string;
1618  }
1619 
1620  if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
1621  ff_hls_write_init_file(byterange_mode ? hls->m3u8_out : vs->out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
1622  hls->flags & HLS_SINGLE_FILE, vs->init_range_length, 0);
1623  }
1624 
1625  ret = ff_hls_write_file_entry(byterange_mode ? hls->m3u8_out : vs->out, en->discont, byterange_mode,
1626  en->duration, hls->flags & HLS_ROUND_DURATIONS,
1627  en->size, en->pos, hls->baseurl,
1628  en->filename,
1629  en->discont_program_date_time ? &en->discont_program_date_time : prog_date_time_p,
1631  if (en->discont_program_date_time)
1633  if (ret < 0) {
1634  av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1635  }
1636  }
1637 
1638  if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1639  ff_hls_write_end_list(byterange_mode ? hls->m3u8_out : vs->out);
1640 
1641  if (vs->vtt_m3u8_name) {
1642  snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
1643  if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, temp_vtt_filename, &options)) < 0) {
1644  if (hls->ignore_io_errors)
1645  ret = 0;
1646  goto fail;
1647  }
1649  target_duration, sequence, PLAYLIST_TYPE_NONE, 0);
1650  for (en = vs->segments; en; en = en->next) {
1651  ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
1652  en->duration, 0, en->size, en->pos,
1653  hls->baseurl, en->sub_filename, NULL, 0, 0, 0);
1654  if (ret < 0) {
1655  av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1656  }
1657  }
1658 
1659  if (last)
1661 
1662  }
1663 
1664 fail:
1666  ret = hlsenc_io_close(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename);
1667  if (ret < 0) {
1668  return ret;
1669  }
1671  if (use_temp_file) {
1672  ff_rename(temp_filename, vs->m3u8_name, s);
1673  if (vs->vtt_m3u8_name)
1674  ff_rename(temp_vtt_filename, vs->vtt_m3u8_name, s);
1675  }
1676  if (ret >= 0 && hls->master_pl_name)
1677  if (create_master_playlist(s, vs) < 0)
1678  av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
1679 
1680  return ret;
1681 }
1682 
1684 {
1685  HLSContext *c = s->priv_data;
1686  AVFormatContext *oc = vs->avf;
1687  AVFormatContext *vtt_oc = vs->vtt_avf;
1689  const char *proto = NULL;
1690  int use_temp_file = 0;
1691  char iv_string[KEYSIZE*2 + 1];
1692  int err = 0;
1693 
1694  if (c->flags & HLS_SINGLE_FILE) {
1695  char *new_name = av_strdup(vs->basename);
1696  if (!new_name)
1697  return AVERROR(ENOMEM);
1698  ff_format_set_url(oc, new_name);
1699  if (vs->vtt_basename) {
1700  new_name = av_strdup(vs->vtt_basename);
1701  if (!new_name)
1702  return AVERROR(ENOMEM);
1703  ff_format_set_url(vtt_oc, new_name);
1704  }
1705  } else if (c->max_seg_size > 0) {
1706  char *filename = NULL;
1707  if (replace_int_data_in_filename(&filename,
1708 #if FF_API_HLS_WRAP
1709  vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1710 #else
1711  vs->basename, 'd', vs->sequence) < 1) {
1712 #endif
1713  av_freep(&filename);
1714  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -strftime 1 with it\n", vs->basename);
1715  return AVERROR(EINVAL);
1716  }
1717  ff_format_set_url(oc, filename);
1718  } else {
1719  if (c->use_localtime) {
1720  int r;
1721  char *expanded = NULL;
1722 
1723  r = strftime_expand(vs->basename, &expanded);
1724  if (r < 0) {
1725  av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
1726  return r;
1727  }
1728  ff_format_set_url(oc, expanded);
1729 
1730  err = sls_flag_use_localtime_filename(oc, c, vs);
1731  if (err < 0) {
1732  return AVERROR(ENOMEM);
1733  }
1734 
1735  if (c->use_localtime_mkdir) {
1736  const char *dir;
1737  char *fn_copy = av_strdup(oc->url);
1738  if (!fn_copy)
1739  return AVERROR(ENOMEM);
1740  dir = av_dirname(fn_copy);
1741  if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1742  av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1743  av_freep(&fn_copy);
1744  return AVERROR(errno);
1745  }
1746  av_freep(&fn_copy);
1747  }
1748  } else {
1749  char *filename = NULL;
1750  if (replace_int_data_in_filename(&filename,
1751 #if FF_API_HLS_WRAP
1752  vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1753 #else
1754  vs->basename, 'd', vs->sequence) < 1) {
1755 #endif
1756  av_freep(&filename);
1757  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -strftime 1 with it\n", vs->basename);
1758  return AVERROR(EINVAL);
1759  }
1760  ff_format_set_url(oc, filename);
1761  }
1762  if (vs->vtt_basename) {
1763  char *filename = NULL;
1764  if (replace_int_data_in_filename(&filename,
1765 #if FF_API_HLS_WRAP
1766  vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1767 #else
1768  vs->vtt_basename, 'd', vs->sequence) < 1) {
1769 #endif
1770  av_freep(&filename);
1771  av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
1772  return AVERROR(EINVAL);
1773  }
1774  ff_format_set_url(vtt_oc, filename);
1775  }
1776  }
1777 
1778  proto = avio_find_protocol_name(oc->url);
1779  use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
1780 
1781  if (use_temp_file) {
1782  char *new_name = av_asprintf("%s.tmp", oc->url);
1783  if (!new_name)
1784  return AVERROR(ENOMEM);
1785  ff_format_set_url(oc, new_name);
1786  }
1787 
1788  if (c->key_info_file || c->encrypt) {
1789  if (c->segment_type == SEGMENT_TYPE_FMP4) {
1790  av_log(s, AV_LOG_ERROR, "Encrypted fmp4 not yet supported\n");
1791  return AVERROR_PATCHWELCOME;
1792  }
1793 
1794  if (c->key_info_file && c->encrypt) {
1795  av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1796  " ignoring -hls_enc\n");
1797  }
1798 
1799  if (!vs->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
1800  if (c->key_info_file) {
1801  if ((err = hls_encryption_start(s, vs)) < 0)
1802  goto fail;
1803  } else {
1804  if (!c->encrypt_started) {
1805  if ((err = do_encrypt(s, vs)) < 0)
1806  goto fail;
1807  c->encrypt_started = 1;
1808  }
1809  av_strlcpy(vs->key_uri, c->key_uri, sizeof(vs->key_uri));
1810  av_strlcpy(vs->key_string, c->key_string, sizeof(vs->key_string));
1811  av_strlcpy(vs->iv_string, c->iv_string, sizeof(vs->iv_string));
1812  }
1813  vs->encrypt_started = 1;
1814  }
1815  err = av_strlcpy(iv_string, vs->iv_string, sizeof(iv_string));
1816  if (!err) {
1817  snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
1818  memset(vs->iv_string, 0, sizeof(vs->iv_string));
1819  memcpy(vs->iv_string, iv_string, sizeof(iv_string));
1820  }
1821  }
1822  if (c->segment_type != SEGMENT_TYPE_FMP4) {
1823  if (oc->oformat->priv_class && oc->priv_data) {
1824  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1825  }
1826  if (c->flags & HLS_SINGLE_FILE) {
1827  if (c->key_info_file || c->encrypt) {
1828  av_dict_set(&options, "encryption_key", vs->key_string, 0);
1829  av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
1830 
1831  /* Write temp file with cryption content */
1832  av_freep(&vs->basename_tmp);
1833  vs->basename_tmp = av_asprintf("crypto:%s.tmp", oc->url);
1834 
1835  /* append temp file content into single file */
1836  av_freep(&vs->basename);
1837  vs->basename = av_asprintf("%s", oc->url);
1838  } else {
1839  vs->basename_tmp = vs->basename;
1840  }
1842  if (!vs->out_single_file)
1843  if ((err = hlsenc_io_open(s, &vs->out_single_file, vs->basename, &options)) < 0) {
1844  if (c->ignore_io_errors)
1845  err = 0;
1846  goto fail;
1847  }
1848 
1849  if ((err = hlsenc_io_open(s, &vs->out, vs->basename_tmp, &options)) < 0) {
1850  if (c->ignore_io_errors)
1851  err = 0;
1852  goto fail;
1853  }
1854 
1855  }
1856  }
1857  if (vs->vtt_basename) {
1859  if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
1860  if (c->ignore_io_errors)
1861  err = 0;
1862  goto fail;
1863  }
1864  }
1866 
1867  if (vs->vtt_basename) {
1868  err = avformat_write_header(vtt_oc,NULL);
1869  if (err < 0)
1870  return err;
1871  }
1872 
1873  return 0;
1874 fail:
1876 
1877  return err;
1878 }
1879 
1881 {
1882  char b[21];
1883  time_t t = time(NULL);
1884  struct tm *p, tmbuf;
1885  HLSContext *hls = s->priv_data;
1886 
1887  p = localtime_r(&t, &tmbuf);
1888  // no %s support when strftime returned error or left format string unchanged
1889  // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
1890  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1891  return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
1892  }
1893  return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1894 }
1895 
1896 static int append_postfix(char *name, int name_buf_len, int i)
1897 {
1898  char *p;
1899  char extension[10] = {'\0'};
1900 
1901  p = strrchr(name, '.');
1902  if (p) {
1903  av_strlcpy(extension, p, sizeof(extension));
1904  *p = '\0';
1905  }
1906 
1907  snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
1908 
1909  if (strlen(extension))
1910  av_strlcat(name, extension, name_buf_len);
1911 
1912  return 0;
1913 }
1914 
1915 static int validate_name(int nb_vs, const char *fn)
1916 {
1917  const char *filename, *subdir_name;
1918  char *fn_dup = NULL;
1919  int ret = 0;
1920 
1921  if (!fn)
1922  return AVERROR(EINVAL);
1923 
1924  fn_dup = av_strdup(fn);
1925  if (!fn_dup)
1926  return AVERROR(ENOMEM);
1927  filename = av_basename(fn);
1928  subdir_name = av_dirname(fn_dup);
1929 
1930  if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
1931  av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected "
1932  "either in the filename or in the sub-directory name of file %s\n", fn);
1933  ret = AVERROR(EINVAL);
1934  goto fail;
1935  }
1936 
1937  if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
1938  av_log(NULL, AV_LOG_ERROR, "%%v is expected either in the filename or "
1939  "in the sub-directory name of file %s, but only in one of them\n", fn);
1940  ret = AVERROR(EINVAL);
1941  goto fail;
1942  }
1943 
1944 fail:
1945  av_freep(&fn_dup);
1946  return ret;
1947 }
1948 
1949 static int format_name(const char *buf, char **s, int index, const char *varname)
1950 {
1951  const char *proto, *dir;
1952  char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
1953  int ret = 0;
1954 
1955  orig_buf_dup = av_strdup(buf);
1956  if (!orig_buf_dup)
1957  return AVERROR(ENOMEM);
1958 
1959  if (!av_stristr(buf, "%v")) {
1960  *s = orig_buf_dup;
1961  return 0;
1962  }
1963 
1964  if (!varname) {
1965  if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
1966  ret = AVERROR(EINVAL);
1967  goto fail;
1968  }
1969  } else {
1970  if (replace_str_data_in_filename(s, orig_buf_dup, 'v', varname) < 1) {
1971  ret = AVERROR(EINVAL);
1972  goto fail;
1973  }
1974  }
1975 
1976  proto = avio_find_protocol_name(orig_buf_dup);
1977  dir = av_dirname(orig_buf_dup);
1978 
1979  /* if %v is present in the file's directory, create sub-directory */
1980  if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
1981  mod_buf_dup = av_strdup(*s);
1982  dir = av_dirname(mod_buf_dup);
1983  if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1984  ret = AVERROR(errno);
1985  goto fail;
1986  }
1987  }
1988 
1989 fail:
1990  av_freep(&orig_buf_dup);
1991  av_freep(&mod_buf_dup);
1992  return ret;
1993 }
1994 
1996  enum AVMediaType codec_type,
1997  int64_t stream_id)
1998 {
1999  unsigned int stream_index, cnt;
2000  if (stream_id < 0 || stream_id > s->nb_streams - 1)
2001  return -1;
2002  cnt = 0;
2003  for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
2004  if (s->streams[stream_index]->codecpar->codec_type != codec_type)
2005  continue;
2006  if (cnt == stream_id)
2007  return stream_index;
2008  cnt++;
2009  }
2010  return -1;
2011 }
2012 
2014 {
2015  HLSContext *hls = s->priv_data;
2016  VariantStream *vs;
2017  int stream_index, i, j;
2018  enum AVMediaType codec_type;
2019  int nb_varstreams = 0, nb_streams;
2020  char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
2021  const char *val;
2022 
2023  /**
2024  * Expected format for var_stream_map string is as below:
2025  * "a:0,v:0 a:1,v:1"
2026  * "a:0,agroup:a0,default:1,language:ENG a:1,agroup:a1,default:0 v:0,agroup:a0 v:1,agroup:a1"
2027  * This string specifies how to group the audio, video and subtitle streams
2028  * into different variant streams. The variant stream groups are separated
2029  * by space.
2030  *
2031  * a:, v:, s: are keys to specify audio, video and subtitle streams
2032  * respectively. Allowed values are 0 to 9 digits (limited just based on
2033  * practical usage)
2034  *
2035  * agroup: is key to specify audio group. A string can be given as value.
2036  * sgroup: is key to specify subtitle group. A string can be given as value.
2037  */
2038  p = av_strdup(hls->var_stream_map);
2039  if (!p)
2040  return AVERROR(ENOMEM);
2041 
2042  q = p;
2043  while (av_strtok(q, " \t", &saveptr1)) {
2044  q = NULL;
2045  nb_varstreams++;
2046  }
2047  av_freep(&p);
2048 
2049  hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * nb_varstreams);
2050  if (!hls->var_streams)
2051  return AVERROR(ENOMEM);
2052  hls->nb_varstreams = nb_varstreams;
2053 
2054  p = hls->var_stream_map;
2055  nb_varstreams = 0;
2056  while (varstr = av_strtok(p, " \t", &saveptr1)) {
2057  p = NULL;
2058 
2059  if (nb_varstreams < hls->nb_varstreams) {
2060  vs = &(hls->var_streams[nb_varstreams]);
2061  vs->var_stream_idx = nb_varstreams;
2062  vs->is_default = 0;
2063  nb_varstreams++;
2064  } else
2065  return AVERROR(EINVAL);
2066 
2067  q = varstr;
2068  while (1) {
2069  if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
2070  !av_strncasecmp(q, "s:", 2))
2071  vs->nb_streams++;
2072  q = strchr(q, ',');
2073  if (!q)
2074  break;
2075  q++;
2076  }
2077  vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
2078  if (!vs->streams)
2079  return AVERROR(ENOMEM);
2080 
2081  nb_streams = 0;
2082  while (keyval = av_strtok(varstr, ",", &saveptr2)) {
2083  int64_t num;
2084  char *end;
2085  varstr = NULL;
2086  if (av_strstart(keyval, "language:", &val)) {
2087  vs->language = val;
2088  continue;
2089  } else if (av_strstart(keyval, "default:", &val)) {
2090  vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
2091  (!av_strncasecmp(val, "1", strlen("1"))));
2092  hls->has_default_key = 1;
2093  continue;
2094  } else if (av_strstart(keyval, "name:", &val)) {
2095  vs->varname = val;
2096  continue;
2097  } else if (av_strstart(keyval, "agroup:", &val)) {
2098  vs->agroup = val;
2099  continue;
2100  } else if (av_strstart(keyval, "sgroup:", &val)) {
2101  vs->sgroup = val;
2102  continue;
2103  } else if (av_strstart(keyval, "ccgroup:", &val)) {
2104  vs->ccgroup = val;
2105  continue;
2106  } else if (av_strstart(keyval, "v:", &val)) {
2108  hls->has_video_m3u8 = 1;
2109  } else if (av_strstart(keyval, "a:", &val)) {
2111  } else if (av_strstart(keyval, "s:", &val)) {
2113  } else {
2114  av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2115  return AVERROR(EINVAL);
2116  }
2117 
2118  num = strtoll(val, &end, 10);
2119  if (!av_isdigit(*val) || *end != '\0') {
2120  av_log(s, AV_LOG_ERROR, "Invalid stream number: '%s'\n", val);
2121  return AVERROR(EINVAL);
2122  }
2123  stream_index = get_nth_codec_stream_index(s, codec_type, num);
2124 
2125  if (stream_index >= 0 && nb_streams < vs->nb_streams) {
2126  for (i = 0; nb_streams > 0 && i < nb_streams; i++) {
2127  if (vs->streams[i] == s->streams[stream_index]) {
2128  av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once inside "
2129  "variant definition #%d\n", nb_varstreams - 1);
2130  return AVERROR(EINVAL);
2131  }
2132  }
2133  for (j = 0; nb_varstreams > 1 && j < nb_varstreams - 1; j++) {
2134  for (i = 0; i < hls->var_streams[j].nb_streams; i++) {
2135  if (hls->var_streams[j].streams[i] == s->streams[stream_index]) {
2136  av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once "
2137  "in two different variant definitions #%d and #%d\n",
2138  j, nb_varstreams - 1);
2139  return AVERROR(EINVAL);
2140  }
2141  }
2142  }
2143  vs->streams[nb_streams++] = s->streams[stream_index];
2144  } else {
2145  av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
2146  return AVERROR(EINVAL);
2147  }
2148  }
2149  }
2150  av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
2151  hls->nb_varstreams);
2152 
2153  return 0;
2154 }
2155 
2157 {
2158  HLSContext *hls = s->priv_data;
2159  int nb_ccstreams = 0;
2160  char *p, *q, *ccstr, *keyval;
2161  char *saveptr1 = NULL, *saveptr2 = NULL;
2162  const char *val;
2163  ClosedCaptionsStream *ccs;
2164 
2165  p = av_strdup(hls->cc_stream_map);
2166  if(!p)
2167  return AVERROR(ENOMEM);
2168 
2169  q = p;
2170  while (av_strtok(q, " \t", &saveptr1)) {
2171  q = NULL;
2172  nb_ccstreams++;
2173  }
2174  av_freep(&p);
2175 
2176  hls->cc_streams = av_mallocz(sizeof(*hls->cc_streams) * nb_ccstreams);
2177  if (!hls->cc_streams)
2178  return AVERROR(ENOMEM);
2179  hls->nb_ccstreams = nb_ccstreams;
2180 
2181  p = hls->cc_stream_map;
2182  nb_ccstreams = 0;
2183  while (ccstr = av_strtok(p, " \t", &saveptr1)) {
2184  p = NULL;
2185 
2186  if (nb_ccstreams < hls->nb_ccstreams)
2187  ccs = &(hls->cc_streams[nb_ccstreams++]);
2188  else
2189  return AVERROR(EINVAL);
2190 
2191  while (keyval = av_strtok(ccstr, ",", &saveptr2)) {
2192  ccstr = NULL;
2193 
2194  if (av_strstart(keyval, "ccgroup:", &val)) {
2195  ccs->ccgroup = val;
2196  } else if (av_strstart(keyval, "instreamid:", &val)) {
2197  ccs->instreamid = val;
2198  } else if (av_strstart(keyval, "language:", &val)) {
2199  ccs->language = val;
2200  } else {
2201  av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2202  return AVERROR(EINVAL);
2203  }
2204  }
2205 
2206  if (!ccs->ccgroup || !ccs->instreamid) {
2207  av_log(s, AV_LOG_ERROR, "Insufficient parameters in cc stream map string\n");
2208  return AVERROR(EINVAL);
2209  }
2210 
2211  if (av_strstart(ccs->instreamid, "CC", &val)) {
2212  if (atoi(val) < 1 || atoi(val) > 4) {
2213  av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
2214  atoi(val), ccs->instreamid);
2215  return AVERROR(EINVAL);
2216  }
2217  } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
2218  if (atoi(val) < 1 || atoi(val) > 63) {
2219  av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
2220  atoi(val), ccs->instreamid);
2221  return AVERROR(EINVAL);
2222  }
2223  } else {
2224  av_log(s, AV_LOG_ERROR, "Invalid instream ID %s, supported are CCn or SERVICEn\n",
2225  ccs->instreamid);
2226  return AVERROR(EINVAL);
2227  }
2228  }
2229 
2230  return 0;
2231 }
2232 
2234 {
2235  HLSContext *hls = s->priv_data;
2236  unsigned int i;
2237  int ret = 0;
2238 
2239  if (hls->cc_stream_map) {
2241  if (ret < 0)
2242  return ret;
2243  }
2244 
2245  if (hls->var_stream_map) {
2247  } else {
2248  //By default, a single variant stream with all the codec streams is created
2249  hls->var_streams = av_mallocz(sizeof(*hls->var_streams));
2250  if (!hls->var_streams)
2251  return AVERROR(ENOMEM);
2252  hls->nb_varstreams = 1;
2253 
2254  hls->var_streams[0].var_stream_idx = 0;
2255  hls->var_streams[0].nb_streams = s->nb_streams;
2256  hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
2257  hls->var_streams[0].nb_streams);
2258  if (!hls->var_streams[0].streams)
2259  return AVERROR(ENOMEM);
2260 
2261  //by default, the first available ccgroup is mapped to the variant stream
2262  if (hls->nb_ccstreams)
2263  hls->var_streams[0].ccgroup = hls->cc_streams[0].ccgroup;
2264 
2265  for (i = 0; i < s->nb_streams; i++)
2266  hls->var_streams[0].streams[i] = s->streams[i];
2267  }
2268  return 0;
2269 }
2270 
2272 {
2273  HLSContext *hls = s->priv_data;
2274  const char *dir;
2275  char *fn1= NULL, *fn2 = NULL;
2276  int ret = 0;
2277 
2278  fn1 = av_strdup(s->url);
2279  if (!fn1)
2280  return AVERROR(ENOMEM);
2281  dir = av_dirname(fn1);
2282 
2283  /**
2284  * if output file's directory has %v, variants are created in sub-directories
2285  * then master is created at the sub-directories level
2286  */
2287  if (dir && av_stristr(av_basename(dir), "%v")) {
2288  fn2 = av_strdup(dir);
2289  if (!fn2) {
2290  ret = AVERROR(ENOMEM);
2291  goto fail;
2292  }
2293  dir = av_dirname(fn2);
2294  }
2295 
2296  if (dir && strcmp(dir, "."))
2298  else
2300 
2301  if (!hls->master_m3u8_url) {
2302  ret = AVERROR(ENOMEM);
2303  goto fail;
2304  }
2305 
2306 fail:
2307  av_freep(&fn1);
2308  av_freep(&fn2);
2309 
2310  return ret;
2311 }
2312 
2314 {
2315  HLSContext *hls = s->priv_data;
2316  int ret, i, j;
2317  VariantStream *vs = NULL;
2318 
2319  for (i = 0; i < hls->nb_varstreams; i++) {
2320  vs = &hls->var_streams[i];
2321 
2322  ret = avformat_write_header(vs->avf, NULL);
2323  if (ret < 0)
2324  return ret;
2325  //av_assert0(s->nb_streams == hls->avf->nb_streams);
2326  for (j = 0; j < vs->nb_streams; j++) {
2327  AVStream *inner_st;
2328  AVStream *outer_st = vs->streams[j];
2329 
2330  if (hls->max_seg_size > 0) {
2331  if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
2332  (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
2333  av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
2334  "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
2335  outer_st->codecpar->bit_rate, hls->max_seg_size);
2336  }
2337  }
2338 
2339  if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
2340  inner_st = vs->avf->streams[j];
2341  else if (vs->vtt_avf)
2342  inner_st = vs->vtt_avf->streams[0];
2343  else {
2344  /* We have a subtitle stream, when the user does not want one */
2345  inner_st = NULL;
2346  continue;
2347  }
2348  avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
2349  if (outer_st->codecpar->codec_id == AV_CODEC_ID_HEVC &&
2350  outer_st->codecpar->codec_tag != MKTAG('h','v','c','1')) {
2351  av_log(s, AV_LOG_WARNING, "Stream HEVC is not hvc1, you should use tag:v hvc1 to set it.\n");
2352  }
2353  write_codec_attr(outer_st, vs);
2354 
2355  }
2356  /* Update the Codec Attr string for the mapped audio groups */
2357  if (vs->has_video && vs->agroup) {
2358  for (j = 0; j < hls->nb_varstreams; j++) {
2359  VariantStream *vs_agroup = &(hls->var_streams[j]);
2360  if (!vs_agroup->has_video && !vs_agroup->has_subtitle &&
2361  vs_agroup->agroup &&
2362  !av_strcasecmp(vs_agroup->agroup, vs->agroup)) {
2363  write_codec_attr(vs_agroup->streams[0], vs);
2364  }
2365  }
2366  }
2367  }
2368 
2369  return ret;
2370 }
2371 
2373 {
2374  HLSContext *hls = s->priv_data;
2376  int ret = 0;
2377 
2378  set_http_options(s, &options, hls);
2379  ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
2381  if (ret < 0)
2382  return ret;
2384  hlsenc_io_close(s, &vs->out, hls->fmp4_init_filename);
2385 
2386  return ret;
2387 }
2388 
2390 {
2391  int ret = 0;
2392  int64_t read_byte = 0;
2393  int64_t total_size = 0;
2394  char *filename = NULL;
2395  char buf[BUFSIZE];
2396  AVFormatContext *oc = vs->avf;
2397 
2398  hlsenc_io_close(s, &vs->out, vs->basename_tmp);
2399  filename = av_asprintf("%s.tmp", oc->url);
2400  ret = s->io_open(s, &vs->out, filename, AVIO_FLAG_READ, NULL);
2401  if (ret < 0) {
2402  av_free(filename);
2403  return ret;
2404  }
2405 
2406  do {
2407  memset(buf, 0, sizeof(BUFSIZE));
2408  read_byte = avio_read(vs->out, buf, BUFSIZE);
2409  avio_write(vs->out_single_file, buf, read_byte);
2410  if (read_byte > 0) {
2411  total_size += read_byte;
2412  ret = total_size;
2413  }
2414  } while (read_byte > 0);
2415 
2416  hlsenc_io_close(s, &vs->out, filename);
2417  av_free(filename);
2418 
2419  return ret;
2420 }
2422 {
2423  HLSContext *hls = s->priv_data;
2424  AVFormatContext *oc = NULL;
2425  AVStream *st = s->streams[pkt->stream_index];
2426  int64_t end_pts = 0;
2427  int is_ref_pkt = 1;
2428  int ret = 0, can_split = 1, i, j;
2429  int stream_index = 0;
2430  int range_length = 0;
2431  const char *proto = NULL;
2432  int use_temp_file = 0;
2433  VariantStream *vs = NULL;
2434  char *old_filename = NULL;
2435 
2436  for (i = 0; i < hls->nb_varstreams; i++) {
2437  vs = &hls->var_streams[i];
2438  for (j = 0; j < vs->nb_streams; j++) {
2439  if (vs->streams[j] == st) {
2441  oc = vs->vtt_avf;
2442  stream_index = 0;
2443  } else {
2444  oc = vs->avf;
2445  stream_index = j;
2446  }
2447  break;
2448  }
2449  }
2450 
2451  if (oc)
2452  break;
2453  }
2454 
2455  if (!oc) {
2456  av_log(s, AV_LOG_ERROR, "Unable to find mapping variant stream\n");
2457  return AVERROR(ENOMEM);
2458  }
2459 
2460  end_pts = hls->recording_time * vs->number;
2461 
2462  if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
2463  /* reset end_pts, hls->recording_time at end of the init hls list */
2464  int64_t init_list_dur = hls->init_time * vs->nb_entries;
2465  int64_t after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries) * hls->time;
2466  hls->recording_time = hls->time;
2467  end_pts = init_list_dur + after_init_list_dur ;
2468  }
2469 
2470  if (vs->start_pts == AV_NOPTS_VALUE) {
2471  vs->start_pts = pkt->pts;
2473  vs->start_pts_from_audio = 1;
2474  }
2476  vs->start_pts = pkt->pts;
2477  vs->start_pts_from_audio = 0;
2478  }
2479 
2480  if (vs->has_video) {
2481  can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2482  ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
2483  is_ref_pkt = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->stream_index == vs->reference_stream_index);
2484  }
2485  if (pkt->pts == AV_NOPTS_VALUE)
2486  is_ref_pkt = can_split = 0;
2487 
2488  if (is_ref_pkt) {
2489  if (vs->end_pts == AV_NOPTS_VALUE)
2490  vs->end_pts = pkt->pts;
2491  if (vs->new_start) {
2492  vs->new_start = 0;
2493  vs->duration = (double)(pkt->pts - vs->end_pts)
2494  * st->time_base.num / st->time_base.den;
2495  vs->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2496  } else {
2497  if (pkt->duration) {
2498  vs->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2499  } else {
2500  av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
2501  vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2502  }
2503  }
2504  }
2505 
2506  can_split = can_split && (pkt->pts - vs->end_pts > 0);
2507  if (vs->packets_written && can_split && av_compare_ts(pkt->pts - vs->start_pts, st->time_base,
2508  end_pts, AV_TIME_BASE_Q) >= 0) {
2509  int64_t new_start_pos;
2510  int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2511 
2512  av_write_frame(oc, NULL); /* Flush any buffered data */
2513  new_start_pos = avio_tell(oc->pb);
2514  vs->size = new_start_pos - vs->start_pos;
2515  avio_flush(oc->pb);
2516  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2517  if (!vs->init_range_length) {
2518  range_length = avio_close_dyn_buf(oc->pb, &vs->init_buffer);
2519  if (range_length <= 0)
2520  return AVERROR(EINVAL);
2521  avio_write(vs->out, vs->init_buffer, range_length);
2522  if (!hls->resend_init_file)
2523  av_freep(&vs->init_buffer);
2524  vs->init_range_length = range_length;
2525  avio_open_dyn_buf(&oc->pb);
2526  vs->packets_written = 0;
2527  vs->start_pos = range_length;
2528  if (!byterange_mode) {
2530  }
2531  }
2532  }
2533  if (!byterange_mode) {
2534  if (vs->vtt_avf) {
2535  hlsenc_io_close(s, &vs->vtt_avf->pb, vs->vtt_avf->url);
2536  }
2537  }
2538 
2539  if (hls->flags & HLS_SINGLE_FILE) {
2540  ret = flush_dynbuf(vs, &range_length);
2541  av_freep(&vs->temp_buffer);
2542  if (ret < 0) {
2543  return ret;
2544  }
2545  vs->size = range_length;
2546  if (hls->key_info_file || hls->encrypt)
2547  vs->size = append_single_file(s, vs);
2548  } else {
2549  if (oc->url[0]) {
2550  proto = avio_find_protocol_name(oc->url);
2551  use_temp_file = proto && !strcmp(proto, "file")
2552  && (hls->flags & HLS_TEMP_FILE);
2553  }
2554 
2555  if ((hls->max_seg_size > 0 && (vs->size + vs->start_pos >= hls->max_seg_size)) || !byterange_mode) {
2557  char *filename = NULL;
2558  if (hls->key_info_file || hls->encrypt) {
2559  av_dict_set(&options, "encryption_key", vs->key_string, 0);
2560  av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
2561  filename = av_asprintf("crypto:%s", oc->url);
2562  } else {
2563  filename = av_asprintf("%s", oc->url);
2564  }
2565  if (!filename) {
2567  return AVERROR(ENOMEM);
2568  }
2569 
2570  // look to rename the asset name
2571  if (use_temp_file)
2572  av_dict_set(&options, "mpegts_flags", "resend_headers", 0);
2573 
2574  set_http_options(s, &options, hls);
2575 
2576  ret = hlsenc_io_open(s, &vs->out, filename, &options);
2577  if (ret < 0) {
2579  "Failed to open file '%s'\n", filename);
2580  av_freep(&filename);
2582  return hls->ignore_io_errors ? 0 : ret;
2583  }
2584  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2585  write_styp(vs->out);
2586  }
2587  ret = flush_dynbuf(vs, &range_length);
2588  if (ret < 0) {
2589  av_freep(&filename);
2591  return ret;
2592  }
2593  ret = hlsenc_io_close(s, &vs->out, filename);
2594  if (ret < 0) {
2595  av_log(s, AV_LOG_WARNING, "upload segment failed,"
2596  " will retry with a new http session.\n");
2597  ff_format_io_close(s, &vs->out);
2598  ret = hlsenc_io_open(s, &vs->out, filename, &options);
2599  if (ret >= 0) {
2600  reflush_dynbuf(vs, &range_length);
2601  ret = hlsenc_io_close(s, &vs->out, filename);
2602  }
2603  }
2605  av_freep(&vs->temp_buffer);
2606  av_freep(&filename);
2607  }
2608 
2609  if (use_temp_file)
2610  hls_rename_temp_file(s, oc);
2611  }
2612 
2613  if (ret < 0)
2614  return ret;
2615 
2616  old_filename = av_strdup(oc->url);
2617  if (!old_filename) {
2618  return AVERROR(ENOMEM);
2619  }
2620 
2621  if (vs->start_pos || hls->segment_type != SEGMENT_TYPE_FMP4) {
2622  double cur_duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2623  ret = hls_append_segment(s, hls, vs, cur_duration, vs->start_pos, vs->size);
2624  vs->end_pts = pkt->pts;
2625  vs->duration = 0;
2626  if (ret < 0) {
2627  av_freep(&old_filename);
2628  return ret;
2629  }
2630  }
2631 
2632  // if we're building a VOD playlist, skip writing the manifest multiple times, and just wait until the end
2633  if (hls->pl_type != PLAYLIST_TYPE_VOD) {
2634  if ((ret = hls_window(s, 0, vs)) < 0) {
2635  av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
2636  ff_format_io_close(s, &vs->out);
2637  if ((ret = hls_window(s, 0, vs)) < 0) {
2638  av_freep(&old_filename);
2639  return ret;
2640  }
2641  }
2642  }
2643 
2644  if (hls->resend_init_file && hls->segment_type == SEGMENT_TYPE_FMP4) {
2645  ret = hls_init_file_resend(s, vs);
2646  if (ret < 0) {
2647  av_freep(&old_filename);
2648  return ret;
2649  }
2650  }
2651 
2652  if (hls->flags & HLS_SINGLE_FILE) {
2653  vs->start_pos += vs->size;
2654  if (hls->key_info_file || hls->encrypt)
2655  ret = hls_start(s, vs);
2656  } else if (hls->max_seg_size > 0) {
2657  if (vs->size + vs->start_pos >= hls->max_seg_size) {
2658  vs->sequence++;
2659  sls_flag_file_rename(hls, vs, old_filename);
2660  ret = hls_start(s, vs);
2661  vs->start_pos = 0;
2662  /* When split segment by byte, the duration is short than hls_time,
2663  * so it is not enough one segment duration as hls_time, */
2664  } else {
2665  vs->start_pos = new_start_pos;
2666  }
2667  } else {
2668  vs->start_pos = new_start_pos;
2669  sls_flag_file_rename(hls, vs, old_filename);
2670  ret = hls_start(s, vs);
2671  }
2672  vs->number++;
2673  av_freep(&old_filename);
2674 
2675  if (ret < 0) {
2676  return ret;
2677  }
2678 
2679  }
2680 
2681  vs->packets_written++;
2682  if (oc->pb) {
2683  ret = ff_write_chained(oc, stream_index, pkt, s, 0);
2684  vs->video_keyframe_size += pkt->size;
2686  vs->video_keyframe_size = avio_tell(oc->pb);
2687  } else {
2688  vs->video_keyframe_pos = avio_tell(vs->out);
2689  }
2690  if (hls->ignore_io_errors)
2691  ret = 0;
2692  }
2693 
2694  return ret;
2695 }
2696 
2698 {
2699  HLSContext *hls = s->priv_data;
2700  int i = 0;
2701  VariantStream *vs = NULL;
2702 
2703  for (i = 0; i < hls->nb_varstreams; i++) {
2704  vs = &hls->var_streams[i];
2705 
2706  av_freep(&vs->basename);
2709  av_freep(&vs->vtt_basename);
2710  av_freep(&vs->vtt_m3u8_name);
2711 
2714  if (hls->resend_init_file)
2715  av_freep(&vs->init_buffer);
2718  av_freep(&vs->m3u8_name);
2719  av_freep(&vs->streams);
2720  }
2721 
2722  ff_format_io_close(s, &hls->m3u8_out);
2724  av_freep(&hls->key_basename);
2725  av_freep(&hls->var_streams);
2726  av_freep(&hls->cc_streams);
2727  av_freep(&hls->master_m3u8_url);
2728 }
2729 
2731 {
2732  HLSContext *hls = s->priv_data;
2733  AVFormatContext *oc = NULL;
2734  AVFormatContext *vtt_oc = NULL;
2735  char *old_filename = NULL;
2736  const char *proto = NULL;
2737  int use_temp_file = 0;
2738  int i;
2739  int ret = 0;
2740  VariantStream *vs = NULL;
2742  int range_length, byterange_mode;
2743 
2744  for (i = 0; i < hls->nb_varstreams; i++) {
2745  char *filename = NULL;
2746  vs = &hls->var_streams[i];
2747  oc = vs->avf;
2748  vtt_oc = vs->vtt_avf;
2749  old_filename = av_strdup(oc->url);
2750  use_temp_file = 0;
2751 
2752  if (!old_filename) {
2753  return AVERROR(ENOMEM);
2754  }
2755  if (hls->key_info_file || hls->encrypt) {
2756  av_dict_set(&options, "encryption_key", vs->key_string, 0);
2757  av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
2758  filename = av_asprintf("crypto:%s", oc->url);
2759  } else {
2760  filename = av_asprintf("%s", oc->url);
2761  }
2762  if (!filename) {
2763  av_freep(&old_filename);
2764  return AVERROR(ENOMEM);
2765  }
2766 
2767  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2768  int range_length = 0;
2769  if (!vs->init_range_length) {
2770  uint8_t *buffer = NULL;
2771  av_write_frame(oc, NULL); /* Flush any buffered data */
2772 
2773  range_length = avio_close_dyn_buf(oc->pb, &buffer);
2774  avio_write(vs->out, buffer, range_length);
2775  av_freep(&buffer);
2776  vs->init_range_length = range_length;
2777  avio_open_dyn_buf(&oc->pb);
2778  vs->packets_written = 0;
2779  vs->start_pos = range_length;
2780  byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2781  if (!byterange_mode) {
2782  ff_format_io_close(s, &vs->out);
2784  }
2785  }
2786  }
2787  if (!(hls->flags & HLS_SINGLE_FILE)) {
2788  set_http_options(s, &options, hls);
2789  ret = hlsenc_io_open(s, &vs->out, filename, &options);
2790  if (ret < 0) {
2791  av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", oc->url);
2792  goto failed;
2793  }
2794  if (hls->segment_type == SEGMENT_TYPE_FMP4)
2795  write_styp(vs->out);
2796  }
2797  ret = flush_dynbuf(vs, &range_length);
2798  if (ret < 0)
2799  goto failed;
2800 
2801  vs->size = range_length;
2802  ret = hlsenc_io_close(s, &vs->out, filename);
2803  if (ret < 0) {
2804  av_log(s, AV_LOG_WARNING, "upload segment failed, will retry with a new http session.\n");
2805  ff_format_io_close(s, &vs->out);
2806  ret = hlsenc_io_open(s, &vs->out, filename, &options);
2807  if (ret < 0) {
2808  av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", oc->url);
2809  goto failed;
2810  }
2811  reflush_dynbuf(vs, &range_length);
2812  ret = hlsenc_io_close(s, &vs->out, filename);
2813  if (ret < 0)
2814  av_log(s, AV_LOG_WARNING, "Failed to upload file '%s' at the end.\n", oc->url);
2815  }
2816  if (hls->flags & HLS_SINGLE_FILE) {
2817  if (hls->key_info_file || hls->encrypt) {
2818  vs->size = append_single_file(s, vs);
2819  }
2821  }
2822 failed:
2823  av_freep(&vs->temp_buffer);
2825  av_freep(&filename);
2826  av_write_trailer(oc);
2827  if (oc->url[0]) {
2828  proto = avio_find_protocol_name(oc->url);
2829  use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
2830  }
2831 
2832  // rename that segment from .tmp to the real one
2833  if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
2834  hls_rename_temp_file(s, oc);
2835  av_freep(&old_filename);
2836  old_filename = av_strdup(oc->url);
2837 
2838  if (!old_filename) {
2839  return AVERROR(ENOMEM);
2840  }
2841  }
2842 
2843  /* after av_write_trailer, then duration + 1 duration per packet */
2844  hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
2845 
2846  sls_flag_file_rename(hls, vs, old_filename);
2847 
2848  if (vtt_oc) {
2849  if (vtt_oc->pb)
2850  av_write_trailer(vtt_oc);
2851  vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
2852  ff_format_io_close(s, &vtt_oc->pb);
2853  }
2854  ret = hls_window(s, 1, vs);
2855  if (ret < 0) {
2856  av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
2857  ff_format_io_close(s, &vs->out);
2858  hls_window(s, 1, vs);
2859  }
2860  ffio_free_dyn_buf(&oc->pb);
2861 
2862  av_free(old_filename);
2863  }
2864 
2865  return 0;
2866 }
2867 
2868 
2870 {
2871  int ret = 0;
2872  int i = 0;
2873  int j = 0;
2874  HLSContext *hls = s->priv_data;
2875  const char *pattern;
2876  VariantStream *vs = NULL;
2877  const char *vtt_pattern = hls->flags & HLS_SINGLE_FILE ? ".vtt" : "%d.vtt";
2878  char *p = NULL;
2879  int http_base_proto = ff_is_http_proto(s->url);
2880  int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
2881  double initial_program_date_time = av_gettime() / 1000000.0;
2882 
2883  if (hls->use_localtime) {
2885  } else {
2886  pattern = hls->segment_type == SEGMENT_TYPE_FMP4 ? "%d.m4s" : "%d.ts";
2887  if (hls->flags & HLS_SINGLE_FILE)
2888  pattern += 2;
2889  }
2890 
2891  hls->has_default_key = 0;
2892  hls->has_video_m3u8 = 0;
2894  if (ret < 0) {
2895  av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
2896  ret);
2897  return ret;
2898  }
2899 
2900  if (!hls->method && http_base_proto) {
2901  av_log(hls, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
2902  }
2903 
2904  ret = validate_name(hls->nb_varstreams, s->url);
2905  if (ret < 0)
2906  return ret;
2907 
2908  if (hls->segment_filename) {
2909  ret = validate_name(hls->nb_varstreams, hls->segment_filename);
2910  if (ret < 0)
2911  return ret;
2912  }
2913 
2914  if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
2916  if (ret < 0)
2917  return ret;
2918  }
2919 
2920  if (hls->subtitle_filename) {
2921  ret = validate_name(hls->nb_varstreams, hls->subtitle_filename);
2922  if (ret < 0)
2923  return ret;
2924  }
2925 
2926  if (hls->master_pl_name) {
2927  ret = update_master_pl_info(s);
2928  if (ret < 0) {
2929  av_log(s, AV_LOG_ERROR, "Master stream info update failed with status %x\n",
2930  ret);
2931  return ret;
2932  }
2933  }
2934 
2938  time_t t = time(NULL);
2940  hls->start_sequence = av_gettime();
2942  hls->start_sequence = (int64_t)t;
2944  char b[15];
2945  struct tm *p, tmbuf;
2946  if (!(p = localtime_r(&t, &tmbuf)))
2947  return AVERROR(errno);
2948  if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
2949  return AVERROR(ENOMEM);
2950  hls->start_sequence = strtoll(b, NULL, 10);
2951  }
2952  av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
2953  }
2954 
2955  hls->recording_time = hls->init_time ? hls->init_time : hls->time;
2956 
2957  if (hls->flags & HLS_SPLIT_BY_TIME && hls->flags & HLS_INDEPENDENT_SEGMENTS) {
2958  // Independent segments cannot be guaranteed when splitting by time
2961  "'split_by_time' and 'independent_segments' cannot be "
2962  "enabled together. Disabling 'independent_segments' flag\n");
2963  }
2964 
2965  for (i = 0; i < hls->nb_varstreams; i++) {
2966  vs = &hls->var_streams[i];
2967 
2968  ret = format_name(s->url, &vs->m3u8_name, i, vs->varname);
2969  if (ret < 0)
2970  return ret;
2971 
2972  vs->sequence = hls->start_sequence;
2973  vs->start_pts = AV_NOPTS_VALUE;
2974  vs->end_pts = AV_NOPTS_VALUE;
2975  vs->current_segment_final_filename_fmt[0] = '\0';
2976  vs->initial_prog_date_time = initial_program_date_time;
2977 
2978  for (j = 0; j < vs->nb_streams; j++) {
2980  /* Get one video stream to reference for split segments
2981  * so use the first video stream index. */
2982  if ((vs->has_video == 1) && (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) {
2983  vs->reference_stream_index = vs->streams[j]->index;
2984  }
2986  }
2987 
2988  if (vs->has_video > 1)
2989  av_log(s, AV_LOG_WARNING, "More than a single video stream present, expect issues decoding it.\n");
2990  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2991  vs->oformat = av_guess_format("mp4", NULL, NULL);
2992  } else {
2993  vs->oformat = av_guess_format("mpegts", NULL, NULL);
2994  }
2995  if (!vs->oformat)
2996  return AVERROR_MUXER_NOT_FOUND;
2997 
2998  if (hls->segment_filename) {
2999  ret = format_name(hls->segment_filename, &vs->basename, i, vs->varname);
3000  if (ret < 0)
3001  return ret;
3002  } else {
3003  p = strrchr(vs->m3u8_name, '.');
3004  if (p)
3005  *p = '\0';
3006 
3007  vs->basename = av_asprintf("%s%s", vs->m3u8_name, pattern);
3008  if (!vs->basename)
3009  return AVERROR(ENOMEM);
3010 
3011  if (p)
3012  *p = '.';
3013  }
3014 
3015  if (hls->segment_type == SEGMENT_TYPE_FMP4) {
3016  if (hls->nb_varstreams > 1)
3017  fmp4_init_filename_len += strlen(POSTFIX_PATTERN);
3018  if (hls->flags & HLS_SINGLE_FILE) {
3020  if (!vs->fmp4_init_filename)
3021  return AVERROR(ENOMEM);
3022  } else {
3023  vs->fmp4_init_filename = av_malloc(fmp4_init_filename_len);
3024  if (!vs->fmp4_init_filename)
3025  return AVERROR(ENOMEM);
3027  fmp4_init_filename_len);
3028  if (hls->nb_varstreams > 1) {
3029  if (av_stristr(vs->fmp4_init_filename, "%v")) {
3031  ret = format_name(hls->fmp4_init_filename,
3032  &vs->fmp4_init_filename, i, vs->varname);
3033  } else {
3034  ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
3035  }
3036  if (ret < 0)
3037  return ret;
3038  }
3039 
3040  if (hls->use_localtime) {
3041  int r;
3042  char *expanded = NULL;
3043 
3044  r = strftime_expand(vs->fmp4_init_filename, &expanded);
3045  if (r < 0) {
3046  av_log(s, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
3047  return r;
3048  }
3050  vs->fmp4_init_filename = expanded;
3051  }
3052 
3053  p = strrchr(vs->m3u8_name, '/');
3054  if (p) {
3055  char tmp = *(++p);
3056  *p = '\0';
3057  vs->base_output_dirname = av_asprintf("%s%s", vs->m3u8_name,
3058  vs->fmp4_init_filename);
3059  *p = tmp;
3060  } else {
3062  }
3063  if (!vs->base_output_dirname)
3064  return AVERROR(ENOMEM);
3065  }
3066  }
3067 
3069  if (ret < 0)
3070  return ret;
3071 
3072  if (vs->has_subtitle) {
3073  vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
3074  if (!vs->vtt_oformat)
3075  return AVERROR_MUXER_NOT_FOUND;
3076 
3077  p = strrchr(vs->m3u8_name, '.');
3078  if (p)
3079  *p = '\0';
3080 
3081  vs->vtt_basename = av_asprintf("%s%s", vs->m3u8_name, vtt_pattern);
3082  if (!vs->vtt_basename)
3083  return AVERROR(ENOMEM);
3084 
3085  if (hls->subtitle_filename) {
3086  ret = format_name(hls->subtitle_filename, &vs->vtt_m3u8_name, i, vs->varname);
3087  if (ret < 0)
3088  return ret;
3089  } else {
3090  vs->vtt_m3u8_name = av_asprintf("%s_vtt.m3u8", vs->m3u8_name);
3091  if (!vs->vtt_m3u8_name)
3092  return AVERROR(ENOMEM);
3093  }
3094  if (p)
3095  *p = '.';
3096  }
3097 
3098  if ((ret = hls_mux_init(s, vs)) < 0)
3099  return ret;
3100 
3101  if (hls->flags & HLS_APPEND_LIST) {
3102  parse_playlist(s, vs->m3u8_name, vs);
3103  vs->discontinuity = 1;
3104  if (hls->init_time > 0) {
3105  av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
3106  " hls_init_time value will have no effect\n");
3107  hls->init_time = 0;
3108  hls->recording_time = hls->time;
3109  }
3110  }
3111 
3112  if ((ret = hls_start(s, vs)) < 0)
3113  return ret;
3114  vs->number++;
3115  }
3116 
3117  return ret;
3118 }
3119 
3120 #define OFFSET(x) offsetof(HLSContext, x)
3121 #define E AV_OPT_FLAG_ENCODING_PARAM
3122 static const AVOption options[] = {
3123  {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
3124  {"hls_time", "set segment length", OFFSET(time), AV_OPT_TYPE_DURATION, {.i64 = 2000000}, 0, INT64_MAX, E},
3125  {"hls_init_time", "set segment length at init list", OFFSET(init_time), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E},
3126  {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
3127  {"hls_delete_threshold", "set number of unreferenced segments to keep before deleting", OFFSET(hls_delete_threshold), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, E},
3128  {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, E},
3129  {"hls_vtt_options","set hls vtt list of options for the container format used for hls", OFFSET(vtt_format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3130 #if FF_API_HLS_WRAP
3131  {"hls_wrap", "set number after which the index wraps (will be deprecated)", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
3132 #endif
3133  {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
3134  {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3135  {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3136  {"hls_segment_size", "maximum size per segment file, (in bytes)", OFFSET(max_seg_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
3137  {"hls_key_info_file", "file with key URI and key file path", OFFSET(key_info_file), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3138  {"hls_enc", "enable AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
3139  {"hls_enc_key", "hex-coded 16 byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_STRING, .flags = E},
3140  {"hls_enc_key_url", "url to access the key to decrypt the segments", OFFSET(key_url), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3141  {"hls_enc_iv", "hex-coded 16 byte initialization vector", OFFSET(iv), AV_OPT_TYPE_STRING, .flags = E},
3142  {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3143  {"hls_segment_type", "set hls segment files type", OFFSET(segment_type), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, SEGMENT_TYPE_FMP4, E, "segment_type"},
3144  {"mpegts", "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX, E, "segment_type"},
3145  {"fmp4", "make segment file to fragment mp4 files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_FMP4 }, 0, UINT_MAX, E, "segment_type"},
3146  {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename), AV_OPT_TYPE_STRING, {.str = "init.mp4"}, 0, 0, E},
3147  {"hls_fmp4_init_resend", "resend fragment mp4 init file after refresh m3u8 every time", OFFSET(resend_init_file), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3148  {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
3149  {"single_file", "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX, E, "flags"},
3150  {"temp_file", "write segment and playlist to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX, E, "flags"},
3151  {"delete_segments", "delete segment files that are no longer part of the playlist", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DELETE_SEGMENTS }, 0, UINT_MAX, E, "flags"},
3152  {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, "flags"},
3153  {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, "flags"},
3154  {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, "flags"},
3155  {"split_by_time", "split the hls segment by time which user set by hls_time", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SPLIT_BY_TIME }, 0, UINT_MAX, E, "flags"},
3156  {"append_list", "append the new segments into old hls segment list", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_APPEND_LIST }, 0, UINT_MAX, E, "flags"},
3157  {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX, E, "flags"},
3158  {"second_level_segment_index", "include segment index in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_INDEX }, 0, UINT_MAX, E, "flags"},
3159  {"second_level_segment_duration", "include segment duration in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_DURATION }, 0, UINT_MAX, E, "flags"},
3160  {"second_level_segment_size", "include segment size in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_SIZE }, 0, UINT_MAX, E, "flags"},
3161  {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX, E, "flags"},
3162  {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, "flags"},
3163  {"iframes_only", "add EXT-X-I-FRAMES-ONLY, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_I_FRAMES_ONLY }, 0, UINT_MAX, E, "flags"},
3164 #if FF_API_HLS_USE_LOCALTIME
3165  {"use_localtime", "set filename expansion with strftime at segment creation(will be deprecated)", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3166 #endif
3167  {"strftime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3168 #if FF_API_HLS_USE_LOCALTIME
3169  {"use_localtime_mkdir", "create last directory component in strftime-generated filename(will be deprecated)", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3170 #endif
3171  {"strftime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3172  {"hls_playlist_type", "set the HLS playlist type", OFFSET(pl_type), AV_OPT_TYPE_INT, {.i64 = PLAYLIST_TYPE_NONE }, 0, PLAYLIST_TYPE_NB-1, E, "pl_type" },
3173  {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
3174  {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
3175  {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3176  {"hls_start_number_source", "set source of first number in sequence", OFFSET(start_sequence_source_type), AV_OPT_TYPE_INT, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, 0, HLS_START_SEQUENCE_LAST-1, E, "start_sequence_source_type" },
3177  {"generic", "start_number value (default)", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
3178  {"epoch", "seconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
3179  {"epoch_us", "microseconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
3180  {"datetime", "current datetime as YYYYMMDDhhmmss", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_FORMATTED_DATETIME }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
3181  {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3182  {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3183  {"cc_stream_map", "Closed captions stream map string", OFFSET(cc_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3184  {"master_pl_name", "Create HLS master playlist with this name", OFFSET(master_pl_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3185  {"master_pl_publish_rate", "Publish master play list every after this many segment intervals", OFFSET(master_publish_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT_MAX, E},
3186  {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3187  {"timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
3188  {"ignore_io_errors", "Ignore IO errors for stable long-duration runs with network output", OFFSET(ignore_io_errors), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
3189  {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
3190  { NULL },
3191 };
3192 
3193 static const AVClass hls_class = {
3194  .class_name = "hls muxer",
3195  .item_name = av_default_item_name,
3196  .option = options,
3197  .version = LIBAVUTIL_VERSION_INT,
3198 };
3199 
3200 
3202  .name = "hls",
3203  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
3204  .extensions = "m3u8",
3205  .priv_data_size = sizeof(HLSContext),
3206  .audio_codec = AV_CODEC_ID_AAC,
3207  .video_codec = AV_CODEC_ID_H264,
3208  .subtitle_codec = AV_CODEC_ID_WEBVTT,
3210  .init = hls_init,
3214  .deinit = hls_deinit,
3215  .priv_class = &hls_class,
3216 };
#define wrap(func)
Definition: neontest.h:65
static double val(void *priv, double ch)
Definition: aeval.c:76
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(const int16_t *) pi >> 8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(const int32_t *) pi >> 24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(const float *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(const float *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(const float *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(const double *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(const double *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(const double *) pi *(1U<< 31)))) #define SET_CONV_FUNC_GROUP(ofmt, ifmt) static void set_generic_function(AudioConvert *ac) { } void ff_audio_convert_free(AudioConvert **ac) { if(! *ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);} AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt, int channels, int sample_rate, int apply_map) { AudioConvert *ac;int in_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) return NULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method !=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt) > 2) { ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc) { av_free(ac);return NULL;} return ac;} in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar) { ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar ? ac->channels :1;} else if(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;else ac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);return ac;} int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in) { int use_generic=1;int len=in->nb_samples;int p;if(ac->dc) { av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));return ff_convert_dither(ac-> in
uint8_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
uint8_t * ff_nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len, uint32_t *dst_len, int header_len)
Definition: avc.c:269
#define FF_PROFILE_UNKNOWN
Definition: avcodec.h:1859
#define FF_LEVEL_UNKNOWN
Definition: avcodec.h:1985
Main libavformat public API header.
int avformat_alloc_output_context2(AVFormatContext **ctx, ff_const59 AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
Definition: mux.c:136
#define AVFMT_NODIMENSIONS
Format does not need width/height.
Definition: avformat.h:466
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:471
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:458
#define ff_const59
The ff_const59 define is not part of the public API and will be removed without further warning.
Definition: avformat.h:533
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:461
int ffurl_shutdown(URLContext *h, int flags)
Signal the URLContext that we are done reading or writing the stream.
Definition: avio.c:654
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition: avio.c:470
int ff_rename(const char *url_src, const char *url_dst, void *logctx)
Wrap avpriv_io_move and log if error happens.
Definition: avio.c:668
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:253
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:383
#define AVIO_FLAG_READ
read-only
Definition: avio.h:674
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:364
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:675
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
Writes a formatted string to the context.
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1427
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:633
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:225
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:1172
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:245
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1382
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1457
static av_always_inline void ffio_wfourcc(AVIOContext *pb, const uint8_t *s)
Definition: avio_internal.h:58
int ffio_open_whitelist(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist)
Definition: aviobuf.c:1145
URLContext * ffio_geturlcontext(AVIOContext *s)
Return the URLContext associated with the AVIOContext.
Definition: aviobuf.c:979
int ff_get_chomp_line(AVIOContext *s, char *buf, int maxlen)
Same as ff_get_line but strip the white-space characters in the text tail.
Definition: aviobuf.c:806
int ff_get_line(AVIOContext *s, char *buf, int maxlen)
Read a whole line of text from AVIOContext.
Definition: aviobuf.c:789
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:31
char * av_asprintf(const char *fmt,...)
Definition: avstring.c:113
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:94
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
void av_bprint_append_data(AVBPrint *buf, const char *data, unsigned size)
Append data to a print buffer.
Definition: bprint.c:158
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition: bprint.c:227
#define AV_BPRINT_SIZE_UNLIMITED
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition: bprint.h:185
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define s(width, name)
Definition: cbs_vp9.c:257
#define fail()
Definition: checkasm.h:133
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: codec_par.c:72
#define fn(a)
#define fn2(a, b, c)
#define MKTAG(a, b, c, d)
Definition: common.h:478
#define FFMAX(a, b)
Definition: common.h:103
#define HAVE_LIBC_MSVCRT
Definition: config.h:272
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:730
static int nb_streams
Definition: ffprobe.c:283
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:346
@ AV_OPT_TYPE_CONST
Definition: opt.h:234
@ AV_OPT_TYPE_DURATION
Definition: opt.h:239
@ AV_OPT_TYPE_FLAGS
Definition: opt.h:224
@ AV_OPT_TYPE_INT64
Definition: opt.h:226
@ AV_OPT_TYPE_INT
Definition: opt.h:225
@ AV_OPT_TYPE_DICT
Definition: opt.h:232
@ AV_OPT_TYPE_BOOL
Definition: opt.h:242
@ AV_OPT_TYPE_STRING
Definition: opt.h:229
@ AV_CODEC_ID_EAC3
Definition: codec_id.h:464
@ AV_CODEC_ID_H264
Definition: codec_id.h:76
@ AV_CODEC_ID_WEBVTT
Definition: codec_id.h:542
@ AV_CODEC_ID_MP2
Definition: codec_id.h:424
@ AV_CODEC_ID_HEVC
Definition: codec_id.h:223
@ AV_CODEC_ID_AAC
Definition: codec_id.h:426
@ AV_CODEC_ID_AC3
Definition: codec_id.h:427
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: codec_id.h:425
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
@ AV_PKT_DATA_CPB_PROPERTIES
This side data corresponds to the AVCPBProperties struct.
Definition: packet.h:145
uint8_t * av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, size_t *size)
Get side information from stream.
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4436
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4509
av_warn_unused_result int avformat_init_output(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and initialize the codec, but do not write the header.
Definition: mux.c:486
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:506
ff_const59 AVOutputFormat * av_guess_format(const char *short_name, const char *filename, const char *mime_type)
Return the output format in the list of registered output formats which best matches the provided par...
Definition: format.c:51
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:1274
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:1212
unsigned int av_codec_get_tag(const struct AVCodecTag *const *tags, enum AVCodecID id)
Get the codec tag for the given codec id id.
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition: dict.c:203
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:217
#define AV_DICT_APPEND
If the entry already exists, append to it.
Definition: dict.h:77
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:76
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition: dict.c:35
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set that converts the value to a string and stores it.
Definition: dict.c:147
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:60
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
Definition: mathematics.c:147
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:253
AVMediaType
Definition: avutil.h:199
#define av_fourcc2str(fourcc)
Definition: avutil.h:348
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition: avstring.c:93
const char * av_basename(const char *path)
Thread safe basename.
Definition: avstring.c:260
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition: avstring.c:186
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition: avstring.c:56
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:215
static av_const int av_isdigit(int c)
Locale-independent conversion of ASCII isdigit.
Definition: avstring.h:211
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:34
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
char * av_append_path_component(const char *path, const char *component)
Append path component to the existing path.
Definition: avstring.c:304
const char * av_dirname(char *path)
Thread safe dirname.
Definition: avstring.c:283
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition: avstring.c:45
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition: avstring.c:225
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:465
int index
Definition: gxfenc.c:89
static int sls_flag_check_duration_size_index(HLSContext *hls)
Definition: hlsenc.c:1014
#define E
Definition: hlsenc.c:3121
static int update_variant_stream_info(AVFormatContext *s)
Definition: hlsenc.c:2233
static int64_t get_stream_bit_rate(AVStream *stream)
Definition: hlsenc.c:1362
static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls, VariantStream *vs, HLSSegment *en, double duration, int64_t pos, int64_t size)
Definition: hlsenc.c:974
static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
Definition: hlsenc.c:328
static int hls_init(AVFormatContext *s)
Definition: hlsenc.c:2869
static int create_master_playlist(AVFormatContext *s, VariantStream *const input_vs)
Definition: hlsenc.c:1378
static const AVOption options[]
Definition: hlsenc.c:3122
static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
Definition: hlsenc.c:1544
static HLSSegment * find_segment_by_filename(HLSSegment *segment, const char *filename)
Definition: hlsenc.c:964
SegmentType
Definition: hlsenc.c:113
@ SEGMENT_TYPE_FMP4
Definition: hlsenc.c:115
@ SEGMENT_TYPE_MPEGTS
Definition: hlsenc.c:114
AVOutputFormat ff_hls_muxer
Definition: hlsenc.c:3201
static int validate_name(int nb_vs, const char *fn)
Definition: hlsenc.c:1915
#define KEYSIZE
Definition: hlsenc.c:70
static int get_nth_codec_stream_index(AVFormatContext *s, enum AVMediaType codec_type, int64_t stream_id)
Definition: hlsenc.c:1995
static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
Definition: hlsenc.c:1327
static int hls_delete_file(HLSContext *hls, AVFormatContext *avf, const char *path, const char *proto)
Definition: hlsenc.c:572
static int parse_variant_stream_mapstring(AVFormatContext *s)
Definition: hlsenc.c:2013
static int append_postfix(char *name, int name_buf_len, int i)
Definition: hlsenc.c:1896
static void hls_free_segments(HLSSegment *p)
Definition: hlsenc.c:1316
static int hls_write_header(AVFormatContext *s)
Definition: hlsenc.c:2313
static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, VariantStream *vs, double duration, int64_t pos, int64_t size)
Definition: hlsenc.c:1112
static int format_name(const char *buf, char **s, int index, const char *varname)
Definition: hlsenc.c:1949
static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
Definition: hlsenc.c:481
static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
Definition: hlsenc.c:441
static void reflush_dynbuf(VariantStream *vs, int *range_length)
Definition: hlsenc.c:560
static int do_encrypt(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:717
static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
Definition: hlsenc.c:1064
static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
Definition: hlsenc.c:307
static int hls_init_file_resend(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:2372
static int64_t append_single_file(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:2389
static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename)
Definition: hlsenc.c:1057
static int strftime_expand(const char *fmt, char **dest)
Definition: hlsenc.c:263
static int hls_write_trailer(struct AVFormatContext *s)
Definition: hlsenc.c:2730
static void hls_deinit(AVFormatContext *s)
Definition: hlsenc.c:2697
StartSequenceSourceType
Definition: hlsenc.c:57
@ HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH
Definition: hlsenc.c:61
@ HLS_START_SEQUENCE_AS_FORMATTED_DATETIME
Definition: hlsenc.c:60
@ HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH
Definition: hlsenc.c:59
@ HLS_START_SEQUENCE_LAST
Definition: hlsenc.c:62
@ HLS_START_SEQUENCE_AS_START_NUMBER
Definition: hlsenc.c:58
static int flush_dynbuf(VariantStream *vs, int *range_length)
Definition: hlsenc.c:539
static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
Definition: hlsenc.c:1880
static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
Definition: hlsenc.c:1205
#define HLS_MICROSECOND_UNIT
Definition: hlsenc.c:72
#define POSTFIX_PATTERN
Definition: hlsenc.c:74
static int hls_start(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:1683
static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename, AVDictionary **options)
Definition: hlsenc.c:286
static void write_styp(AVIOContext *pb)
Definition: hlsenc.c:529
static int hls_encryption_start(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:791
static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hlsenc.c:2421
static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
Definition: hlsenc.c:850
static int parse_cc_stream_mapstring(AVFormatContext *s)
Definition: hlsenc.c:2156
#define OFFSET(x)
Definition: hlsenc.c:3120
static const AVClass hls_class
Definition: hlsenc.c:3193
static int randomize(uint8_t *buf, int len)
Definition: hlsenc.c:703
HLSFlags
Definition: hlsenc.c:94
@ HLS_OMIT_ENDLIST
Definition: hlsenc.c:100
@ HLS_PERIODIC_REKEY
Definition: hlsenc.c:108
@ HLS_SINGLE_FILE
Definition: hlsenc.c:96
@ HLS_DELETE_SEGMENTS
Definition: hlsenc.c:97
@ HLS_APPEND_LIST
Definition: hlsenc.c:102
@ HLS_TEMP_FILE
Definition: hlsenc.c:107
@ HLS_SECOND_LEVEL_SEGMENT_INDEX
Definition: hlsenc.c:104
@ HLS_PROGRAM_DATE_TIME
Definition: hlsenc.c:103
@ HLS_ROUND_DURATIONS
Definition: hlsenc.c:98
@ HLS_SPLIT_BY_TIME
Definition: hlsenc.c:101
@ HLS_DISCONT_START
Definition: hlsenc.c:99
@ HLS_INDEPENDENT_SEGMENTS
Definition: hlsenc.c:109
@ HLS_SECOND_LEVEL_SEGMENT_DURATION
Definition: hlsenc.c:105
@ HLS_SECOND_LEVEL_SEGMENT_SIZE
Definition: hlsenc.c:106
@ HLS_I_FRAMES_ONLY
Definition: hlsenc.c:110
CodecAttributeStatus
Definition: hlsenc.c:65
@ CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN
Definition: hlsenc.c:67
@ CODEC_ATTRIBUTE_WRITTEN
Definition: hlsenc.c:66
#define BUFSIZE
Definition: hlsenc.c:73
static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls, VariantStream *vs)
Definition: hlsenc.c:592
static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
Definition: hlsenc.c:1037
static const char * get_relative_url(const char *master_url, const char *media_url)
Definition: hlsenc.c:1342
static int update_master_pl_info(AVFormatContext *s)
Definition: hlsenc.c:2271
#define SEPARATOR
Definition: hlsenc.c:569
#define LINE_BUFFER_SIZE
Definition: hlsenc.c:71
static void write_codec_attr(AVStream *st, VariantStream *vs)
Definition: hlsenc.c:347
void ff_hls_write_playlist_version(AVIOContext *out, int version)
Definition: hlsplaylist.c:31
void ff_hls_write_playlist_header(AVIOContext *out, int version, int allowcache, int target_duration, int64_t sequence, uint32_t playlist_type, int iframe_mode)
Definition: hlsplaylist.c:98
int ff_hls_write_file_entry(AVIOContext *out, int insert_discont, int byterange_mode, double duration, int round_duration, int64_t size, int64_t pos, const char *baseurl, const char *filename, double *prog_date_time, int64_t video_keyframe_size, int64_t video_keyframe_pos, int iframe_mode)
Definition: hlsplaylist.c:132
void ff_hls_write_init_file(AVIOContext *out, const char *filename, int byterange_mode, int64_t size, int64_t pos)
Definition: hlsplaylist.c:122
void ff_hls_write_subtitle_rendition(AVIOContext *out, const char *sgroup, const char *filename, const char *language, int name_id, int is_default)
Definition: hlsplaylist.c:54
void ff_hls_write_audio_rendition(AVIOContext *out, const char *agroup, const char *filename, const char *language, int name_id, int is_default)
Definition: hlsplaylist.c:39
void ff_hls_write_stream_info(AVStream *st, AVIOContext *out, int bandwidth, const char *filename, const char *agroup, const char *codecs, const char *ccgroup, const char *sgroup)
Definition: hlsplaylist.c:69
void ff_hls_write_end_list(AVIOContext *out)
Definition: hlsplaylist.c:189
@ PLAYLIST_TYPE_VOD
Definition: hlsplaylist.h:35
@ PLAYLIST_TYPE_NB
Definition: hlsplaylist.h:36
@ PLAYLIST_TYPE_NONE
Definition: hlsplaylist.h:33
@ PLAYLIST_TYPE_EVENT
Definition: hlsplaylist.h:34
int ff_http_get_shutdown_status(URLContext *h)
Get the HTTP shutdown response status, be used after http_shutdown.
Definition: http.c:376
int ff_http_do_new_request(URLContext *h, const char *uri)
Send a new HTTP request, reusing the old connection.
Definition: http.c:392
const char * key
int i
Definition: input.c:407
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
int ff_is_http_proto(char *filename)
Utility function to check if the file uses http or https protocol.
Definition: utils.c:5699
int ff_mkdir_p(const char *path)
Automatically create sub-directories.
Definition: utils.c:4862
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)
Write a packet to another muxer than the one the user originally intended.
Definition: mux.c:1328
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition: utils.c:5862
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Definition: utils.c:4896
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4945
#define MAX_URL_SIZE
Definition: internal.h:30
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5692
#define FF_API_HLS_WRAP
Definition: version.h:71
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
static av_always_inline av_const double round(double x)
Definition: libm.h:444
const char data[16]
Definition: mxf.c:142
AVOptions.
miscellaneous OS support macros and functions.
misc parsing utilities
const char * name
Definition: qsvenc.c:46
mfxU16 profile
Definition: qsvenc.c:45
enum AVMediaType codec_type
Definition: rtp.c:37
static const uint8_t start_sequence[]
Definition: rtpdec_h264.c:65
static char buffer[20]
Definition: seek.c:32
#define snprintf
Definition: snprintf.h:34
unsigned int pos
Definition: spdifenc.c:412
This structure describes the bitrate properties of an encoded bitstream.
Definition: avcodec.h:453
int max_bitrate
Maximum bitrate of the stream, in bits per second.
Definition: avcodec.h:459
Describe the class of an AVClass context structure.
Definition: log.h:67
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: codec_par.h:89
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
int profile
Codec-specific bitstream restrictions that the stream conforms to.
Definition: codec_par.h:120
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
Format I/O context.
Definition: avformat.h:1232
AVIOContext * pb
I/O context.
Definition: avformat.h:1274
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1474
int strict_std_compliance
Allow non-standard and experimental extension.
Definition: avformat.h:1542
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1512
char * url
input or output URL.
Definition: avformat.h:1328
void * opaque
User data.
Definition: avformat.h:1752
ff_const59 struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1251
void(* io_close)(struct AVFormatContext *s, AVIOContext *pb)
A callback for closing the streams opened with AVFormatContext.io_open().
Definition: avformat.h:1834
void * priv_data
Format private data.
Definition: avformat.h:1260
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1300
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
A callback for opening new IO streams.
Definition: avformat.h:1828
Bytestream IO Context.
Definition: avio.h:161
AVOption.
Definition: opt.h:248
const char * name
Definition: avformat.h:491
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:516
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:519
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
Stream structure.
Definition: avformat.h:873
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1038
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:935
AVDictionary * metadata
Definition: avformat.h:937
int index
stream index in AVFormatContext
Definition: avformat.h:874
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:1055
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:902
const char * instreamid
Definition: hlsenc.c:190
const char * language
Definition: hlsenc.c:191
const char * ccgroup
Definition: hlsenc.c:189
char * master_pl_name
Definition: hlsenc.c:251
unsigned int nb_ccstreams
Definition: hlsenc.c:244
char * cc_stream_map
Definition: hlsenc.c:250
uint32_t pl_type
Definition: hlsenc.c:207
char * method
Definition: hlsenc.c:238
char * segment_filename
Definition: hlsenc.c:208
int has_video_m3u8
Definition: hlsenc.c:260
ClosedCaptionsStream * cc_streams
Definition: hlsenc.c:243
int hls_delete_threshold
Definition: hlsenc.c:202
AVDictionary * format_options
Definition: hlsenc.c:222
int ignore_io_errors
Definition: hlsenc.c:257
char * subtitle_filename
Definition: hlsenc.c:221
int encrypt_started
Definition: hlsenc.c:229
unsigned int master_publish_rate
Definition: hlsenc.c:252
char * iv
Definition: hlsenc.c:227
char * master_m3u8_url
Definition: hlsenc.c:247
char * key_info_file
Definition: hlsenc.c:231
char * user_agent
Definition: hlsenc.c:239
uint32_t flags
Definition: hlsenc.c:206
char * key_basename
Definition: hlsenc.c:228
int has_default_key
Definition: hlsenc.c:259
int wrap
Definition: hlsenc.c:204
char * headers
Definition: hlsenc.c:258
int http_persistent
Definition: hls.c:212
VariantStream * var_streams
Definition: hlsenc.c:241
uint32_t start_sequence_source_type
Definition: hlsenc.c:197
AVIOContext * sub_m3u8_out
Definition: hlsenc.c:255
char key_string[KEYSIZE *2+1]
Definition: hlsenc.c:234
int version
Definition: hlsenc.c:248
char * fmp4_init_filename
Definition: hlsenc.c:209
int max_nb_segments
Definition: hlsenc.c:201
char * var_stream_map
Definition: hlsenc.c:249
int segment_type
Definition: hlsenc.c:210
char key_uri[LINE_BUFFER_SIZE+1]
Definition: hlsenc.c:233
int use_localtime_mkdir
flag to mkdir dirname in timebased filename
Definition: hlsenc.c:214
AVIOContext * m3u8_out
Definition: hlsenc.c:254
char * vtt_format_options_str
Definition: hlsenc.c:220
int64_t timeout
Definition: hlsenc.c:256
int use_localtime
flag to expand filename with localtime
Definition: hlsenc.c:213
int64_t init_time
Definition: hlsenc.c:200
int64_t time
Definition: hlsenc.c:199
char * key_url
Definition: hlsenc.c:226
int64_t max_seg_size
Definition: hlsenc.c:217
int64_t start_sequence
Definition: hlsenc.c:196
unsigned int nb_varstreams
Definition: hlsenc.c:242
int resend_init_file
resend init file into disk after refresh m3u8
Definition: hlsenc.c:211
int allowcache
Definition: hlsenc.c:215
char * baseurl
Definition: hlsenc.c:219
char * key
Definition: hlsenc.c:225
int64_t recording_time
Definition: hlsenc.c:216
char iv_string[KEYSIZE *2+1]
Definition: hlsenc.c:235
AVDictionary * vtt_format_options
Definition: hlsenc.c:236
char key_file[LINE_BUFFER_SIZE+1]
Definition: hlsenc.c:232
int encrypt
Definition: hlsenc.c:224
int master_m3u8_created
Definition: hlsenc.c:246
int discont
Definition: hlsenc.c:80
char filename[MAX_URL_SIZE]
Definition: hlsenc.c:77
double discont_program_date_time
Definition: hlsenc.c:91
char key_uri[LINE_BUFFER_SIZE+1]
Definition: hlsenc.c:87
double duration
Definition: hlsenc.c:79
struct HLSSegment * next
Definition: hlsenc.c:90
char sub_filename[MAX_URL_SIZE]
Definition: hlsenc.c:78
int64_t keyframe_pos
Definition: hlsenc.c:83
char iv_string[KEYSIZE *2+1]
Definition: hlsenc.c:88
int64_t pos
Definition: hlsenc.c:81
int64_t keyframe_size
Definition: hlsenc.c:84
unsigned var_stream_idx
Definition: hlsenc.c:85
int64_t size
Definition: hlsenc.c:82
Definition: url.h:38
int discontinuity_set
Definition: hlsenc.c:148
int discontinuity
Definition: hlsenc.c:149
char * basename
Definition: hlsenc.c:157
int is_default
Definition: hlsenc.c:180
char key_file[LINE_BUFFER_SIZE+1]
Definition: hlsenc.c:170
double initial_prog_date_time
Definition: hlsenc.c:162
const char * language
Definition: hlsenc.c:181
char * vtt_m3u8_name
Definition: hlsenc.c:159
int start_pts_from_audio
Definition: hlsenc.c:137
int64_t size
Definition: hlsenc.c:146
int m3u8_created
Definition: hlsenc.c:179
HLSSegment * old_segments
Definition: hlsenc.c:154
char codec_attr[128]
Definition: hlsenc.c:176
char * vtt_basename
Definition: hlsenc.c:158
int init_range_length
Definition: hlsenc.c:127
int64_t video_keyframe_size
Definition: hlsenc.c:143
AVIOContext * out_single_file
Definition: hlsenc.c:125
unsigned int nb_streams
Definition: hlsenc.c:178
int64_t sequence
Definition: hlsenc.c:121
int encrypt_started
Definition: hlsenc.c:168
uint8_t * init_buffer
Definition: hlsenc.c:129
int has_subtitle
Definition: hlsenc.c:135
int nb_entries
Definition: hlsenc.c:147
AVStream ** streams
Definition: hlsenc.c:175
int64_t end_pts
Definition: hlsenc.c:140
int reference_stream_index
Definition: hlsenc.c:150
char * fmp4_init_filename
Definition: hlsenc.c:165
int64_t start_pos
Definition: hlsenc.c:145
AVIOContext * out
Definition: hlsenc.c:124
const char * agroup
Definition: hlsenc.c:182
char key_string[KEYSIZE *2+1]
Definition: hlsenc.c:172
int64_t start_pts
Definition: hlsenc.c:139
unsigned var_stream_idx
Definition: hlsenc.c:119
uint8_t * temp_buffer
Definition: hlsenc.c:128
ff_const59 AVOutputFormat * vtt_oformat
Definition: hlsenc.c:123
int has_video
Definition: hlsenc.c:134
char key_uri[LINE_BUFFER_SIZE+1]
Definition: hlsenc.c:171
AVFormatContext * vtt_avf
Definition: hlsenc.c:132
int64_t video_keyframe_pos
Definition: hlsenc.c:142
unsigned number
Definition: hlsenc.c:120
const char * sgroup
Definition: hlsenc.c:183
double dpp
Definition: hlsenc.c:138
HLSSegment * segments
Definition: hlsenc.c:152
const char * varname
Definition: hlsenc.c:185
int new_start
Definition: hlsenc.c:136
AVFormatContext * avf
Definition: hlsenc.c:131
const char * ccgroup
Definition: hlsenc.c:184
char * m3u8_name
Definition: hlsenc.c:160
char * base_output_dirname
Definition: hlsenc.c:166
CodecAttributeStatus attr_status
Definition: hlsenc.c:177
char current_segment_final_filename_fmt[MAX_URL_SIZE]
Definition: hlsenc.c:163
char * basename_tmp
Definition: hlsenc.c:156
int packets_written
Definition: hlsenc.c:126
double duration
Definition: hlsenc.c:144
char iv_string[KEYSIZE *2+1]
Definition: hlsenc.c:173
HLSSegment * last_segment
Definition: hlsenc.c:153
int64_t video_lastpos
Definition: hlsenc.c:141
ff_const59 AVOutputFormat * oformat
Definition: hlsenc.c:122
Definition: graph2dot.c:48
Definition: hls.c:68
int64_t duration
Definition: hls.c:69
uint8_t level
Definition: svq3.c:206
#define lrint
Definition: tablegen.h:53
#define av_free(p)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
static uint8_t tmp[11]
Definition: aes_ctr.c:27
FILE * out
Definition: movenc.c:54
int64_t duration
Definition: movenc.c:64
AVPacket * pkt
Definition: movenc.c:59
AVFormatContext * ctx
Definition: movenc.c:48
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
#define localtime_r
Definition: time_internal.h:46
int size
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:98
const char * b
Definition: vf_curves.c:118
const char * r
Definition: vf_curves.c:116
int len
#define M(a, b)
Definition: vp3dsp.c:45
static double c[64]