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.

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