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.

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