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.

1448 lines
53KB

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