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.

1040 lines
35KB

  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. #define KEYSIZE 16
  39. #define LINE_BUFFER_SIZE 1024
  40. typedef struct HLSSegment {
  41. char filename[1024];
  42. char sub_filename[1024];
  43. double duration; /* in seconds */
  44. int64_t pos;
  45. int64_t size;
  46. char key_uri[LINE_BUFFER_SIZE + 1];
  47. char iv_string[KEYSIZE*2 + 1];
  48. struct HLSSegment *next;
  49. } HLSSegment;
  50. typedef enum HLSFlags {
  51. // Generate a single media file and use byte ranges in the playlist.
  52. HLS_SINGLE_FILE = (1 << 0),
  53. HLS_DELETE_SEGMENTS = (1 << 1),
  54. HLS_ROUND_DURATIONS = (1 << 2),
  55. HLS_DISCONT_START = (1 << 3),
  56. HLS_OMIT_ENDLIST = (1 << 4),
  57. HLS_SPLIT_BY_TIME = (1 << 5),
  58. HLS_APPEND_LIST = (1 << 6),
  59. } HLSFlags;
  60. typedef enum {
  61. PLAYLIST_TYPE_NONE,
  62. PLAYLIST_TYPE_EVENT,
  63. PLAYLIST_TYPE_VOD,
  64. PLAYLIST_TYPE_NB,
  65. } PlaylistType;
  66. typedef struct HLSContext {
  67. const AVClass *class; // Class for private options.
  68. unsigned number;
  69. int64_t sequence;
  70. int64_t start_sequence;
  71. AVOutputFormat *oformat;
  72. AVOutputFormat *vtt_oformat;
  73. AVFormatContext *avf;
  74. AVFormatContext *vtt_avf;
  75. float time; // Set by a private option.
  76. float init_time; // Set by a private option.
  77. int max_nb_segments; // Set by a private option.
  78. int wrap; // Set by a private option.
  79. uint32_t flags; // enum HLSFlags
  80. uint32_t pl_type; // enum PlaylistType
  81. char *segment_filename;
  82. int use_localtime; ///< flag to expand filename with localtime
  83. int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
  84. int allowcache;
  85. int64_t recording_time;
  86. int has_video;
  87. int has_subtitle;
  88. int64_t start_pts;
  89. int64_t end_pts;
  90. double duration; // last segment duration computed so far, in seconds
  91. int64_t start_pos; // last segment starting position
  92. int64_t size; // last segment size
  93. int nb_entries;
  94. int discontinuity_set;
  95. HLSSegment *segments;
  96. HLSSegment *last_segment;
  97. HLSSegment *old_segments;
  98. char *basename;
  99. char *vtt_basename;
  100. char *vtt_m3u8_name;
  101. char *baseurl;
  102. char *format_options_str;
  103. char *vtt_format_options_str;
  104. char *subtitle_filename;
  105. AVDictionary *format_options;
  106. char *key_info_file;
  107. char key_file[LINE_BUFFER_SIZE + 1];
  108. char key_uri[LINE_BUFFER_SIZE + 1];
  109. char key_string[KEYSIZE*2 + 1];
  110. char iv_string[KEYSIZE*2 + 1];
  111. AVDictionary *vtt_format_options;
  112. char *method;
  113. } HLSContext;
  114. static int hls_delete_old_segments(HLSContext *hls) {
  115. HLSSegment *segment, *previous_segment = NULL;
  116. float playlist_duration = 0.0f;
  117. int ret = 0, path_size, sub_path_size;
  118. char *dirname = NULL, *p, *sub_path;
  119. char *path = NULL;
  120. segment = hls->segments;
  121. while (segment) {
  122. playlist_duration += segment->duration;
  123. segment = segment->next;
  124. }
  125. segment = hls->old_segments;
  126. while (segment) {
  127. playlist_duration -= segment->duration;
  128. previous_segment = segment;
  129. segment = previous_segment->next;
  130. if (playlist_duration <= -previous_segment->duration) {
  131. previous_segment->next = NULL;
  132. break;
  133. }
  134. }
  135. if (segment) {
  136. if (hls->segment_filename) {
  137. dirname = av_strdup(hls->segment_filename);
  138. } else {
  139. dirname = av_strdup(hls->avf->filename);
  140. }
  141. if (!dirname) {
  142. ret = AVERROR(ENOMEM);
  143. goto fail;
  144. }
  145. p = (char *)av_basename(dirname);
  146. *p = '\0';
  147. }
  148. while (segment) {
  149. av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
  150. segment->filename);
  151. path_size = strlen(dirname) + strlen(segment->filename) + 1;
  152. path = av_malloc(path_size);
  153. if (!path) {
  154. ret = AVERROR(ENOMEM);
  155. goto fail;
  156. }
  157. av_strlcpy(path, dirname, path_size);
  158. av_strlcat(path, segment->filename, path_size);
  159. if (unlink(path) < 0) {
  160. av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
  161. path, strerror(errno));
  162. }
  163. if (segment->sub_filename[0] != '\0') {
  164. sub_path_size = strlen(dirname) + strlen(segment->sub_filename) + 1;
  165. sub_path = av_malloc(sub_path_size);
  166. if (!sub_path) {
  167. ret = AVERROR(ENOMEM);
  168. goto fail;
  169. }
  170. av_strlcpy(sub_path, dirname, sub_path_size);
  171. av_strlcat(sub_path, segment->sub_filename, sub_path_size);
  172. if (unlink(sub_path) < 0) {
  173. av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
  174. sub_path, strerror(errno));
  175. }
  176. av_free(sub_path);
  177. }
  178. av_freep(&path);
  179. previous_segment = segment;
  180. segment = previous_segment->next;
  181. av_free(previous_segment);
  182. }
  183. fail:
  184. av_free(path);
  185. av_free(dirname);
  186. return ret;
  187. }
  188. static int hls_encryption_start(AVFormatContext *s)
  189. {
  190. HLSContext *hls = s->priv_data;
  191. int ret;
  192. AVIOContext *pb;
  193. uint8_t key[KEYSIZE];
  194. if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
  195. av_log(hls, AV_LOG_ERROR,
  196. "error opening key info file %s\n", hls->key_info_file);
  197. return ret;
  198. }
  199. ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
  200. hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
  201. ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
  202. hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
  203. ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
  204. hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
  205. ff_format_io_close(s, &pb);
  206. if (!*hls->key_uri) {
  207. av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
  208. return AVERROR(EINVAL);
  209. }
  210. if (!*hls->key_file) {
  211. av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
  212. return AVERROR(EINVAL);
  213. }
  214. if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
  215. av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
  216. return ret;
  217. }
  218. ret = avio_read(pb, key, sizeof(key));
  219. ff_format_io_close(s, &pb);
  220. if (ret != sizeof(key)) {
  221. av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
  222. if (ret >= 0 || ret == AVERROR_EOF)
  223. ret = AVERROR(EINVAL);
  224. return ret;
  225. }
  226. ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
  227. return 0;
  228. }
  229. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  230. {
  231. int len = ff_get_line(s, buf, maxlen);
  232. while (len > 0 && av_isspace(buf[len - 1]))
  233. buf[--len] = '\0';
  234. return len;
  235. }
  236. static int hls_mux_init(AVFormatContext *s)
  237. {
  238. HLSContext *hls = s->priv_data;
  239. AVFormatContext *oc;
  240. AVFormatContext *vtt_oc = NULL;
  241. int i, ret;
  242. ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
  243. if (ret < 0)
  244. return ret;
  245. oc = hls->avf;
  246. oc->oformat = hls->oformat;
  247. oc->interrupt_callback = s->interrupt_callback;
  248. oc->max_delay = s->max_delay;
  249. oc->opaque = s->opaque;
  250. oc->io_open = s->io_open;
  251. oc->io_close = s->io_close;
  252. av_dict_copy(&oc->metadata, s->metadata, 0);
  253. if(hls->vtt_oformat) {
  254. ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);
  255. if (ret < 0)
  256. return ret;
  257. vtt_oc = hls->vtt_avf;
  258. vtt_oc->oformat = hls->vtt_oformat;
  259. av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
  260. }
  261. for (i = 0; i < s->nb_streams; i++) {
  262. AVStream *st;
  263. AVFormatContext *loc;
  264. if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  265. loc = vtt_oc;
  266. else
  267. loc = oc;
  268. if (!(st = avformat_new_stream(loc, NULL)))
  269. return AVERROR(ENOMEM);
  270. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  271. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  272. st->time_base = s->streams[i]->time_base;
  273. }
  274. hls->start_pos = 0;
  275. return 0;
  276. }
  277. /* Create a new segment and append it to the segment list */
  278. static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, double duration,
  279. int64_t pos, int64_t size)
  280. {
  281. HLSSegment *en = av_malloc(sizeof(*en));
  282. char *tmp, *p;
  283. const char *pl_dir, *filename;
  284. int ret;
  285. if (!en)
  286. return AVERROR(ENOMEM);
  287. filename = av_basename(hls->avf->filename);
  288. if (hls->use_localtime_mkdir) {
  289. /* Possibly prefix with mkdir'ed subdir, if playlist share same
  290. * base path. */
  291. tmp = av_strdup(s->filename);
  292. if (!tmp) {
  293. av_free(en);
  294. return AVERROR(ENOMEM);
  295. }
  296. pl_dir = av_dirname(tmp);
  297. p = hls->avf->filename;
  298. if (strstr(p, pl_dir) == p)
  299. filename = hls->avf->filename + strlen(pl_dir) + 1;
  300. av_free(tmp);
  301. }
  302. av_strlcpy(en->filename, filename, sizeof(en->filename));
  303. if(hls->has_subtitle)
  304. av_strlcpy(en->sub_filename, av_basename(hls->vtt_avf->filename), sizeof(en->sub_filename));
  305. else
  306. en->sub_filename[0] = '\0';
  307. en->duration = duration;
  308. en->pos = pos;
  309. en->size = size;
  310. en->next = NULL;
  311. if (hls->key_info_file) {
  312. av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
  313. av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
  314. }
  315. if (!hls->segments)
  316. hls->segments = en;
  317. else
  318. hls->last_segment->next = en;
  319. hls->last_segment = en;
  320. // EVENT or VOD playlists imply sliding window cannot be used
  321. if (hls->pl_type != PLAYLIST_TYPE_NONE)
  322. hls->max_nb_segments = 0;
  323. if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
  324. en = hls->segments;
  325. hls->segments = en->next;
  326. if (en && hls->flags & HLS_DELETE_SEGMENTS &&
  327. !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
  328. en->next = hls->old_segments;
  329. hls->old_segments = en;
  330. if ((ret = hls_delete_old_segments(hls)) < 0)
  331. return ret;
  332. } else
  333. av_free(en);
  334. } else
  335. hls->nb_entries++;
  336. hls->sequence++;
  337. return 0;
  338. }
  339. static int parse_playlist(AVFormatContext *s, const char *url)
  340. {
  341. HLSContext *hls = s->priv_data;
  342. AVIOContext *in;
  343. int ret = 0, is_segment = 0;
  344. int64_t new_start_pos;
  345. char line[1024];
  346. const char *ptr;
  347. if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
  348. &s->interrupt_callback, NULL,
  349. s->protocol_whitelist, s->protocol_blacklist)) < 0)
  350. return ret;
  351. read_chomp_line(in, line, sizeof(line));
  352. if (strcmp(line, "#EXTM3U")) {
  353. ret = AVERROR_INVALIDDATA;
  354. goto fail;
  355. }
  356. while (!avio_feof(in)) {
  357. read_chomp_line(in, line, sizeof(line));
  358. if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  359. hls->sequence = atoi(ptr);
  360. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  361. is_segment = 1;
  362. hls->duration = atof(ptr);
  363. } else if (av_strstart(line, "#", NULL)) {
  364. continue;
  365. } else if (line[0]) {
  366. if (is_segment) {
  367. is_segment = 0;
  368. new_start_pos = avio_tell(hls->avf->pb);
  369. hls->size = new_start_pos - hls->start_pos;
  370. av_strlcpy(hls->avf->filename, line, sizeof(line));
  371. ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
  372. if (ret < 0)
  373. goto fail;
  374. hls->start_pos = new_start_pos;
  375. }
  376. }
  377. }
  378. fail:
  379. avio_close(in);
  380. return ret;
  381. }
  382. static void hls_free_segments(HLSSegment *p)
  383. {
  384. HLSSegment *en;
  385. while(p) {
  386. en = p;
  387. p = p->next;
  388. av_free(en);
  389. }
  390. }
  391. static void set_http_options(AVDictionary **options, HLSContext *c)
  392. {
  393. if (c->method)
  394. av_dict_set(options, "method", c->method, 0);
  395. }
  396. static int hls_window(AVFormatContext *s, int last)
  397. {
  398. HLSContext *hls = s->priv_data;
  399. HLSSegment *en;
  400. int target_duration = 0;
  401. int ret = 0;
  402. AVIOContext *out = NULL;
  403. AVIOContext *sub_out = NULL;
  404. char temp_filename[1024];
  405. int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
  406. int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
  407. const char *proto = avio_find_protocol_name(s->filename);
  408. int use_rename = proto && !strcmp(proto, "file");
  409. static unsigned warned_non_file;
  410. char *key_uri = NULL;
  411. char *iv_string = NULL;
  412. AVDictionary *options = NULL;
  413. if (!use_rename && !warned_non_file++)
  414. av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporarly partial files\n");
  415. set_http_options(&options, hls);
  416. snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
  417. if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &options)) < 0)
  418. goto fail;
  419. for (en = hls->segments; en; en = en->next) {
  420. if (target_duration < en->duration)
  421. target_duration = ceil(en->duration);
  422. }
  423. hls->discontinuity_set = 0;
  424. avio_printf(out, "#EXTM3U\n");
  425. avio_printf(out, "#EXT-X-VERSION:%d\n", version);
  426. if (hls->allowcache == 0 || hls->allowcache == 1) {
  427. avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  428. }
  429. avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
  430. avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  431. if (hls->pl_type == PLAYLIST_TYPE_EVENT) {
  432. avio_printf(out, "#EXT-X-PLAYLIST-TYPE:EVENT\n");
  433. } else if (hls->pl_type == PLAYLIST_TYPE_VOD) {
  434. avio_printf(out, "#EXT-X-PLAYLIST-TYPE:VOD\n");
  435. }
  436. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
  437. sequence);
  438. if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && hls->discontinuity_set==0 ){
  439. avio_printf(out, "#EXT-X-DISCONTINUITY\n");
  440. hls->discontinuity_set = 1;
  441. }
  442. for (en = hls->segments; en; en = en->next) {
  443. if (hls->key_info_file && (!key_uri || strcmp(en->key_uri, key_uri) ||
  444. av_strcasecmp(en->iv_string, iv_string))) {
  445. avio_printf(out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
  446. if (*en->iv_string)
  447. avio_printf(out, ",IV=0x%s", en->iv_string);
  448. avio_printf(out, "\n");
  449. key_uri = en->key_uri;
  450. iv_string = en->iv_string;
  451. }
  452. if (hls->flags & HLS_ROUND_DURATIONS)
  453. avio_printf(out, "#EXTINF:%ld,\n", lrint(en->duration));
  454. else
  455. avio_printf(out, "#EXTINF:%f,\n", en->duration);
  456. if (hls->flags & HLS_SINGLE_FILE)
  457. avio_printf(out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
  458. en->size, en->pos);
  459. if (hls->baseurl)
  460. avio_printf(out, "%s", hls->baseurl);
  461. avio_printf(out, "%s\n", en->filename);
  462. }
  463. if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
  464. avio_printf(out, "#EXT-X-ENDLIST\n");
  465. if( hls->vtt_m3u8_name ) {
  466. if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)
  467. goto fail;
  468. avio_printf(sub_out, "#EXTM3U\n");
  469. avio_printf(sub_out, "#EXT-X-VERSION:%d\n", version);
  470. if (hls->allowcache == 0 || hls->allowcache == 1) {
  471. avio_printf(sub_out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  472. }
  473. avio_printf(sub_out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
  474. avio_printf(sub_out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  475. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
  476. sequence);
  477. for (en = hls->segments; en; en = en->next) {
  478. avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);
  479. if (hls->flags & HLS_SINGLE_FILE)
  480. avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
  481. en->size, en->pos);
  482. if (hls->baseurl)
  483. avio_printf(sub_out, "%s", hls->baseurl);
  484. avio_printf(sub_out, "%s\n", en->sub_filename);
  485. }
  486. if (last)
  487. avio_printf(sub_out, "#EXT-X-ENDLIST\n");
  488. }
  489. fail:
  490. av_dict_free(&options);
  491. ff_format_io_close(s, &out);
  492. ff_format_io_close(s, &sub_out);
  493. if (ret >= 0 && use_rename)
  494. ff_rename(temp_filename, s->filename, s);
  495. return ret;
  496. }
  497. static int hls_start(AVFormatContext *s)
  498. {
  499. HLSContext *c = s->priv_data;
  500. AVFormatContext *oc = c->avf;
  501. AVFormatContext *vtt_oc = c->vtt_avf;
  502. AVDictionary *options = NULL;
  503. char *filename, iv_string[KEYSIZE*2 + 1];
  504. int err = 0;
  505. if (c->flags & HLS_SINGLE_FILE) {
  506. av_strlcpy(oc->filename, c->basename,
  507. sizeof(oc->filename));
  508. if (c->vtt_basename)
  509. av_strlcpy(vtt_oc->filename, c->vtt_basename,
  510. sizeof(vtt_oc->filename));
  511. } else {
  512. if (c->use_localtime) {
  513. time_t now0;
  514. struct tm *tm, tmpbuf;
  515. time(&now0);
  516. tm = localtime_r(&now0, &tmpbuf);
  517. if (!strftime(oc->filename, sizeof(oc->filename), c->basename, tm)) {
  518. av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
  519. return AVERROR(EINVAL);
  520. }
  521. if (c->use_localtime_mkdir) {
  522. const char *dir;
  523. char *fn_copy = av_strdup(oc->filename);
  524. if (!fn_copy) {
  525. return AVERROR(ENOMEM);
  526. }
  527. dir = av_dirname(fn_copy);
  528. if (mkdir(dir, 0777) == -1 && errno != EEXIST) {
  529. av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
  530. av_free(fn_copy);
  531. return AVERROR(errno);
  532. }
  533. av_free(fn_copy);
  534. }
  535. } else if (av_get_frame_filename2(oc->filename, sizeof(oc->filename),
  536. c->basename, c->wrap ? c->sequence % c->wrap : c->sequence,
  537. AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0) {
  538. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try use -use_localtime 1 with it\n", c->basename);
  539. return AVERROR(EINVAL);
  540. }
  541. if( c->vtt_basename) {
  542. if (av_get_frame_filename2(vtt_oc->filename, sizeof(vtt_oc->filename),
  543. c->vtt_basename, c->wrap ? c->sequence % c->wrap : c->sequence,
  544. AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0) {
  545. av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->vtt_basename);
  546. return AVERROR(EINVAL);
  547. }
  548. }
  549. }
  550. c->number++;
  551. set_http_options(&options, c);
  552. if (c->key_info_file) {
  553. if ((err = hls_encryption_start(s)) < 0)
  554. goto fail;
  555. if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
  556. < 0)
  557. goto fail;
  558. err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
  559. if (!err)
  560. snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, c->sequence);
  561. if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
  562. goto fail;
  563. filename = av_asprintf("crypto:%s", oc->filename);
  564. if (!filename) {
  565. err = AVERROR(ENOMEM);
  566. goto fail;
  567. }
  568. err = s->io_open(s, &oc->pb, filename, AVIO_FLAG_WRITE, &options);
  569. av_free(filename);
  570. av_dict_free(&options);
  571. if (err < 0)
  572. return err;
  573. } else
  574. if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
  575. goto fail;
  576. if (c->vtt_basename) {
  577. set_http_options(&options, c);
  578. if ((err = s->io_open(s, &vtt_oc->pb, vtt_oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
  579. goto fail;
  580. }
  581. av_dict_free(&options);
  582. /* We only require one PAT/PMT per segment. */
  583. if (oc->oformat->priv_class && oc->priv_data) {
  584. char period[21];
  585. snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
  586. av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
  587. av_opt_set(oc->priv_data, "sdt_period", period, 0);
  588. av_opt_set(oc->priv_data, "pat_period", period, 0);
  589. }
  590. if (c->vtt_basename) {
  591. err = avformat_write_header(vtt_oc,NULL);
  592. if (err < 0)
  593. return err;
  594. }
  595. return 0;
  596. fail:
  597. av_dict_free(&options);
  598. return err;
  599. }
  600. static int hls_write_header(AVFormatContext *s)
  601. {
  602. HLSContext *hls = s->priv_data;
  603. int ret, i;
  604. char *p;
  605. const char *pattern = "%d.ts";
  606. const char *pattern_localtime_fmt = "-%s.ts";
  607. const char *vtt_pattern = "%d.vtt";
  608. AVDictionary *options = NULL;
  609. int basename_size;
  610. int vtt_basename_size;
  611. hls->sequence = hls->start_sequence;
  612. hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
  613. hls->start_pts = AV_NOPTS_VALUE;
  614. if (hls->format_options_str) {
  615. ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
  616. if (ret < 0) {
  617. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
  618. goto fail;
  619. }
  620. }
  621. for (i = 0; i < s->nb_streams; i++) {
  622. hls->has_video +=
  623. s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
  624. hls->has_subtitle +=
  625. s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
  626. }
  627. if (hls->has_video > 1)
  628. av_log(s, AV_LOG_WARNING,
  629. "More than a single video stream present, "
  630. "expect issues decoding it.\n");
  631. hls->oformat = av_guess_format("mpegts", NULL, NULL);
  632. if (!hls->oformat) {
  633. ret = AVERROR_MUXER_NOT_FOUND;
  634. goto fail;
  635. }
  636. if(hls->has_subtitle) {
  637. hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
  638. if (!hls->oformat) {
  639. ret = AVERROR_MUXER_NOT_FOUND;
  640. goto fail;
  641. }
  642. }
  643. if (hls->segment_filename) {
  644. hls->basename = av_strdup(hls->segment_filename);
  645. if (!hls->basename) {
  646. ret = AVERROR(ENOMEM);
  647. goto fail;
  648. }
  649. } else {
  650. if (hls->flags & HLS_SINGLE_FILE)
  651. pattern = ".ts";
  652. if (hls->use_localtime) {
  653. basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;
  654. } else {
  655. basename_size = strlen(s->filename) + strlen(pattern) + 1;
  656. }
  657. hls->basename = av_malloc(basename_size);
  658. if (!hls->basename) {
  659. ret = AVERROR(ENOMEM);
  660. goto fail;
  661. }
  662. av_strlcpy(hls->basename, s->filename, basename_size);
  663. p = strrchr(hls->basename, '.');
  664. if (p)
  665. *p = '\0';
  666. if (hls->use_localtime) {
  667. av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);
  668. } else {
  669. av_strlcat(hls->basename, pattern, basename_size);
  670. }
  671. }
  672. if(hls->has_subtitle) {
  673. if (hls->flags & HLS_SINGLE_FILE)
  674. vtt_pattern = ".vtt";
  675. vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1;
  676. hls->vtt_basename = av_malloc(vtt_basename_size);
  677. if (!hls->vtt_basename) {
  678. ret = AVERROR(ENOMEM);
  679. goto fail;
  680. }
  681. hls->vtt_m3u8_name = av_malloc(vtt_basename_size);
  682. if (!hls->vtt_m3u8_name ) {
  683. ret = AVERROR(ENOMEM);
  684. goto fail;
  685. }
  686. av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);
  687. p = strrchr(hls->vtt_basename, '.');
  688. if (p)
  689. *p = '\0';
  690. if( hls->subtitle_filename ) {
  691. strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);
  692. } else {
  693. strcpy(hls->vtt_m3u8_name, hls->vtt_basename);
  694. av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
  695. }
  696. av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);
  697. }
  698. if ((ret = hls_mux_init(s)) < 0)
  699. goto fail;
  700. if (hls->flags & HLS_APPEND_LIST) {
  701. parse_playlist(s, s->filename);
  702. if (hls->init_time > 0) {
  703. av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
  704. " hls_init_time value will have no effect\n");
  705. hls->init_time = 0;
  706. hls->recording_time = hls->time * AV_TIME_BASE;
  707. }
  708. }
  709. if ((ret = hls_start(s)) < 0)
  710. goto fail;
  711. av_dict_copy(&options, hls->format_options, 0);
  712. ret = avformat_write_header(hls->avf, &options);
  713. if (av_dict_count(options)) {
  714. av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
  715. ret = AVERROR(EINVAL);
  716. goto fail;
  717. }
  718. //av_assert0(s->nb_streams == hls->avf->nb_streams);
  719. for (i = 0; i < s->nb_streams; i++) {
  720. AVStream *inner_st;
  721. AVStream *outer_st = s->streams[i];
  722. if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
  723. inner_st = hls->avf->streams[i];
  724. else if (hls->vtt_avf)
  725. inner_st = hls->vtt_avf->streams[0];
  726. else {
  727. /* We have a subtitle stream, when the user does not want one */
  728. inner_st = NULL;
  729. continue;
  730. }
  731. avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
  732. }
  733. fail:
  734. av_dict_free(&options);
  735. if (ret < 0) {
  736. av_freep(&hls->basename);
  737. av_freep(&hls->vtt_basename);
  738. if (hls->avf)
  739. avformat_free_context(hls->avf);
  740. if (hls->vtt_avf)
  741. avformat_free_context(hls->vtt_avf);
  742. }
  743. return ret;
  744. }
  745. static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
  746. {
  747. HLSContext *hls = s->priv_data;
  748. AVFormatContext *oc = NULL;
  749. AVStream *st = s->streams[pkt->stream_index];
  750. int64_t end_pts = hls->recording_time * hls->number;
  751. int is_ref_pkt = 1;
  752. int ret, can_split = 1;
  753. int stream_index = 0;
  754. if (hls->sequence - hls->nb_entries > hls->start_sequence && hls->init_time > 0) {
  755. /* reset end_pts, hls->recording_time at end of the init hls list */
  756. int init_list_dur = hls->init_time * hls->nb_entries * AV_TIME_BASE;
  757. int after_init_list_dur = (hls->sequence - hls->nb_entries ) * hls->time * AV_TIME_BASE;
  758. hls->recording_time = hls->time * AV_TIME_BASE;
  759. end_pts = init_list_dur + after_init_list_dur ;
  760. }
  761. if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
  762. oc = hls->vtt_avf;
  763. stream_index = 0;
  764. } else {
  765. oc = hls->avf;
  766. stream_index = pkt->stream_index;
  767. }
  768. if (hls->start_pts == AV_NOPTS_VALUE) {
  769. hls->start_pts = pkt->pts;
  770. hls->end_pts = pkt->pts;
  771. }
  772. if (hls->has_video) {
  773. can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  774. ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
  775. is_ref_pkt = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
  776. }
  777. if (pkt->pts == AV_NOPTS_VALUE)
  778. is_ref_pkt = can_split = 0;
  779. if (is_ref_pkt)
  780. hls->duration = (double)(pkt->pts - hls->end_pts)
  781. * st->time_base.num / st->time_base.den;
  782. if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
  783. end_pts, AV_TIME_BASE_Q) >= 0) {
  784. int64_t new_start_pos;
  785. av_write_frame(oc, NULL); /* Flush any buffered data */
  786. new_start_pos = avio_tell(hls->avf->pb);
  787. hls->size = new_start_pos - hls->start_pos;
  788. ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
  789. hls->start_pos = new_start_pos;
  790. if (ret < 0)
  791. return ret;
  792. hls->end_pts = pkt->pts;
  793. hls->duration = 0;
  794. if (hls->flags & HLS_SINGLE_FILE) {
  795. if (hls->avf->oformat->priv_class && hls->avf->priv_data)
  796. av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
  797. hls->number++;
  798. } else {
  799. ff_format_io_close(s, &oc->pb);
  800. if (hls->vtt_avf)
  801. ff_format_io_close(s, &hls->vtt_avf->pb);
  802. ret = hls_start(s);
  803. }
  804. if (ret < 0)
  805. return ret;
  806. if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE )
  807. oc = hls->vtt_avf;
  808. else
  809. oc = hls->avf;
  810. if ((ret = hls_window(s, 0)) < 0)
  811. return ret;
  812. }
  813. ret = ff_write_chained(oc, stream_index, pkt, s, 0);
  814. return ret;
  815. }
  816. static int hls_write_trailer(struct AVFormatContext *s)
  817. {
  818. HLSContext *hls = s->priv_data;
  819. AVFormatContext *oc = hls->avf;
  820. AVFormatContext *vtt_oc = hls->vtt_avf;
  821. av_write_trailer(oc);
  822. if (oc->pb) {
  823. hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
  824. ff_format_io_close(s, &oc->pb);
  825. hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
  826. }
  827. if (vtt_oc) {
  828. if (vtt_oc->pb)
  829. av_write_trailer(vtt_oc);
  830. hls->size = avio_tell(hls->vtt_avf->pb) - hls->start_pos;
  831. ff_format_io_close(s, &vtt_oc->pb);
  832. }
  833. av_freep(&hls->basename);
  834. avformat_free_context(oc);
  835. hls->avf = NULL;
  836. hls_window(s, 1);
  837. if (vtt_oc) {
  838. av_freep(&hls->vtt_basename);
  839. av_freep(&hls->vtt_m3u8_name);
  840. avformat_free_context(vtt_oc);
  841. }
  842. hls_free_segments(hls->segments);
  843. hls_free_segments(hls->old_segments);
  844. return 0;
  845. }
  846. #define OFFSET(x) offsetof(HLSContext, x)
  847. #define E AV_OPT_FLAG_ENCODING_PARAM
  848. static const AVOption options[] = {
  849. {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
  850. {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
  851. {"hls_init_time", "set segment length in seconds at init list", OFFSET(init_time), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, FLT_MAX, E},
  852. {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
  853. {"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},
  854. {"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},
  855. {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  856. {"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},
  857. {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  858. {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  859. {"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},
  860. {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  861. {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
  862. {"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"},
  863. {"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"},
  864. {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, "flags"},
  865. {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, "flags"},
  866. {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, "flags"},
  867. {"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"},
  868. {"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"},
  869. {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  870. {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
  871. {"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" },
  872. {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
  873. {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
  874. {"method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  875. { NULL },
  876. };
  877. static const AVClass hls_class = {
  878. .class_name = "hls muxer",
  879. .item_name = av_default_item_name,
  880. .option = options,
  881. .version = LIBAVUTIL_VERSION_INT,
  882. };
  883. AVOutputFormat ff_hls_muxer = {
  884. .name = "hls",
  885. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  886. .extensions = "m3u8",
  887. .priv_data_size = sizeof(HLSContext),
  888. .audio_codec = AV_CODEC_ID_AAC,
  889. .video_codec = AV_CODEC_ID_H264,
  890. .subtitle_codec = AV_CODEC_ID_WEBVTT,
  891. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  892. .write_header = hls_write_header,
  893. .write_packet = hls_write_packet,
  894. .write_trailer = hls_write_trailer,
  895. .priv_class = &hls_class,
  896. };