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.

1454 lines
54KB

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