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.

652 lines
23KB

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