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.

1547 lines
56KB

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