You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1774 lines
64KB

  1. /*
  2. * Apple HTTP Live Streaming segmenter
  3. * Copyright (c) 2012, Luca Barbato
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include <float.h>
  23. #include <stdint.h>
  24. #if HAVE_UNISTD_H
  25. #include <unistd.h>
  26. #endif
  27. #if CONFIG_GCRYPT
  28. #include <gcrypt.h>
  29. #elif CONFIG_OPENSSL
  30. #include <openssl/rand.h>
  31. #endif
  32. #include "libavutil/avassert.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/parseutils.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/intreadwrite.h"
  37. #include "libavutil/random_seed.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/log.h"
  40. #include "libavutil/time_internal.h"
  41. #include "avformat.h"
  42. #include "avio_internal.h"
  43. #include "internal.h"
  44. #include "os_support.h"
  45. typedef enum {
  46. HLS_START_SEQUENCE_AS_START_NUMBER = 0,
  47. HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
  48. HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2, // YYYYMMDDhhmmss
  49. } StartSequenceSourceType;
  50. #define KEYSIZE 16
  51. #define LINE_BUFFER_SIZE 1024
  52. #define HLS_MICROSECOND_UNIT 1000000
  53. typedef struct HLSSegment {
  54. char filename[1024];
  55. char sub_filename[1024];
  56. double duration; /* in seconds */
  57. int discont;
  58. int64_t pos;
  59. int64_t size;
  60. char key_uri[LINE_BUFFER_SIZE + 1];
  61. char iv_string[KEYSIZE*2 + 1];
  62. struct HLSSegment *next;
  63. } HLSSegment;
  64. typedef enum HLSFlags {
  65. // Generate a single media file and use byte ranges in the playlist.
  66. HLS_SINGLE_FILE = (1 << 0),
  67. HLS_DELETE_SEGMENTS = (1 << 1),
  68. HLS_ROUND_DURATIONS = (1 << 2),
  69. HLS_DISCONT_START = (1 << 3),
  70. HLS_OMIT_ENDLIST = (1 << 4),
  71. HLS_SPLIT_BY_TIME = (1 << 5),
  72. HLS_APPEND_LIST = (1 << 6),
  73. HLS_PROGRAM_DATE_TIME = (1 << 7),
  74. HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
  75. HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
  76. HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
  77. HLS_TEMP_FILE = (1 << 11),
  78. } HLSFlags;
  79. typedef enum {
  80. SEGMENT_TYPE_MPEGTS,
  81. SEGMENT_TYPE_FMP4,
  82. } SegmentType;
  83. typedef enum {
  84. PLAYLIST_TYPE_NONE,
  85. PLAYLIST_TYPE_EVENT,
  86. PLAYLIST_TYPE_VOD,
  87. PLAYLIST_TYPE_NB,
  88. } PlaylistType;
  89. typedef struct HLSContext {
  90. const AVClass *class; // Class for private options.
  91. unsigned number;
  92. int64_t sequence;
  93. int64_t start_sequence;
  94. uint32_t start_sequence_source_type; // enum StartSequenceSourceType
  95. AVOutputFormat *oformat;
  96. AVOutputFormat *vtt_oformat;
  97. AVFormatContext *avf;
  98. AVFormatContext *vtt_avf;
  99. float time; // Set by a private option.
  100. float init_time; // Set by a private option.
  101. int max_nb_segments; // Set by a private option.
  102. #if FF_API_HLS_WRAP
  103. int wrap; // Set by a private option.
  104. #endif
  105. uint32_t flags; // enum HLSFlags
  106. uint32_t pl_type; // enum PlaylistType
  107. char *segment_filename;
  108. char *fmp4_init_filename;
  109. int segment_type;
  110. int fmp4_init_mode;
  111. int use_localtime; ///< flag to expand filename with localtime
  112. int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
  113. int allowcache;
  114. int64_t recording_time;
  115. int has_video;
  116. int has_subtitle;
  117. int new_start;
  118. double dpp; // duration per packet
  119. int64_t start_pts;
  120. int64_t end_pts;
  121. double duration; // last segment duration computed so far, in seconds
  122. int64_t start_pos; // last segment starting position
  123. int64_t size; // last segment size
  124. int64_t max_seg_size; // every segment file max size
  125. int nb_entries;
  126. int discontinuity_set;
  127. int discontinuity;
  128. HLSSegment *segments;
  129. HLSSegment *last_segment;
  130. HLSSegment *old_segments;
  131. char *basename;
  132. char *vtt_basename;
  133. char *vtt_m3u8_name;
  134. char *baseurl;
  135. char *format_options_str;
  136. char *vtt_format_options_str;
  137. char *subtitle_filename;
  138. AVDictionary *format_options;
  139. int encrypt;
  140. char *key;
  141. char *key_url;
  142. char *iv;
  143. char *key_basename;
  144. char *key_info_file;
  145. char key_file[LINE_BUFFER_SIZE + 1];
  146. char key_uri[LINE_BUFFER_SIZE + 1];
  147. char key_string[KEYSIZE*2 + 1];
  148. char iv_string[KEYSIZE*2 + 1];
  149. AVDictionary *vtt_format_options;
  150. char *method;
  151. double initial_prog_date_time;
  152. char current_segment_final_filename_fmt[1024]; // when renaming segments
  153. } HLSContext;
  154. static int get_int_from_double(double val)
  155. {
  156. return (int)((val - (int)val) >= 0.001) ? (int)(val + 1) : (int)val;
  157. }
  158. static int mkdir_p(const char *path) {
  159. int ret = 0;
  160. char *temp = av_strdup(path);
  161. char *pos = temp;
  162. char tmp_ch = '\0';
  163. if (!path || !temp) {
  164. return -1;
  165. }
  166. if (!strncmp(temp, "/", 1) || !strncmp(temp, "\\", 1)) {
  167. pos++;
  168. } else if (!strncmp(temp, "./", 2) || !strncmp(temp, ".\\", 2)) {
  169. pos += 2;
  170. }
  171. for ( ; *pos != '\0'; ++pos) {
  172. if (*pos == '/' || *pos == '\\') {
  173. tmp_ch = *pos;
  174. *pos = '\0';
  175. ret = mkdir(temp, 0755);
  176. *pos = tmp_ch;
  177. }
  178. }
  179. if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
  180. ret = mkdir(temp, 0755);
  181. }
  182. av_free(temp);
  183. return ret;
  184. }
  185. static int replace_int_data_in_filename(char *buf, int buf_size, const char *filename, char placeholder, int64_t number)
  186. {
  187. const char *p;
  188. char *q, buf1[20], c;
  189. int nd, len, addchar_count;
  190. int found_count = 0;
  191. q = buf;
  192. p = filename;
  193. for (;;) {
  194. c = *p;
  195. if (c == '\0')
  196. break;
  197. if (c == '%' && *(p+1) == '%') // %%
  198. addchar_count = 2;
  199. else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
  200. nd = 0;
  201. addchar_count = 1;
  202. while (av_isdigit(*(p + addchar_count))) {
  203. nd = nd * 10 + *(p + addchar_count) - '0';
  204. addchar_count++;
  205. }
  206. if (*(p + addchar_count) == placeholder) {
  207. len = snprintf(buf1, sizeof(buf1), "%0*"PRId64, (number < 0) ? nd : nd++, number);
  208. if (len < 1) // returned error or empty buf1
  209. goto fail;
  210. if ((q - buf + len) > buf_size - 1)
  211. goto fail;
  212. memcpy(q, buf1, len);
  213. q += len;
  214. p += (addchar_count + 1);
  215. addchar_count = 0;
  216. found_count++;
  217. }
  218. } else
  219. addchar_count = 1;
  220. while (addchar_count--)
  221. if ((q - buf) < buf_size - 1)
  222. *q++ = *p++;
  223. else
  224. goto fail;
  225. }
  226. *q = '\0';
  227. return found_count;
  228. fail:
  229. *q = '\0';
  230. return -1;
  231. }
  232. static void write_styp(AVIOContext *pb)
  233. {
  234. avio_wb32(pb, 24);
  235. ffio_wfourcc(pb, "styp");
  236. ffio_wfourcc(pb, "msdh");
  237. avio_wb32(pb, 0); /* minor */
  238. ffio_wfourcc(pb, "msdh");
  239. ffio_wfourcc(pb, "msix");
  240. }
  241. static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls) {
  242. HLSSegment *segment, *previous_segment = NULL;
  243. float playlist_duration = 0.0f;
  244. int ret = 0, path_size, sub_path_size;
  245. char *dirname = NULL, *p, *sub_path;
  246. char *path = NULL;
  247. AVDictionary *options = NULL;
  248. AVIOContext *out = NULL;
  249. const char *proto = NULL;
  250. segment = hls->segments;
  251. while (segment) {
  252. playlist_duration += segment->duration;
  253. segment = segment->next;
  254. }
  255. segment = hls->old_segments;
  256. while (segment) {
  257. playlist_duration -= segment->duration;
  258. previous_segment = segment;
  259. segment = previous_segment->next;
  260. if (playlist_duration <= -previous_segment->duration) {
  261. previous_segment->next = NULL;
  262. break;
  263. }
  264. }
  265. if (segment && !hls->use_localtime_mkdir) {
  266. if (hls->segment_filename) {
  267. dirname = av_strdup(hls->segment_filename);
  268. } else {
  269. dirname = av_strdup(hls->avf->filename);
  270. }
  271. if (!dirname) {
  272. ret = AVERROR(ENOMEM);
  273. goto fail;
  274. }
  275. p = (char *)av_basename(dirname);
  276. *p = '\0';
  277. }
  278. while (segment) {
  279. av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
  280. segment->filename);
  281. path_size = (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
  282. path = av_malloc(path_size);
  283. if (!path) {
  284. ret = AVERROR(ENOMEM);
  285. goto fail;
  286. }
  287. if (hls->use_localtime_mkdir)
  288. av_strlcpy(path, segment->filename, path_size);
  289. else { // segment->filename contains basename only
  290. av_strlcpy(path, dirname, path_size);
  291. av_strlcat(path, segment->filename, path_size);
  292. }
  293. proto = avio_find_protocol_name(s->filename);
  294. if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
  295. av_dict_set(&options, "method", "DELETE", 0);
  296. if ((ret = hls->avf->io_open(hls->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0)
  297. goto fail;
  298. ff_format_io_close(hls->avf, &out);
  299. } else if (unlink(path) < 0) {
  300. av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
  301. path, strerror(errno));
  302. }
  303. if ((segment->sub_filename[0] != '\0')) {
  304. sub_path_size = strlen(segment->sub_filename) + 1 + (dirname ? strlen(dirname) : 0);
  305. sub_path = av_malloc(sub_path_size);
  306. if (!sub_path) {
  307. ret = AVERROR(ENOMEM);
  308. goto fail;
  309. }
  310. av_strlcpy(sub_path, dirname, sub_path_size);
  311. av_strlcat(sub_path, segment->sub_filename, sub_path_size);
  312. if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
  313. av_dict_set(&options, "method", "DELETE", 0);
  314. if ((ret = hls->avf->io_open(hls->avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
  315. av_free(sub_path);
  316. goto fail;
  317. }
  318. ff_format_io_close(hls->avf, &out);
  319. } else if (unlink(sub_path) < 0) {
  320. av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
  321. sub_path, strerror(errno));
  322. }
  323. av_free(sub_path);
  324. }
  325. av_freep(&path);
  326. previous_segment = segment;
  327. segment = previous_segment->next;
  328. av_free(previous_segment);
  329. }
  330. fail:
  331. av_free(path);
  332. av_free(dirname);
  333. return ret;
  334. }
  335. static int randomize(uint8_t *buf, int len)
  336. {
  337. #if CONFIG_GCRYPT
  338. gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
  339. return 0;
  340. #elif CONFIG_OPENSSL
  341. if (RAND_bytes(buf, len))
  342. return 0;
  343. #else
  344. return AVERROR(ENOSYS);
  345. #endif
  346. return AVERROR(EINVAL);
  347. }
  348. static int do_encrypt(AVFormatContext *s)
  349. {
  350. HLSContext *hls = s->priv_data;
  351. int ret;
  352. int len;
  353. AVIOContext *pb;
  354. uint8_t key[KEYSIZE];
  355. len = strlen(hls->basename) + 4 + 1;
  356. hls->key_basename = av_mallocz(len);
  357. if (!hls->key_basename)
  358. return AVERROR(ENOMEM);
  359. av_strlcpy(hls->key_basename, s->filename, len);
  360. av_strlcat(hls->key_basename, ".key", len);
  361. if (hls->key_url) {
  362. av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
  363. av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
  364. } else {
  365. av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
  366. av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
  367. }
  368. if (!*hls->iv_string) {
  369. uint8_t iv[16] = { 0 };
  370. char buf[33];
  371. if (!hls->iv) {
  372. AV_WB64(iv + 8, hls->sequence);
  373. } else {
  374. memcpy(iv, hls->iv, sizeof(iv));
  375. }
  376. ff_data_to_hex(buf, iv, sizeof(iv), 0);
  377. buf[32] = '\0';
  378. memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
  379. }
  380. if (!*hls->key_uri) {
  381. av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
  382. return AVERROR(EINVAL);
  383. }
  384. if (!*hls->key_file) {
  385. av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
  386. return AVERROR(EINVAL);
  387. }
  388. if (!*hls->key_string) {
  389. if (!hls->key) {
  390. if ((ret = randomize(key, sizeof(key))) < 0) {
  391. av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
  392. return ret;
  393. }
  394. } else {
  395. memcpy(key, hls->key, sizeof(key));
  396. }
  397. ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
  398. if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
  399. return ret;
  400. avio_seek(pb, 0, SEEK_CUR);
  401. avio_write(pb, key, KEYSIZE);
  402. avio_close(pb);
  403. }
  404. return 0;
  405. }
  406. static int hls_encryption_start(AVFormatContext *s)
  407. {
  408. HLSContext *hls = s->priv_data;
  409. int ret;
  410. AVIOContext *pb;
  411. uint8_t key[KEYSIZE];
  412. if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
  413. av_log(hls, AV_LOG_ERROR,
  414. "error opening key info file %s\n", hls->key_info_file);
  415. return ret;
  416. }
  417. ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
  418. hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
  419. ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
  420. hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
  421. ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
  422. hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
  423. ff_format_io_close(s, &pb);
  424. if (!*hls->key_uri) {
  425. av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
  426. return AVERROR(EINVAL);
  427. }
  428. if (!*hls->key_file) {
  429. av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
  430. return AVERROR(EINVAL);
  431. }
  432. if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
  433. av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
  434. return ret;
  435. }
  436. ret = avio_read(pb, key, sizeof(key));
  437. ff_format_io_close(s, &pb);
  438. if (ret != sizeof(key)) {
  439. av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
  440. if (ret >= 0 || ret == AVERROR_EOF)
  441. ret = AVERROR(EINVAL);
  442. return ret;
  443. }
  444. ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
  445. return 0;
  446. }
  447. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  448. {
  449. int len = ff_get_line(s, buf, maxlen);
  450. while (len > 0 && av_isspace(buf[len - 1]))
  451. buf[--len] = '\0';
  452. return len;
  453. }
  454. static int hls_mux_init(AVFormatContext *s)
  455. {
  456. AVDictionary *options = NULL;
  457. HLSContext *hls = s->priv_data;
  458. AVFormatContext *oc;
  459. AVFormatContext *vtt_oc = NULL;
  460. int i, ret;
  461. ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
  462. if (ret < 0)
  463. return ret;
  464. oc = hls->avf;
  465. oc->filename[0] = '\0';
  466. oc->oformat = hls->oformat;
  467. oc->interrupt_callback = s->interrupt_callback;
  468. oc->max_delay = s->max_delay;
  469. oc->opaque = s->opaque;
  470. oc->io_open = s->io_open;
  471. oc->io_close = s->io_close;
  472. av_dict_copy(&oc->metadata, s->metadata, 0);
  473. if(hls->vtt_oformat) {
  474. ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);
  475. if (ret < 0)
  476. return ret;
  477. vtt_oc = hls->vtt_avf;
  478. vtt_oc->oformat = hls->vtt_oformat;
  479. av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
  480. }
  481. for (i = 0; i < s->nb_streams; i++) {
  482. AVStream *st;
  483. AVFormatContext *loc;
  484. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  485. loc = vtt_oc;
  486. else
  487. loc = oc;
  488. if (!(st = avformat_new_stream(loc, NULL)))
  489. return AVERROR(ENOMEM);
  490. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  491. if (!oc->oformat->codec_tag ||
  492. av_codec_get_id (oc->oformat->codec_tag, s->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
  493. av_codec_get_tag(oc->oformat->codec_tag, s->streams[i]->codecpar->codec_id) <= 0) {
  494. st->codecpar->codec_tag = s->streams[i]->codecpar->codec_tag;
  495. } else {
  496. st->codecpar->codec_tag = 0;
  497. }
  498. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  499. st->time_base = s->streams[i]->time_base;
  500. av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
  501. }
  502. hls->start_pos = 0;
  503. hls->new_start = 1;
  504. hls->fmp4_init_mode = 0;
  505. if (hls->segment_type == SEGMENT_TYPE_FMP4) {
  506. hls->fmp4_init_mode = 1;
  507. if ((ret = s->io_open(s, &oc->pb, hls->fmp4_init_filename, AVIO_FLAG_WRITE, NULL)) < 0) {
  508. av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", hls->fmp4_init_filename);
  509. return ret;
  510. }
  511. if (hls->format_options_str) {
  512. ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
  513. if (ret < 0) {
  514. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
  515. hls->format_options_str);
  516. return ret;
  517. }
  518. }
  519. av_dict_copy(&options, hls->format_options, 0);
  520. av_dict_set(&options, "fflags", "-autobsf", 0);
  521. av_dict_set(&options, "movflags", "frag_custom+dash+delay_moov", 0);
  522. ret = avformat_init_output(oc, &options);
  523. if (av_dict_count(options)) {
  524. av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
  525. av_dict_free(&options);
  526. return AVERROR(EINVAL);
  527. }
  528. av_dict_free(&options);
  529. }
  530. return 0;
  531. }
  532. static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
  533. {
  534. while (segment) {
  535. if (!av_strcasecmp(segment->filename,filename))
  536. return segment;
  537. segment = segment->next;
  538. }
  539. return (HLSSegment *) NULL;
  540. }
  541. static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls, HLSSegment *en, double duration,
  542. int64_t pos, int64_t size)
  543. {
  544. if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
  545. strlen(hls->current_segment_final_filename_fmt)) {
  546. av_strlcpy(hls->avf->filename, hls->current_segment_final_filename_fmt, sizeof(hls->avf->filename));
  547. if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
  548. char * filename = av_strdup(hls->avf->filename); // %%s will be %s after strftime
  549. if (!filename) {
  550. av_free(en);
  551. return AVERROR(ENOMEM);
  552. }
  553. if (replace_int_data_in_filename(hls->avf->filename, sizeof(hls->avf->filename),
  554. filename, 's', pos + size) < 1) {
  555. av_log(hls, AV_LOG_ERROR,
  556. "Invalid second level segment filename template '%s', "
  557. "you can try to remove second_level_segment_size flag\n",
  558. filename);
  559. av_free(filename);
  560. av_free(en);
  561. return AVERROR(EINVAL);
  562. }
  563. av_free(filename);
  564. }
  565. if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
  566. char * filename = av_strdup(hls->avf->filename); // %%t will be %t after strftime
  567. if (!filename) {
  568. av_free(en);
  569. return AVERROR(ENOMEM);
  570. }
  571. if (replace_int_data_in_filename(hls->avf->filename, sizeof(hls->avf->filename),
  572. filename, 't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
  573. av_log(hls, AV_LOG_ERROR,
  574. "Invalid second level segment filename template '%s', "
  575. "you can try to remove second_level_segment_time flag\n",
  576. filename);
  577. av_free(filename);
  578. av_free(en);
  579. return AVERROR(EINVAL);
  580. }
  581. av_free(filename);
  582. }
  583. }
  584. return 0;
  585. }
  586. static int sls_flag_check_duration_size_index(HLSContext *hls)
  587. {
  588. int ret = 0;
  589. if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
  590. av_log(hls, AV_LOG_ERROR,
  591. "second_level_segment_duration hls_flag requires use_localtime to be true\n");
  592. ret = AVERROR(EINVAL);
  593. }
  594. if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
  595. av_log(hls, AV_LOG_ERROR,
  596. "second_level_segment_size hls_flag requires use_localtime to be true\n");
  597. ret = AVERROR(EINVAL);
  598. }
  599. if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
  600. av_log(hls, AV_LOG_ERROR,
  601. "second_level_segment_index hls_flag requires use_localtime to be true\n");
  602. ret = AVERROR(EINVAL);
  603. }
  604. return ret;
  605. }
  606. static int sls_flag_check_duration_size(HLSContext *hls)
  607. {
  608. const char *proto = avio_find_protocol_name(hls->basename);
  609. int segment_renaming_ok = proto && !strcmp(proto, "file");
  610. int ret = 0;
  611. if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
  612. av_log(hls, AV_LOG_ERROR,
  613. "second_level_segment_duration hls_flag works only with file protocol segment names\n");
  614. ret = AVERROR(EINVAL);
  615. }
  616. if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
  617. av_log(hls, AV_LOG_ERROR,
  618. "second_level_segment_size hls_flag works only with file protocol segment names\n");
  619. ret = AVERROR(EINVAL);
  620. }
  621. return ret;
  622. }
  623. static void sls_flag_file_rename(HLSContext *hls, char *old_filename) {
  624. if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
  625. strlen(hls->current_segment_final_filename_fmt)) {
  626. ff_rename(old_filename, hls->avf->filename, hls);
  627. }
  628. }
  629. static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c)
  630. {
  631. if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
  632. char * filename = av_strdup(oc->filename); // %%d will be %d after strftime
  633. if (!filename)
  634. return AVERROR(ENOMEM);
  635. if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
  636. #if FF_API_HLS_WRAP
  637. filename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
  638. #else
  639. filename, 'd', c->sequence) < 1) {
  640. #endif
  641. av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
  642. "you can try to remove second_level_segment_index flag\n",
  643. filename);
  644. av_free(filename);
  645. return AVERROR(EINVAL);
  646. }
  647. av_free(filename);
  648. }
  649. if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
  650. av_strlcpy(c->current_segment_final_filename_fmt, oc->filename,
  651. sizeof(c->current_segment_final_filename_fmt));
  652. if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
  653. char * filename = av_strdup(oc->filename); // %%s will be %s after strftime
  654. if (!filename)
  655. return AVERROR(ENOMEM);
  656. if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename), filename, 's', 0) < 1) {
  657. av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
  658. "you can try to remove second_level_segment_size flag\n",
  659. filename);
  660. av_free(filename);
  661. return AVERROR(EINVAL);
  662. }
  663. av_free(filename);
  664. }
  665. if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
  666. char * filename = av_strdup(oc->filename); // %%t will be %t after strftime
  667. if (!filename)
  668. return AVERROR(ENOMEM);
  669. if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename), filename, 't', 0) < 1) {
  670. av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
  671. "you can try to remove second_level_segment_time flag\n",
  672. filename);
  673. av_free(filename);
  674. return AVERROR(EINVAL);
  675. }
  676. av_free(filename);
  677. }
  678. }
  679. return 0;
  680. }
  681. /* Create a new segment and append it to the segment list */
  682. static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, double duration,
  683. int64_t pos, int64_t size)
  684. {
  685. HLSSegment *en = av_malloc(sizeof(*en));
  686. const char *filename;
  687. int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
  688. int ret;
  689. if (!en)
  690. return AVERROR(ENOMEM);
  691. ret = sls_flags_filename_process(s, hls, en, duration, pos, size);
  692. if (ret < 0) {
  693. return ret;
  694. }
  695. filename = av_basename(hls->avf->filename);
  696. if (hls->use_localtime_mkdir) {
  697. filename = hls->avf->filename;
  698. }
  699. if ((find_segment_by_filename(hls->segments, filename) || find_segment_by_filename(hls->old_segments, filename))
  700. && !byterange_mode) {
  701. av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
  702. }
  703. av_strlcpy(en->filename, filename, sizeof(en->filename));
  704. if(hls->has_subtitle)
  705. av_strlcpy(en->sub_filename, av_basename(hls->vtt_avf->filename), sizeof(en->sub_filename));
  706. else
  707. en->sub_filename[0] = '\0';
  708. en->duration = duration;
  709. en->pos = pos;
  710. en->size = size;
  711. en->next = NULL;
  712. en->discont = 0;
  713. if (hls->discontinuity) {
  714. en->discont = 1;
  715. hls->discontinuity = 0;
  716. }
  717. if (hls->key_info_file || hls->encrypt) {
  718. av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
  719. av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
  720. }
  721. if (!hls->segments)
  722. hls->segments = en;
  723. else
  724. hls->last_segment->next = en;
  725. hls->last_segment = en;
  726. // EVENT or VOD playlists imply sliding window cannot be used
  727. if (hls->pl_type != PLAYLIST_TYPE_NONE)
  728. hls->max_nb_segments = 0;
  729. if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
  730. en = hls->segments;
  731. hls->initial_prog_date_time += en->duration;
  732. hls->segments = en->next;
  733. if (en && hls->flags & HLS_DELETE_SEGMENTS &&
  734. #if FF_API_HLS_WRAP
  735. !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
  736. #else
  737. !(hls->flags & HLS_SINGLE_FILE)) {
  738. #endif
  739. en->next = hls->old_segments;
  740. hls->old_segments = en;
  741. if ((ret = hls_delete_old_segments(s, hls)) < 0)
  742. return ret;
  743. } else
  744. av_free(en);
  745. } else
  746. hls->nb_entries++;
  747. if (hls->max_seg_size > 0) {
  748. return 0;
  749. }
  750. hls->sequence++;
  751. return 0;
  752. }
  753. static int parse_playlist(AVFormatContext *s, const char *url)
  754. {
  755. HLSContext *hls = s->priv_data;
  756. AVIOContext *in;
  757. int ret = 0, is_segment = 0;
  758. int64_t new_start_pos;
  759. char line[1024];
  760. const char *ptr;
  761. const char *end;
  762. if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
  763. &s->interrupt_callback, NULL,
  764. s->protocol_whitelist, s->protocol_blacklist)) < 0)
  765. return ret;
  766. read_chomp_line(in, line, sizeof(line));
  767. if (strcmp(line, "#EXTM3U")) {
  768. ret = AVERROR_INVALIDDATA;
  769. goto fail;
  770. }
  771. hls->discontinuity = 0;
  772. while (!avio_feof(in)) {
  773. read_chomp_line(in, line, sizeof(line));
  774. if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  775. int64_t tmp_sequence = strtoll(ptr, NULL, 10);
  776. if (tmp_sequence < hls->sequence)
  777. av_log(hls, AV_LOG_VERBOSE,
  778. "Found playlist sequence number was smaller """
  779. "than specified start sequence number: %"PRId64" < %"PRId64", "
  780. "omitting\n", tmp_sequence, hls->start_sequence);
  781. else {
  782. av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
  783. hls->sequence = tmp_sequence;
  784. }
  785. } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
  786. is_segment = 1;
  787. hls->discontinuity = 1;
  788. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  789. is_segment = 1;
  790. hls->duration = atof(ptr);
  791. } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
  792. ptr = av_stristr(line, "URI=\"");
  793. if (ptr) {
  794. ptr += strlen("URI=\"");
  795. end = av_stristr(ptr, ",");
  796. if (end) {
  797. av_strlcpy(hls->key_uri, ptr, end - ptr);
  798. } else {
  799. av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
  800. }
  801. }
  802. ptr = av_stristr(line, "IV=0x");
  803. if (ptr) {
  804. ptr += strlen("IV=0x");
  805. end = av_stristr(ptr, ",");
  806. if (end) {
  807. av_strlcpy(hls->iv_string, ptr, end - ptr);
  808. } else {
  809. av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
  810. }
  811. }
  812. } else if (av_strstart(line, "#", NULL)) {
  813. continue;
  814. } else if (line[0]) {
  815. if (is_segment) {
  816. is_segment = 0;
  817. new_start_pos = avio_tell(hls->avf->pb);
  818. hls->size = new_start_pos - hls->start_pos;
  819. av_strlcpy(hls->avf->filename, line, sizeof(line));
  820. ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
  821. if (ret < 0)
  822. goto fail;
  823. hls->start_pos = new_start_pos;
  824. }
  825. }
  826. }
  827. fail:
  828. avio_close(in);
  829. return ret;
  830. }
  831. static void hls_free_segments(HLSSegment *p)
  832. {
  833. HLSSegment *en;
  834. while(p) {
  835. en = p;
  836. p = p->next;
  837. av_free(en);
  838. }
  839. }
  840. static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
  841. {
  842. const char *proto = avio_find_protocol_name(s->filename);
  843. int http_base_proto = proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
  844. if (c->method) {
  845. av_dict_set(options, "method", c->method, 0);
  846. } else if (http_base_proto) {
  847. av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
  848. av_dict_set(options, "method", "PUT", 0);
  849. }
  850. }
  851. static void write_m3u8_head_block(HLSContext *hls, AVIOContext *out, int version,
  852. int target_duration, int64_t sequence)
  853. {
  854. avio_printf(out, "#EXTM3U\n");
  855. avio_printf(out, "#EXT-X-VERSION:%d\n", version);
  856. if (hls->allowcache == 0 || hls->allowcache == 1) {
  857. avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  858. }
  859. avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
  860. avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  861. if (hls->segment_type == SEGMENT_TYPE_FMP4) {
  862. avio_printf(out, "#EXT-X-MAP:URI=\"%s\"\n", hls->fmp4_init_filename);
  863. }
  864. av_log(hls, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  865. }
  866. static void hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
  867. {
  868. size_t len = strlen(oc->filename);
  869. char final_filename[sizeof(oc->filename)];
  870. av_strlcpy(final_filename, oc->filename, len);
  871. final_filename[len-4] = '\0';
  872. ff_rename(oc->filename, final_filename, s);
  873. oc->filename[len-4] = '\0';
  874. }
  875. static int hls_window(AVFormatContext *s, int last)
  876. {
  877. HLSContext *hls = s->priv_data;
  878. HLSSegment *en;
  879. int target_duration = 0;
  880. int ret = 0;
  881. AVIOContext *out = NULL;
  882. AVIOContext *sub_out = NULL;
  883. char temp_filename[1024];
  884. int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
  885. int version = 3;
  886. const char *proto = avio_find_protocol_name(s->filename);
  887. int use_rename = proto && !strcmp(proto, "file");
  888. static unsigned warned_non_file;
  889. char *key_uri = NULL;
  890. char *iv_string = NULL;
  891. AVDictionary *options = NULL;
  892. double prog_date_time = hls->initial_prog_date_time;
  893. int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
  894. if (byterange_mode) {
  895. version = 4;
  896. sequence = 0;
  897. }
  898. if (hls->segment_type == SEGMENT_TYPE_FMP4) {
  899. version = 7;
  900. }
  901. if (!use_rename && !warned_non_file++)
  902. av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
  903. set_http_options(s, &options, hls);
  904. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
  905. if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &options)) < 0)
  906. goto fail;
  907. for (en = hls->segments; en; en = en->next) {
  908. if (target_duration <= en->duration)
  909. target_duration = get_int_from_double(en->duration);
  910. }
  911. hls->discontinuity_set = 0;
  912. write_m3u8_head_block(hls, out, version, target_duration, sequence);
  913. if (hls->pl_type == PLAYLIST_TYPE_EVENT) {
  914. avio_printf(out, "#EXT-X-PLAYLIST-TYPE:EVENT\n");
  915. } else if (hls->pl_type == PLAYLIST_TYPE_VOD) {
  916. avio_printf(out, "#EXT-X-PLAYLIST-TYPE:VOD\n");
  917. }
  918. if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && hls->discontinuity_set==0 ){
  919. avio_printf(out, "#EXT-X-DISCONTINUITY\n");
  920. hls->discontinuity_set = 1;
  921. }
  922. for (en = hls->segments; en; en = en->next) {
  923. if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
  924. av_strcasecmp(en->iv_string, iv_string))) {
  925. avio_printf(out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
  926. if (*en->iv_string)
  927. avio_printf(out, ",IV=0x%s", en->iv_string);
  928. avio_printf(out, "\n");
  929. key_uri = en->key_uri;
  930. iv_string = en->iv_string;
  931. }
  932. if (en->discont) {
  933. avio_printf(out, "#EXT-X-DISCONTINUITY\n");
  934. }
  935. if (hls->flags & HLS_ROUND_DURATIONS)
  936. avio_printf(out, "#EXTINF:%ld,\n", lrint(en->duration));
  937. else
  938. avio_printf(out, "#EXTINF:%f,\n", en->duration);
  939. if (byterange_mode)
  940. avio_printf(out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
  941. en->size, en->pos);
  942. if (hls->flags & HLS_PROGRAM_DATE_TIME) {
  943. time_t tt, wrongsecs;
  944. int milli;
  945. struct tm *tm, tmpbuf;
  946. char buf0[128], buf1[128];
  947. tt = (int64_t)prog_date_time;
  948. milli = av_clip(lrint(1000*(prog_date_time - tt)), 0, 999);
  949. tm = localtime_r(&tt, &tmpbuf);
  950. strftime(buf0, sizeof(buf0), "%Y-%m-%dT%H:%M:%S", tm);
  951. if (!strftime(buf1, sizeof(buf1), "%z", tm) || buf1[1]<'0' ||buf1[1]>'2') {
  952. int tz_min, dst = tm->tm_isdst;
  953. tm = gmtime_r(&tt, &tmpbuf);
  954. tm->tm_isdst = dst;
  955. wrongsecs = mktime(tm);
  956. tz_min = (abs(wrongsecs - tt) + 30) / 60;
  957. snprintf(buf1, sizeof(buf1),
  958. "%c%02d%02d",
  959. wrongsecs <= tt ? '+' : '-',
  960. tz_min / 60,
  961. tz_min % 60);
  962. }
  963. avio_printf(out, "#EXT-X-PROGRAM-DATE-TIME:%s.%03d%s\n", buf0, milli, buf1);
  964. prog_date_time += en->duration;
  965. }
  966. if (hls->baseurl)
  967. avio_printf(out, "%s", hls->baseurl);
  968. avio_printf(out, "%s\n", en->filename);
  969. }
  970. if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
  971. avio_printf(out, "#EXT-X-ENDLIST\n");
  972. if( hls->vtt_m3u8_name ) {
  973. if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)
  974. goto fail;
  975. write_m3u8_head_block(hls, sub_out, version, target_duration, sequence);
  976. for (en = hls->segments; en; en = en->next) {
  977. avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);
  978. if (byterange_mode)
  979. avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
  980. en->size, en->pos);
  981. if (hls->baseurl)
  982. avio_printf(sub_out, "%s", hls->baseurl);
  983. avio_printf(sub_out, "%s\n", en->sub_filename);
  984. }
  985. if (last)
  986. avio_printf(sub_out, "#EXT-X-ENDLIST\n");
  987. }
  988. fail:
  989. av_dict_free(&options);
  990. ff_format_io_close(s, &out);
  991. ff_format_io_close(s, &sub_out);
  992. if (ret >= 0 && use_rename)
  993. ff_rename(temp_filename, s->filename, s);
  994. return ret;
  995. }
  996. static int hls_start(AVFormatContext *s)
  997. {
  998. HLSContext *c = s->priv_data;
  999. AVFormatContext *oc = c->avf;
  1000. AVFormatContext *vtt_oc = c->vtt_avf;
  1001. AVDictionary *options = NULL;
  1002. char *filename, iv_string[KEYSIZE*2 + 1];
  1003. int err = 0;
  1004. if (c->flags & HLS_SINGLE_FILE) {
  1005. av_strlcpy(oc->filename, c->basename,
  1006. sizeof(oc->filename));
  1007. if (c->vtt_basename)
  1008. av_strlcpy(vtt_oc->filename, c->vtt_basename,
  1009. sizeof(vtt_oc->filename));
  1010. } else if (c->max_seg_size > 0) {
  1011. if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
  1012. #if FF_API_HLS_WRAP
  1013. c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
  1014. #else
  1015. c->basename, 'd', c->sequence) < 1) {
  1016. #endif
  1017. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -use_localtime 1 with it\n", c->basename);
  1018. return AVERROR(EINVAL);
  1019. }
  1020. } else {
  1021. if (c->use_localtime) {
  1022. time_t now0;
  1023. struct tm *tm, tmpbuf;
  1024. time(&now0);
  1025. tm = localtime_r(&now0, &tmpbuf);
  1026. if (!strftime(oc->filename, sizeof(oc->filename), c->basename, tm)) {
  1027. av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
  1028. return AVERROR(EINVAL);
  1029. }
  1030. err = sls_flag_use_localtime_filename(oc, c);
  1031. if (err < 0) {
  1032. return AVERROR(ENOMEM);
  1033. }
  1034. if (c->use_localtime_mkdir) {
  1035. const char *dir;
  1036. char *fn_copy = av_strdup(oc->filename);
  1037. if (!fn_copy) {
  1038. return AVERROR(ENOMEM);
  1039. }
  1040. dir = av_dirname(fn_copy);
  1041. if (mkdir_p(dir) == -1 && errno != EEXIST) {
  1042. av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
  1043. av_free(fn_copy);
  1044. return AVERROR(errno);
  1045. }
  1046. av_free(fn_copy);
  1047. }
  1048. } else if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
  1049. #if FF_API_HLS_WRAP
  1050. c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
  1051. #else
  1052. c->basename, 'd', c->sequence) < 1) {
  1053. #endif
  1054. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -use_localtime 1 with it\n", c->basename);
  1055. return AVERROR(EINVAL);
  1056. }
  1057. if( c->vtt_basename) {
  1058. if (replace_int_data_in_filename(vtt_oc->filename, sizeof(vtt_oc->filename),
  1059. #if FF_API_HLS_WRAP
  1060. c->vtt_basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
  1061. #else
  1062. c->vtt_basename, 'd', c->sequence) < 1) {
  1063. #endif
  1064. av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->vtt_basename);
  1065. return AVERROR(EINVAL);
  1066. }
  1067. }
  1068. }
  1069. c->number++;
  1070. set_http_options(s, &options, c);
  1071. if (c->flags & HLS_TEMP_FILE) {
  1072. av_strlcat(oc->filename, ".tmp", sizeof(oc->filename));
  1073. }
  1074. if (c->key_info_file || c->encrypt) {
  1075. if (c->key_info_file && c->encrypt) {
  1076. av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
  1077. " will use -hls_key_info_file priority\n");
  1078. }
  1079. if (c->key_info_file) {
  1080. if ((err = hls_encryption_start(s)) < 0)
  1081. goto fail;
  1082. } else {
  1083. if ((err = do_encrypt(s)) < 0)
  1084. goto fail;
  1085. }
  1086. if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
  1087. < 0)
  1088. goto fail;
  1089. err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
  1090. if (!err)
  1091. snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, c->sequence);
  1092. if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
  1093. goto fail;
  1094. filename = av_asprintf("crypto:%s", oc->filename);
  1095. if (!filename) {
  1096. err = AVERROR(ENOMEM);
  1097. goto fail;
  1098. }
  1099. err = s->io_open(s, &oc->pb, filename, AVIO_FLAG_WRITE, &options);
  1100. av_free(filename);
  1101. av_dict_free(&options);
  1102. if (err < 0)
  1103. return err;
  1104. } else
  1105. if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
  1106. goto fail;
  1107. if (c->vtt_basename) {
  1108. set_http_options(s, &options, c);
  1109. if ((err = s->io_open(s, &vtt_oc->pb, vtt_oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
  1110. goto fail;
  1111. }
  1112. av_dict_free(&options);
  1113. if (c->segment_type == SEGMENT_TYPE_FMP4) {
  1114. write_styp(oc->pb);
  1115. } else {
  1116. /* We only require one PAT/PMT per segment. */
  1117. if (oc->oformat->priv_class && oc->priv_data) {
  1118. char period[21];
  1119. snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
  1120. av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
  1121. av_opt_set(oc->priv_data, "sdt_period", period, 0);
  1122. av_opt_set(oc->priv_data, "pat_period", period, 0);
  1123. }
  1124. }
  1125. if (c->vtt_basename) {
  1126. err = avformat_write_header(vtt_oc,NULL);
  1127. if (err < 0)
  1128. return err;
  1129. }
  1130. return 0;
  1131. fail:
  1132. av_dict_free(&options);
  1133. return err;
  1134. }
  1135. static const char * get_default_pattern_localtime_fmt(void)
  1136. {
  1137. char b[21];
  1138. time_t t = time(NULL);
  1139. struct tm *p, tmbuf;
  1140. p = localtime_r(&t, &tmbuf);
  1141. // no %s support when strftime returned error or left format string unchanged
  1142. // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
  1143. return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
  1144. }
  1145. static int hls_write_header(AVFormatContext *s)
  1146. {
  1147. HLSContext *hls = s->priv_data;
  1148. int ret, i;
  1149. char *p;
  1150. const char *pattern = "%d.ts";
  1151. const char *pattern_localtime_fmt = get_default_pattern_localtime_fmt();
  1152. const char *vtt_pattern = "%d.vtt";
  1153. AVDictionary *options = NULL;
  1154. int basename_size;
  1155. int vtt_basename_size;
  1156. if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
  1157. (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
  1158. time_t t = time(NULL); // we will need it in either case
  1159. if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
  1160. hls->start_sequence = (int64_t)t;
  1161. } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
  1162. char b[15];
  1163. struct tm *p, tmbuf;
  1164. if (!(p = localtime_r(&t, &tmbuf)))
  1165. return AVERROR(ENOMEM);
  1166. if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
  1167. return AVERROR(ENOMEM);
  1168. hls->start_sequence = strtoll(b, NULL, 10);
  1169. }
  1170. av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
  1171. }
  1172. hls->sequence = hls->start_sequence;
  1173. hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
  1174. hls->start_pts = AV_NOPTS_VALUE;
  1175. hls->current_segment_final_filename_fmt[0] = '\0';
  1176. if (hls->flags & HLS_PROGRAM_DATE_TIME) {
  1177. time_t now0;
  1178. time(&now0);
  1179. hls->initial_prog_date_time = now0;
  1180. }
  1181. if (hls->format_options_str) {
  1182. ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
  1183. if (ret < 0) {
  1184. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
  1185. goto fail;
  1186. }
  1187. }
  1188. for (i = 0; i < s->nb_streams; i++) {
  1189. hls->has_video +=
  1190. s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
  1191. hls->has_subtitle +=
  1192. s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
  1193. }
  1194. if (hls->has_video > 1)
  1195. av_log(s, AV_LOG_WARNING,
  1196. "More than a single video stream present, "
  1197. "expect issues decoding it.\n");
  1198. if (hls->segment_type == SEGMENT_TYPE_FMP4) {
  1199. hls->oformat = av_guess_format("mp4", NULL, NULL);
  1200. } else {
  1201. hls->oformat = av_guess_format("mpegts", NULL, NULL);
  1202. }
  1203. if (!hls->oformat) {
  1204. ret = AVERROR_MUXER_NOT_FOUND;
  1205. goto fail;
  1206. }
  1207. if(hls->has_subtitle) {
  1208. hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
  1209. if (!hls->oformat) {
  1210. ret = AVERROR_MUXER_NOT_FOUND;
  1211. goto fail;
  1212. }
  1213. }
  1214. if (hls->segment_filename) {
  1215. hls->basename = av_strdup(hls->segment_filename);
  1216. if (!hls->basename) {
  1217. ret = AVERROR(ENOMEM);
  1218. goto fail;
  1219. }
  1220. } else {
  1221. if (hls->flags & HLS_SINGLE_FILE)
  1222. pattern = ".ts";
  1223. if (hls->use_localtime) {
  1224. basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;
  1225. } else {
  1226. basename_size = strlen(s->filename) + strlen(pattern) + 1;
  1227. }
  1228. hls->basename = av_malloc(basename_size);
  1229. if (!hls->basename) {
  1230. ret = AVERROR(ENOMEM);
  1231. goto fail;
  1232. }
  1233. av_strlcpy(hls->basename, s->filename, basename_size);
  1234. p = strrchr(hls->basename, '.');
  1235. if (p)
  1236. *p = '\0';
  1237. if (hls->use_localtime) {
  1238. av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);
  1239. } else {
  1240. av_strlcat(hls->basename, pattern, basename_size);
  1241. }
  1242. }
  1243. if (!hls->use_localtime) {
  1244. ret = sls_flag_check_duration_size_index(hls);
  1245. if (ret < 0) {
  1246. goto fail;
  1247. }
  1248. } else {
  1249. ret = sls_flag_check_duration_size(hls);
  1250. if (ret < 0) {
  1251. goto fail;
  1252. }
  1253. }
  1254. if(hls->has_subtitle) {
  1255. if (hls->flags & HLS_SINGLE_FILE)
  1256. vtt_pattern = ".vtt";
  1257. vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1;
  1258. hls->vtt_basename = av_malloc(vtt_basename_size);
  1259. if (!hls->vtt_basename) {
  1260. ret = AVERROR(ENOMEM);
  1261. goto fail;
  1262. }
  1263. hls->vtt_m3u8_name = av_malloc(vtt_basename_size);
  1264. if (!hls->vtt_m3u8_name ) {
  1265. ret = AVERROR(ENOMEM);
  1266. goto fail;
  1267. }
  1268. av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);
  1269. p = strrchr(hls->vtt_basename, '.');
  1270. if (p)
  1271. *p = '\0';
  1272. if( hls->subtitle_filename ) {
  1273. strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);
  1274. } else {
  1275. strcpy(hls->vtt_m3u8_name, hls->vtt_basename);
  1276. av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
  1277. }
  1278. av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);
  1279. }
  1280. if ((ret = hls_mux_init(s)) < 0)
  1281. goto fail;
  1282. if (hls->flags & HLS_APPEND_LIST) {
  1283. parse_playlist(s, s->filename);
  1284. hls->discontinuity = 1;
  1285. if (hls->init_time > 0) {
  1286. av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
  1287. " hls_init_time value will have no effect\n");
  1288. hls->init_time = 0;
  1289. hls->recording_time = hls->time * AV_TIME_BASE;
  1290. }
  1291. }
  1292. if (hls->segment_type != SEGMENT_TYPE_FMP4) {
  1293. if ((ret = hls_start(s)) < 0)
  1294. goto fail;
  1295. }
  1296. av_dict_copy(&options, hls->format_options, 0);
  1297. ret = avformat_write_header(hls->avf, &options);
  1298. if (av_dict_count(options)) {
  1299. av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
  1300. ret = AVERROR(EINVAL);
  1301. goto fail;
  1302. }
  1303. //av_assert0(s->nb_streams == hls->avf->nb_streams);
  1304. for (i = 0; i < s->nb_streams; i++) {
  1305. AVStream *inner_st;
  1306. AVStream *outer_st = s->streams[i];
  1307. if (hls->max_seg_size > 0) {
  1308. if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  1309. (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
  1310. av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
  1311. "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
  1312. outer_st->codecpar->bit_rate, hls->max_seg_size);
  1313. }
  1314. }
  1315. if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
  1316. inner_st = hls->avf->streams[i];
  1317. else if (hls->vtt_avf)
  1318. inner_st = hls->vtt_avf->streams[0];
  1319. else {
  1320. /* We have a subtitle stream, when the user does not want one */
  1321. inner_st = NULL;
  1322. continue;
  1323. }
  1324. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  1325. }
  1326. fail:
  1327. av_dict_free(&options);
  1328. if (ret < 0) {
  1329. av_freep(&hls->basename);
  1330. av_freep(&hls->vtt_basename);
  1331. av_freep(&hls->key_basename);
  1332. if (hls->avf)
  1333. avformat_free_context(hls->avf);
  1334. if (hls->vtt_avf)
  1335. avformat_free_context(hls->vtt_avf);
  1336. }
  1337. return ret;
  1338. }
  1339. static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
  1340. {
  1341. HLSContext *hls = s->priv_data;
  1342. AVFormatContext *oc = NULL;
  1343. AVStream *st = s->streams[pkt->stream_index];
  1344. int64_t end_pts = hls->recording_time * hls->number;
  1345. int is_ref_pkt = 1;
  1346. int ret = 0, can_split = 1;
  1347. int stream_index = 0;
  1348. if (hls->sequence - hls->nb_entries > hls->start_sequence && hls->init_time > 0) {
  1349. /* reset end_pts, hls->recording_time at end of the init hls list */
  1350. int init_list_dur = hls->init_time * hls->nb_entries * AV_TIME_BASE;
  1351. int after_init_list_dur = (hls->sequence - hls->nb_entries ) * hls->time * AV_TIME_BASE;
  1352. hls->recording_time = hls->time * AV_TIME_BASE;
  1353. end_pts = init_list_dur + after_init_list_dur ;
  1354. }
  1355. if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
  1356. oc = hls->vtt_avf;
  1357. stream_index = 0;
  1358. } else {
  1359. oc = hls->avf;
  1360. stream_index = pkt->stream_index;
  1361. }
  1362. if (hls->start_pts == AV_NOPTS_VALUE) {
  1363. hls->start_pts = pkt->pts;
  1364. hls->end_pts = pkt->pts;
  1365. }
  1366. if (hls->has_video) {
  1367. can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1368. ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
  1369. is_ref_pkt = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
  1370. }
  1371. if (pkt->pts == AV_NOPTS_VALUE)
  1372. is_ref_pkt = can_split = 0;
  1373. if (is_ref_pkt) {
  1374. if (hls->new_start) {
  1375. hls->new_start = 0;
  1376. hls->duration = (double)(pkt->pts - hls->end_pts)
  1377. * st->time_base.num / st->time_base.den;
  1378. hls->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
  1379. } else {
  1380. if (pkt->duration) {
  1381. hls->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
  1382. } else {
  1383. av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
  1384. hls->duration = (double)(pkt->pts - hls->end_pts) * st->time_base.num / st->time_base.den;
  1385. }
  1386. }
  1387. }
  1388. if (hls->fmp4_init_mode || can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
  1389. end_pts, AV_TIME_BASE_Q) >= 0) {
  1390. int64_t new_start_pos;
  1391. char *old_filename = av_strdup(hls->avf->filename);
  1392. int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
  1393. if (!old_filename) {
  1394. return AVERROR(ENOMEM);
  1395. }
  1396. av_write_frame(hls->avf, NULL); /* Flush any buffered data */
  1397. new_start_pos = avio_tell(hls->avf->pb);
  1398. hls->size = new_start_pos - hls->start_pos;
  1399. if (!byterange_mode) {
  1400. ff_format_io_close(s, &oc->pb);
  1401. if (hls->vtt_avf) {
  1402. ff_format_io_close(s, &hls->vtt_avf->pb);
  1403. }
  1404. }
  1405. if ((hls->flags & HLS_TEMP_FILE) && oc->filename[0]) {
  1406. if (!(hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size <= 0))
  1407. if ((hls->avf->oformat->priv_class && hls->avf->priv_data) && hls->segment_type != SEGMENT_TYPE_FMP4)
  1408. av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
  1409. hls_rename_temp_file(s, oc);
  1410. }
  1411. if (hls->fmp4_init_mode) {
  1412. hls->number--;
  1413. }
  1414. if (!hls->fmp4_init_mode)
  1415. ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
  1416. hls->start_pos = new_start_pos;
  1417. if (ret < 0) {
  1418. av_free(old_filename);
  1419. return ret;
  1420. }
  1421. hls->end_pts = pkt->pts;
  1422. hls->duration = 0;
  1423. hls->fmp4_init_mode = 0;
  1424. if (hls->flags & HLS_SINGLE_FILE) {
  1425. hls->number++;
  1426. } else if (hls->max_seg_size > 0) {
  1427. if (hls->start_pos >= hls->max_seg_size) {
  1428. hls->sequence++;
  1429. sls_flag_file_rename(hls, old_filename);
  1430. ret = hls_start(s);
  1431. hls->start_pos = 0;
  1432. /* When split segment by byte, the duration is short than hls_time,
  1433. * so it is not enough one segment duration as hls_time, */
  1434. hls->number--;
  1435. }
  1436. hls->number++;
  1437. } else {
  1438. sls_flag_file_rename(hls, old_filename);
  1439. ret = hls_start(s);
  1440. }
  1441. av_free(old_filename);
  1442. if (ret < 0) {
  1443. return ret;
  1444. }
  1445. if ((ret = hls_window(s, 0)) < 0) {
  1446. return ret;
  1447. }
  1448. }
  1449. ret = ff_write_chained(oc, stream_index, pkt, s, 0);
  1450. return ret;
  1451. }
  1452. static int hls_write_trailer(struct AVFormatContext *s)
  1453. {
  1454. HLSContext *hls = s->priv_data;
  1455. AVFormatContext *oc = hls->avf;
  1456. AVFormatContext *vtt_oc = hls->vtt_avf;
  1457. char *old_filename = av_strdup(hls->avf->filename);
  1458. if (!old_filename) {
  1459. return AVERROR(ENOMEM);
  1460. }
  1461. av_write_trailer(oc);
  1462. if (oc->pb) {
  1463. hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
  1464. ff_format_io_close(s, &oc->pb);
  1465. if ((hls->flags & HLS_TEMP_FILE) && oc->filename[0]) {
  1466. hls_rename_temp_file(s, oc);
  1467. }
  1468. /* after av_write_trailer, then duration + 1 duration per packet */
  1469. hls_append_segment(s, hls, hls->duration + hls->dpp, hls->start_pos, hls->size);
  1470. }
  1471. sls_flag_file_rename(hls, old_filename);
  1472. if (vtt_oc) {
  1473. if (vtt_oc->pb)
  1474. av_write_trailer(vtt_oc);
  1475. hls->size = avio_tell(hls->vtt_avf->pb) - hls->start_pos;
  1476. ff_format_io_close(s, &vtt_oc->pb);
  1477. }
  1478. av_freep(&hls->basename);
  1479. av_freep(&hls->key_basename);
  1480. avformat_free_context(oc);
  1481. hls->avf = NULL;
  1482. hls_window(s, 1);
  1483. if (vtt_oc) {
  1484. av_freep(&hls->vtt_basename);
  1485. av_freep(&hls->vtt_m3u8_name);
  1486. avformat_free_context(vtt_oc);
  1487. }
  1488. hls_free_segments(hls->segments);
  1489. hls_free_segments(hls->old_segments);
  1490. av_free(old_filename);
  1491. return 0;
  1492. }
  1493. #define OFFSET(x) offsetof(HLSContext, x)
  1494. #define E AV_OPT_FLAG_ENCODING_PARAM
  1495. static const AVOption options[] = {
  1496. {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
  1497. {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
  1498. {"hls_init_time", "set segment length in seconds at init list", OFFSET(init_time), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, FLT_MAX, E},
  1499. {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
  1500. {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1501. {"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},
  1502. #if FF_API_HLS_WRAP
  1503. {"hls_wrap", "set number after which the index wraps (will be deprecated)", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  1504. #endif
  1505. {"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},
  1506. {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1507. {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1508. {"hls_segment_size", "maximum size per segment file, (in bytes)", OFFSET(max_seg_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  1509. {"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},
  1510. {"hls_enc", "enable AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
  1511. {"hls_enc_key", "hex-coded 16 byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_STRING, .flags = E},
  1512. {"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},
  1513. {"hls_enc_iv", "hex-coded 16 byte initialization vector", OFFSET(iv), AV_OPT_TYPE_STRING, .flags = E},
  1514. {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1515. {"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"},
  1516. {"mpegts", "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX, E, "segment_type"},
  1517. {"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"},
  1518. {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename), AV_OPT_TYPE_STRING, {.str = "init.mp4"}, 0, 0, E},
  1519. {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
  1520. {"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"},
  1521. {"temp_file", "write segment to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX, E, "flags"},
  1522. {"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"},
  1523. {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, "flags"},
  1524. {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, "flags"},
  1525. {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, "flags"},
  1526. {"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"},
  1527. {"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"},
  1528. {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX, E, "flags"},
  1529. {"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"},
  1530. {"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"},
  1531. {"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"},
  1532. {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  1533. {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  1534. {"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" },
  1535. {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
  1536. {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
  1537. {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  1538. {"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_AS_FORMATTED_DATETIME, E, "start_sequence_source_type" },
  1539. {"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" },
  1540. {"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" },
  1541. {"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" },
  1542. { NULL },
  1543. };
  1544. static const AVClass hls_class = {
  1545. .class_name = "hls muxer",
  1546. .item_name = av_default_item_name,
  1547. .option = options,
  1548. .version = LIBAVUTIL_VERSION_INT,
  1549. };
  1550. AVOutputFormat ff_hls_muxer = {
  1551. .name = "hls",
  1552. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  1553. .extensions = "m3u8",
  1554. .priv_data_size = sizeof(HLSContext),
  1555. .audio_codec = AV_CODEC_ID_AAC,
  1556. .video_codec = AV_CODEC_ID_H264,
  1557. .subtitle_codec = AV_CODEC_ID_WEBVTT,
  1558. .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  1559. .write_header = hls_write_header,
  1560. .write_packet = hls_write_packet,
  1561. .write_trailer = hls_write_trailer,
  1562. .priv_class = &hls_class,
  1563. };