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.

1849 lines
67KB

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