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.

647 lines
22KB

  1. /*
  2. * Live smooth streaming fragmenter
  3. * Copyright (c) 2012 Martin Storsjo
  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. #if HAVE_UNISTD_H
  24. #include <unistd.h>
  25. #endif
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "os_support.h"
  29. #include "avc.h"
  30. #include "url.h"
  31. #include "isom.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/avstring.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/intreadwrite.h"
  36. typedef struct {
  37. char file[1024];
  38. char infofile[1024];
  39. int64_t start_time, duration;
  40. int n;
  41. int64_t start_pos, size;
  42. } Fragment;
  43. typedef struct {
  44. AVFormatContext *ctx;
  45. int ctx_inited;
  46. char dirname[1024];
  47. uint8_t iobuf[32768];
  48. URLContext *out; // Current output stream where all output is written
  49. URLContext *out2; // Auxiliary output stream where all output is also written
  50. URLContext *tail_out; // The actual main output stream, if we're currently seeked back to write elsewhere
  51. int64_t tail_pos, cur_pos, cur_start_pos;
  52. int packets_written;
  53. const char *stream_type_tag;
  54. int nb_fragments, fragments_size, fragment_index;
  55. Fragment **fragments;
  56. const char *fourcc;
  57. char *private_str;
  58. int packet_size;
  59. int audio_tag;
  60. } OutputStream;
  61. typedef struct {
  62. const AVClass *class; /* Class for private options. */
  63. int window_size;
  64. int extra_window_size;
  65. int lookahead_count;
  66. int min_frag_duration;
  67. int remove_at_exit;
  68. OutputStream *streams;
  69. int has_video, has_audio;
  70. int nb_fragments;
  71. } SmoothStreamingContext;
  72. static int ism_write(void *opaque, uint8_t *buf, int buf_size)
  73. {
  74. OutputStream *os = opaque;
  75. if (os->out)
  76. ffurl_write(os->out, buf, buf_size);
  77. if (os->out2)
  78. ffurl_write(os->out2, buf, buf_size);
  79. os->cur_pos += buf_size;
  80. if (os->cur_pos >= os->tail_pos)
  81. os->tail_pos = os->cur_pos;
  82. return buf_size;
  83. }
  84. static int64_t ism_seek(void *opaque, int64_t offset, int whence)
  85. {
  86. OutputStream *os = opaque;
  87. int i;
  88. if (whence != SEEK_SET)
  89. return AVERROR(ENOSYS);
  90. if (os->tail_out) {
  91. if (os->out) {
  92. ffurl_close(os->out);
  93. }
  94. if (os->out2) {
  95. ffurl_close(os->out2);
  96. }
  97. os->out = os->tail_out;
  98. os->out2 = NULL;
  99. os->tail_out = NULL;
  100. }
  101. if (offset >= os->cur_start_pos) {
  102. if (os->out)
  103. ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
  104. os->cur_pos = offset;
  105. return offset;
  106. }
  107. for (i = os->nb_fragments - 1; i >= 0; i--) {
  108. Fragment *frag = os->fragments[i];
  109. if (offset >= frag->start_pos && offset < frag->start_pos + frag->size) {
  110. int ret;
  111. AVDictionary *opts = NULL;
  112. os->tail_out = os->out;
  113. av_dict_set(&opts, "truncate", "0", 0);
  114. ret = ffurl_open(&os->out, frag->file, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
  115. av_dict_free(&opts);
  116. if (ret < 0) {
  117. os->out = os->tail_out;
  118. os->tail_out = NULL;
  119. return ret;
  120. }
  121. av_dict_set(&opts, "truncate", "0", 0);
  122. ffurl_open(&os->out2, frag->infofile, AVIO_FLAG_READ_WRITE, &os->ctx->interrupt_callback, &opts);
  123. av_dict_free(&opts);
  124. ffurl_seek(os->out, offset - frag->start_pos, SEEK_SET);
  125. if (os->out2)
  126. ffurl_seek(os->out2, offset - frag->start_pos, SEEK_SET);
  127. os->cur_pos = offset;
  128. return offset;
  129. }
  130. }
  131. return AVERROR(EIO);
  132. }
  133. static void get_private_data(OutputStream *os)
  134. {
  135. AVCodecContext *codec = os->ctx->streams[0]->codec;
  136. uint8_t *ptr = codec->extradata;
  137. int size = codec->extradata_size;
  138. int i;
  139. if (codec->codec_id == AV_CODEC_ID_H264) {
  140. ff_avc_write_annexb_extradata(ptr, &ptr, &size);
  141. if (!ptr)
  142. ptr = codec->extradata;
  143. }
  144. if (!ptr)
  145. return;
  146. os->private_str = av_mallocz(2*size + 1);
  147. if (!os->private_str)
  148. goto fail;
  149. for (i = 0; i < size; i++)
  150. snprintf(&os->private_str[2*i], 3, "%02x", ptr[i]);
  151. fail:
  152. if (ptr != codec->extradata)
  153. av_free(ptr);
  154. }
  155. static void ism_free(AVFormatContext *s)
  156. {
  157. SmoothStreamingContext *c = s->priv_data;
  158. int i, j;
  159. if (!c->streams)
  160. return;
  161. for (i = 0; i < s->nb_streams; i++) {
  162. OutputStream *os = &c->streams[i];
  163. ffurl_close(os->out);
  164. ffurl_close(os->out2);
  165. ffurl_close(os->tail_out);
  166. os->out = os->out2 = os->tail_out = NULL;
  167. if (os->ctx && os->ctx_inited)
  168. av_write_trailer(os->ctx);
  169. if (os->ctx && os->ctx->pb)
  170. av_free(os->ctx->pb);
  171. if (os->ctx)
  172. avformat_free_context(os->ctx);
  173. av_free(os->private_str);
  174. for (j = 0; j < os->nb_fragments; j++)
  175. av_free(os->fragments[j]);
  176. av_free(os->fragments);
  177. }
  178. av_freep(&c->streams);
  179. }
  180. static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
  181. {
  182. int removed = 0, i, start = 0;
  183. if (os->nb_fragments <= 0)
  184. return;
  185. if (os->fragments[0]->n > 0)
  186. removed = 1;
  187. if (final)
  188. skip = 0;
  189. if (window_size)
  190. start = FFMAX(os->nb_fragments - skip - window_size, 0);
  191. for (i = start; i < os->nb_fragments - skip; i++) {
  192. Fragment *frag = os->fragments[i];
  193. if (!final || removed)
  194. avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
  195. else
  196. avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
  197. }
  198. }
  199. static int write_manifest(AVFormatContext *s, int final)
  200. {
  201. SmoothStreamingContext *c = s->priv_data;
  202. AVIOContext *out;
  203. char filename[1024], temp_filename[1024];
  204. int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
  205. int64_t duration = 0;
  206. snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
  207. snprintf(temp_filename, sizeof(temp_filename), "%s/Manifest.tmp", s->filename);
  208. ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  209. if (ret < 0) {
  210. av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
  211. return ret;
  212. }
  213. avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  214. for (i = 0; i < s->nb_streams; i++) {
  215. OutputStream *os = &c->streams[i];
  216. if (os->nb_fragments > 0) {
  217. Fragment *last = os->fragments[os->nb_fragments - 1];
  218. duration = last->start_time + last->duration;
  219. }
  220. if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  221. video_chunks = os->nb_fragments;
  222. video_streams++;
  223. } else {
  224. audio_chunks = os->nb_fragments;
  225. audio_streams++;
  226. }
  227. }
  228. if (!final) {
  229. duration = 0;
  230. video_chunks = audio_chunks = 0;
  231. }
  232. if (c->window_size) {
  233. video_chunks = FFMIN(video_chunks, c->window_size);
  234. audio_chunks = FFMIN(audio_chunks, c->window_size);
  235. }
  236. avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
  237. if (!final)
  238. avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
  239. avio_printf(out, ">\n");
  240. if (c->has_video) {
  241. int last = -1, index = 0;
  242. avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
  243. for (i = 0; i < s->nb_streams; i++) {
  244. OutputStream *os = &c->streams[i];
  245. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
  246. continue;
  247. last = i;
  248. avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->width, s->streams[i]->codec->height, os->private_str);
  249. index++;
  250. }
  251. output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
  252. avio_printf(out, "</StreamIndex>\n");
  253. }
  254. if (c->has_audio) {
  255. int last = -1, index = 0;
  256. avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
  257. for (i = 0; i < s->nb_streams; i++) {
  258. OutputStream *os = &c->streams[i];
  259. if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  260. continue;
  261. last = i;
  262. avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->sample_rate, s->streams[i]->codec->channels, os->packet_size, os->audio_tag, os->private_str);
  263. index++;
  264. }
  265. output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
  266. avio_printf(out, "</StreamIndex>\n");
  267. }
  268. avio_printf(out, "</SmoothStreamingMedia>\n");
  269. avio_flush(out);
  270. avio_close(out);
  271. rename(temp_filename, filename);
  272. return 0;
  273. }
  274. static int ism_write_header(AVFormatContext *s)
  275. {
  276. SmoothStreamingContext *c = s->priv_data;
  277. int ret = 0, i;
  278. AVOutputFormat *oformat;
  279. if (mkdir(s->filename, 0777) < 0) {
  280. av_log(s, AV_LOG_ERROR, "mkdir failed\n");
  281. ret = AVERROR(errno);
  282. goto fail;
  283. }
  284. oformat = av_guess_format("ismv", NULL, NULL);
  285. if (!oformat) {
  286. ret = AVERROR_MUXER_NOT_FOUND;
  287. goto fail;
  288. }
  289. c->streams = av_mallocz_array(s->nb_streams, sizeof(*c->streams));
  290. if (!c->streams) {
  291. ret = AVERROR(ENOMEM);
  292. goto fail;
  293. }
  294. for (i = 0; i < s->nb_streams; i++) {
  295. OutputStream *os = &c->streams[i];
  296. AVFormatContext *ctx;
  297. AVStream *st;
  298. AVDictionary *opts = NULL;
  299. char buf[10];
  300. if (!s->streams[i]->codec->bit_rate) {
  301. av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
  302. ret = AVERROR(EINVAL);
  303. goto fail;
  304. }
  305. snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codec->bit_rate);
  306. if (mkdir(os->dirname, 0777) < 0) {
  307. ret = AVERROR(errno);
  308. av_log(s, AV_LOG_ERROR, "mkdir failed\n");
  309. goto fail;
  310. }
  311. ctx = avformat_alloc_context();
  312. if (!ctx) {
  313. ret = AVERROR(ENOMEM);
  314. goto fail;
  315. }
  316. os->ctx = ctx;
  317. ctx->oformat = oformat;
  318. ctx->interrupt_callback = s->interrupt_callback;
  319. if (!(st = avformat_new_stream(ctx, NULL))) {
  320. ret = AVERROR(ENOMEM);
  321. goto fail;
  322. }
  323. avcodec_copy_context(st->codec, s->streams[i]->codec);
  324. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  325. ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, ism_write, ism_seek);
  326. if (!ctx->pb) {
  327. ret = AVERROR(ENOMEM);
  328. goto fail;
  329. }
  330. snprintf(buf, sizeof(buf), "%d", c->lookahead_count);
  331. av_dict_set(&opts, "ism_lookahead", buf, 0);
  332. av_dict_set(&opts, "movflags", "frag_custom", 0);
  333. if ((ret = avformat_write_header(ctx, &opts)) < 0) {
  334. goto fail;
  335. }
  336. os->ctx_inited = 1;
  337. avio_flush(ctx->pb);
  338. av_dict_free(&opts);
  339. s->streams[i]->time_base = st->time_base;
  340. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  341. c->has_video = 1;
  342. os->stream_type_tag = "video";
  343. if (st->codec->codec_id == AV_CODEC_ID_H264) {
  344. os->fourcc = "H264";
  345. } else if (st->codec->codec_id == AV_CODEC_ID_VC1) {
  346. os->fourcc = "WVC1";
  347. } else {
  348. av_log(s, AV_LOG_ERROR, "Unsupported video codec\n");
  349. ret = AVERROR(EINVAL);
  350. goto fail;
  351. }
  352. } else {
  353. c->has_audio = 1;
  354. os->stream_type_tag = "audio";
  355. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  356. os->fourcc = "AACL";
  357. os->audio_tag = 0xff;
  358. } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
  359. os->fourcc = "WMAP";
  360. os->audio_tag = 0x0162;
  361. } else {
  362. av_log(s, AV_LOG_ERROR, "Unsupported audio codec\n");
  363. ret = AVERROR(EINVAL);
  364. goto fail;
  365. }
  366. os->packet_size = st->codec->block_align ? st->codec->block_align : 4;
  367. }
  368. get_private_data(os);
  369. }
  370. if (!c->has_video && c->min_frag_duration <= 0) {
  371. av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");
  372. ret = AVERROR(EINVAL);
  373. }
  374. ret = write_manifest(s, 0);
  375. fail:
  376. if (ret)
  377. ism_free(s);
  378. return ret;
  379. }
  380. static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)
  381. {
  382. AVIOContext *in;
  383. int ret;
  384. uint32_t len;
  385. if ((ret = avio_open2(&in, filename, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
  386. return ret;
  387. ret = AVERROR(EIO);
  388. *moof_size = avio_rb32(in);
  389. if (*moof_size < 8 || *moof_size > size)
  390. goto fail;
  391. if (avio_rl32(in) != MKTAG('m','o','o','f'))
  392. goto fail;
  393. len = avio_rb32(in);
  394. if (len > *moof_size)
  395. goto fail;
  396. if (avio_rl32(in) != MKTAG('m','f','h','d'))
  397. goto fail;
  398. avio_seek(in, len - 8, SEEK_CUR);
  399. avio_rb32(in); /* traf size */
  400. if (avio_rl32(in) != MKTAG('t','r','a','f'))
  401. goto fail;
  402. while (avio_tell(in) < *moof_size) {
  403. uint32_t len = avio_rb32(in);
  404. uint32_t tag = avio_rl32(in);
  405. int64_t end = avio_tell(in) + len - 8;
  406. if (len < 8 || len >= *moof_size)
  407. goto fail;
  408. if (tag == MKTAG('u','u','i','d')) {
  409. static const uint8_t tfxd[] = {
  410. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  411. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  412. };
  413. uint8_t uuid[16];
  414. avio_read(in, uuid, 16);
  415. if (!memcmp(uuid, tfxd, 16) && len >= 8 + 16 + 4 + 16) {
  416. avio_seek(in, 4, SEEK_CUR);
  417. *start_ts = avio_rb64(in);
  418. *duration = avio_rb64(in);
  419. ret = 0;
  420. break;
  421. }
  422. }
  423. avio_seek(in, end, SEEK_SET);
  424. }
  425. fail:
  426. avio_close(in);
  427. return ret;
  428. }
  429. static int add_fragment(OutputStream *os, const char *file, const char *infofile, int64_t start_time, int64_t duration, int64_t start_pos, int64_t size)
  430. {
  431. int err;
  432. Fragment *frag;
  433. if (os->nb_fragments >= os->fragments_size) {
  434. os->fragments_size = (os->fragments_size + 1) * 2;
  435. if ((err = av_reallocp(&os->fragments, sizeof(*os->fragments) *
  436. os->fragments_size)) < 0) {
  437. os->fragments_size = 0;
  438. os->nb_fragments = 0;
  439. return err;
  440. }
  441. }
  442. frag = av_mallocz(sizeof(*frag));
  443. if (!frag)
  444. return AVERROR(ENOMEM);
  445. av_strlcpy(frag->file, file, sizeof(frag->file));
  446. av_strlcpy(frag->infofile, infofile, sizeof(frag->infofile));
  447. frag->start_time = start_time;
  448. frag->duration = duration;
  449. frag->start_pos = start_pos;
  450. frag->size = size;
  451. frag->n = os->fragment_index;
  452. os->fragments[os->nb_fragments++] = frag;
  453. os->fragment_index++;
  454. return 0;
  455. }
  456. static int copy_moof(AVFormatContext *s, const char* infile, const char *outfile, int64_t size)
  457. {
  458. AVIOContext *in, *out;
  459. int ret = 0;
  460. if ((ret = avio_open2(&in, infile, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)
  461. return ret;
  462. if ((ret = avio_open2(&out, outfile, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL)) < 0) {
  463. avio_close(in);
  464. return ret;
  465. }
  466. while (size > 0) {
  467. uint8_t buf[8192];
  468. int n = FFMIN(size, sizeof(buf));
  469. n = avio_read(in, buf, n);
  470. if (n <= 0) {
  471. ret = AVERROR(EIO);
  472. break;
  473. }
  474. avio_write(out, buf, n);
  475. size -= n;
  476. }
  477. avio_flush(out);
  478. avio_close(out);
  479. avio_close(in);
  480. return ret;
  481. }
  482. static int ism_flush(AVFormatContext *s, int final)
  483. {
  484. SmoothStreamingContext *c = s->priv_data;
  485. int i, ret = 0;
  486. for (i = 0; i < s->nb_streams; i++) {
  487. OutputStream *os = &c->streams[i];
  488. char filename[1024], target_filename[1024], header_filename[1024];
  489. int64_t start_pos = os->tail_pos, size;
  490. int64_t start_ts, duration, moof_size;
  491. if (!os->packets_written)
  492. continue;
  493. snprintf(filename, sizeof(filename), "%s/temp", os->dirname);
  494. ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
  495. if (ret < 0)
  496. break;
  497. os->cur_start_pos = os->tail_pos;
  498. av_write_frame(os->ctx, NULL);
  499. avio_flush(os->ctx->pb);
  500. os->packets_written = 0;
  501. if (!os->out || os->tail_out)
  502. return AVERROR(EIO);
  503. ffurl_close(os->out);
  504. os->out = NULL;
  505. size = os->tail_pos - start_pos;
  506. if ((ret = parse_fragment(s, filename, &start_ts, &duration, &moof_size, size)) < 0)
  507. break;
  508. snprintf(header_filename, sizeof(header_filename), "%s/FragmentInfo(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
  509. snprintf(target_filename, sizeof(target_filename), "%s/Fragments(%s=%"PRIu64")", os->dirname, os->stream_type_tag, start_ts);
  510. copy_moof(s, filename, header_filename, moof_size);
  511. rename(filename, target_filename);
  512. add_fragment(os, target_filename, header_filename, start_ts, duration, start_pos, size);
  513. }
  514. if (c->window_size || (final && c->remove_at_exit)) {
  515. for (i = 0; i < s->nb_streams; i++) {
  516. OutputStream *os = &c->streams[i];
  517. int j;
  518. int remove = os->nb_fragments - c->window_size - c->extra_window_size - c->lookahead_count;
  519. if (final && c->remove_at_exit)
  520. remove = os->nb_fragments;
  521. if (remove > 0) {
  522. for (j = 0; j < remove; j++) {
  523. unlink(os->fragments[j]->file);
  524. unlink(os->fragments[j]->infofile);
  525. av_free(os->fragments[j]);
  526. }
  527. os->nb_fragments -= remove;
  528. memmove(os->fragments, os->fragments + remove, os->nb_fragments * sizeof(*os->fragments));
  529. }
  530. if (final && c->remove_at_exit)
  531. rmdir(os->dirname);
  532. }
  533. }
  534. if (ret >= 0)
  535. ret = write_manifest(s, final);
  536. return ret;
  537. }
  538. static int ism_write_packet(AVFormatContext *s, AVPacket *pkt)
  539. {
  540. SmoothStreamingContext *c = s->priv_data;
  541. AVStream *st = s->streams[pkt->stream_index];
  542. OutputStream *os = &c->streams[pkt->stream_index];
  543. int64_t end_dts = (c->nb_fragments + 1LL) * c->min_frag_duration;
  544. int ret;
  545. if (st->first_dts == AV_NOPTS_VALUE)
  546. st->first_dts = pkt->dts;
  547. if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
  548. av_compare_ts(pkt->dts - st->first_dts, st->time_base,
  549. end_dts, AV_TIME_BASE_Q) >= 0 &&
  550. pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
  551. if ((ret = ism_flush(s, 0)) < 0)
  552. return ret;
  553. c->nb_fragments++;
  554. }
  555. os->packets_written++;
  556. return ff_write_chained(os->ctx, 0, pkt, s);
  557. }
  558. static int ism_write_trailer(AVFormatContext *s)
  559. {
  560. SmoothStreamingContext *c = s->priv_data;
  561. ism_flush(s, 1);
  562. if (c->remove_at_exit) {
  563. char filename[1024];
  564. snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
  565. unlink(filename);
  566. rmdir(s->filename);
  567. }
  568. ism_free(s);
  569. return 0;
  570. }
  571. #define OFFSET(x) offsetof(SmoothStreamingContext, x)
  572. #define E AV_OPT_FLAG_ENCODING_PARAM
  573. static const AVOption options[] = {
  574. { "window_size", "number of fragments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
  575. { "extra_window_size", "number of fragments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
  576. { "lookahead_count", "number of lookahead fragments", OFFSET(lookahead_count), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, E },
  577. { "min_frag_duration", "minimum fragment duration (in microseconds)", OFFSET(min_frag_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
  578. { "remove_at_exit", "remove all fragments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  579. { NULL },
  580. };
  581. static const AVClass ism_class = {
  582. .class_name = "smooth streaming muxer",
  583. .item_name = av_default_item_name,
  584. .option = options,
  585. .version = LIBAVUTIL_VERSION_INT,
  586. };
  587. AVOutputFormat ff_smoothstreaming_muxer = {
  588. .name = "smoothstreaming",
  589. .long_name = NULL_IF_CONFIG_SMALL("Smooth Streaming Muxer"),
  590. .priv_data_size = sizeof(SmoothStreamingContext),
  591. .audio_codec = AV_CODEC_ID_AAC,
  592. .video_codec = AV_CODEC_ID_H264,
  593. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
  594. .write_header = ism_write_header,
  595. .write_packet = ism_write_packet,
  596. .write_trailer = ism_write_trailer,
  597. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  598. .priv_class = &ism_class,
  599. };