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.

1816 lines
65KB

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