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.

958 lines
32KB

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