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.

905 lines
30KB

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