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