ismindex.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * Copyright (c) 2012 Martin Storsjo
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /*
  21. * To create a simple file for smooth streaming:
  22. * ffmpeg <normal input/transcoding options> -movflags frag_keyframe foo.ismv
  23. * ismindex -n foo foo.ismv
  24. * This step creates foo.ism and foo.ismc that is required by IIS for
  25. * serving it.
  26. *
  27. * To pre-split files for serving as static files by a web server without
  28. * any extra server support, create the ismv file as above, and split it:
  29. * ismindex -split foo.ismv
  30. * This step creates a file Manifest and directories QualityLevel(...),
  31. * that can be read directly by a smooth streaming player.
  32. */
  33. #include <stdio.h>
  34. #include <string.h>
  35. #include "cmdutils.h"
  36. #include "libavformat/avformat.h"
  37. #include "libavformat/os_support.h"
  38. #include "libavutil/intreadwrite.h"
  39. #include "libavutil/mathematics.h"
  40. static int usage(const char *argv0, int ret)
  41. {
  42. fprintf(stderr, "%s [-split] [-n basename] file1 [file2] ...\n", argv0);
  43. return ret;
  44. }
  45. struct MoofOffset {
  46. int64_t time;
  47. int64_t offset;
  48. int64_t duration;
  49. };
  50. struct Track {
  51. const char *name;
  52. int64_t duration;
  53. int bitrate;
  54. int track_id;
  55. int is_audio, is_video;
  56. int width, height;
  57. int chunks;
  58. int sample_rate, channels;
  59. uint8_t *codec_private;
  60. int codec_private_size;
  61. struct MoofOffset *offsets;
  62. int timescale;
  63. const char *fourcc;
  64. int blocksize;
  65. int tag;
  66. };
  67. struct Tracks {
  68. int nb_tracks;
  69. int64_t duration;
  70. struct Track **tracks;
  71. int video_track, audio_track;
  72. int nb_video_tracks, nb_audio_tracks;
  73. };
  74. static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
  75. {
  76. int32_t size, tag;
  77. size = avio_rb32(in);
  78. tag = avio_rb32(in);
  79. avio_wb32(out, size);
  80. avio_wb32(out, tag);
  81. if (tag != tag_name)
  82. return -1;
  83. size -= 8;
  84. while (size > 0) {
  85. char buf[1024];
  86. int len = FFMIN(sizeof(buf), size);
  87. if (avio_read(in, buf, len) != len)
  88. break;
  89. avio_write(out, buf, len);
  90. size -= len;
  91. }
  92. return 0;
  93. }
  94. static int write_fragment(const char *filename, AVIOContext *in)
  95. {
  96. AVIOContext *out = NULL;
  97. int ret;
  98. if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
  99. return ret;
  100. copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
  101. copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
  102. avio_flush(out);
  103. avio_close(out);
  104. return ret;
  105. }
  106. static int write_fragments(struct Tracks *tracks, int start_index,
  107. AVIOContext *in)
  108. {
  109. char dirname[100], filename[500];
  110. int i, j;
  111. for (i = start_index; i < tracks->nb_tracks; i++) {
  112. struct Track *track = tracks->tracks[i];
  113. const char *type = track->is_video ? "video" : "audio";
  114. snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", track->bitrate);
  115. if (mkdir(dirname, 0777) == -1)
  116. return AVERROR(errno);
  117. for (j = 0; j < track->chunks; j++) {
  118. snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
  119. dirname, type, track->offsets[j].time);
  120. avio_seek(in, track->offsets[j].offset, SEEK_SET);
  121. write_fragment(filename, in);
  122. }
  123. }
  124. return 0;
  125. }
  126. static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
  127. {
  128. int ret = AVERROR_EOF, track_id;
  129. int version, fieldlength, i, j;
  130. int64_t pos = avio_tell(f);
  131. uint32_t size = avio_rb32(f);
  132. struct Track *track = NULL;
  133. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
  134. goto fail;
  135. version = avio_r8(f);
  136. avio_rb24(f);
  137. track_id = avio_rb32(f); /* track id */
  138. for (i = start_index; i < tracks->nb_tracks && !track; i++)
  139. if (tracks->tracks[i]->track_id == track_id)
  140. track = tracks->tracks[i];
  141. if (!track) {
  142. /* Ok, continue parsing the next atom */
  143. ret = 0;
  144. goto fail;
  145. }
  146. fieldlength = avio_rb32(f);
  147. track->chunks = avio_rb32(f);
  148. track->offsets = av_mallocz(sizeof(*track->offsets) * track->chunks);
  149. if (!track->offsets) {
  150. ret = AVERROR(ENOMEM);
  151. goto fail;
  152. }
  153. for (i = 0; i < track->chunks; i++) {
  154. if (version == 1) {
  155. track->offsets[i].time = avio_rb64(f);
  156. track->offsets[i].offset = avio_rb64(f);
  157. } else {
  158. track->offsets[i].time = avio_rb32(f);
  159. track->offsets[i].offset = avio_rb32(f);
  160. }
  161. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  162. avio_r8(f);
  163. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  164. avio_r8(f);
  165. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  166. avio_r8(f);
  167. if (i > 0)
  168. track->offsets[i - 1].duration = track->offsets[i].time -
  169. track->offsets[i - 1].time;
  170. }
  171. if (track->chunks > 0)
  172. track->offsets[track->chunks - 1].duration = track->duration -
  173. track->offsets[track->chunks - 1].time;
  174. ret = 0;
  175. fail:
  176. avio_seek(f, pos + size, SEEK_SET);
  177. return ret;
  178. }
  179. static int read_mfra(struct Tracks *tracks, int start_index,
  180. const char *file, int split)
  181. {
  182. int err = 0;
  183. AVIOContext *f = NULL;
  184. int32_t mfra_size;
  185. if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
  186. goto fail;
  187. avio_seek(f, avio_size(f) - 4, SEEK_SET);
  188. mfra_size = avio_rb32(f);
  189. avio_seek(f, -mfra_size, SEEK_CUR);
  190. if (avio_rb32(f) != mfra_size) {
  191. err = AVERROR_INVALIDDATA;
  192. goto fail;
  193. }
  194. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  195. err = AVERROR_INVALIDDATA;
  196. goto fail;
  197. }
  198. while (!read_tfra(tracks, start_index, f)) {
  199. /* Empty */
  200. }
  201. if (split)
  202. err = write_fragments(tracks, start_index, f);
  203. fail:
  204. if (f)
  205. avio_close(f);
  206. if (err)
  207. fprintf(stderr, "Unable to read the MFRA atom in %s\n", file);
  208. return err;
  209. }
  210. static int get_private_data(struct Track *track, AVCodecContext *codec)
  211. {
  212. track->codec_private_size = codec->extradata_size;
  213. track->codec_private = av_mallocz(codec->extradata_size);
  214. if (!track->codec_private)
  215. return AVERROR(ENOMEM);
  216. memcpy(track->codec_private, codec->extradata, codec->extradata_size);
  217. return 0;
  218. }
  219. static int get_video_private_data(struct Track *track, AVCodecContext *codec)
  220. {
  221. AVIOContext *io = NULL;
  222. uint16_t sps_size, pps_size;
  223. int err = AVERROR(EINVAL);
  224. if (codec->codec_id == AV_CODEC_ID_VC1)
  225. return get_private_data(track, codec);
  226. if (avio_open_dyn_buf(&io) < 0) {
  227. err = AVERROR(ENOMEM);
  228. goto fail;
  229. }
  230. if (codec->extradata_size < 11 || codec->extradata[0] != 1)
  231. goto fail;
  232. sps_size = AV_RB16(&codec->extradata[6]);
  233. if (11 + sps_size > codec->extradata_size)
  234. goto fail;
  235. avio_wb32(io, 0x00000001);
  236. avio_write(io, &codec->extradata[8], sps_size);
  237. pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
  238. if (11 + sps_size + pps_size > codec->extradata_size)
  239. goto fail;
  240. avio_wb32(io, 0x00000001);
  241. avio_write(io, &codec->extradata[11 + sps_size], pps_size);
  242. err = 0;
  243. fail:
  244. track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
  245. return err;
  246. }
  247. static int handle_file(struct Tracks *tracks, const char *file, int split)
  248. {
  249. AVFormatContext *ctx = NULL;
  250. int err = 0, i, orig_tracks = tracks->nb_tracks;
  251. char errbuf[50], *ptr;
  252. struct Track *track;
  253. err = avformat_open_input(&ctx, file, NULL, NULL);
  254. if (err < 0) {
  255. av_strerror(err, errbuf, sizeof(errbuf));
  256. fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
  257. return 1;
  258. }
  259. err = avformat_find_stream_info(ctx, NULL);
  260. if (err < 0) {
  261. av_strerror(err, errbuf, sizeof(errbuf));
  262. fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
  263. goto fail;
  264. }
  265. if (ctx->nb_streams < 1) {
  266. fprintf(stderr, "No streams found in %s\n", file);
  267. goto fail;
  268. }
  269. for (i = 0; i < ctx->nb_streams; i++) {
  270. struct Track **temp;
  271. AVStream *st = ctx->streams[i];
  272. track = av_mallocz(sizeof(*track));
  273. if (!track) {
  274. err = AVERROR(ENOMEM);
  275. goto fail;
  276. }
  277. temp = av_realloc(tracks->tracks,
  278. sizeof(*tracks->tracks) * (tracks->nb_tracks + 1));
  279. if (!temp) {
  280. av_free(track);
  281. err = AVERROR(ENOMEM);
  282. goto fail;
  283. }
  284. tracks->tracks = temp;
  285. tracks->tracks[tracks->nb_tracks] = track;
  286. track->name = file;
  287. if ((ptr = strrchr(file, '/')) != NULL)
  288. track->name = ptr + 1;
  289. track->bitrate = st->codec->bit_rate;
  290. track->track_id = st->id;
  291. track->timescale = st->time_base.den;
  292. track->duration = st->duration;
  293. track->is_audio = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
  294. track->is_video = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  295. if (!track->is_audio && !track->is_video) {
  296. fprintf(stderr,
  297. "Track %d in %s is neither video nor audio, skipping\n",
  298. track->track_id, file);
  299. av_freep(&tracks->tracks[tracks->nb_tracks]);
  300. continue;
  301. }
  302. tracks->duration = FFMAX(tracks->duration,
  303. av_rescale_rnd(track->duration, AV_TIME_BASE,
  304. track->timescale, AV_ROUND_UP));
  305. if (track->is_audio) {
  306. if (tracks->audio_track < 0)
  307. tracks->audio_track = tracks->nb_tracks;
  308. tracks->nb_audio_tracks++;
  309. track->channels = st->codec->channels;
  310. track->sample_rate = st->codec->sample_rate;
  311. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  312. track->fourcc = "AACL";
  313. track->tag = 255;
  314. track->blocksize = 4;
  315. } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
  316. track->fourcc = "WMAP";
  317. track->tag = st->codec->codec_tag;
  318. track->blocksize = st->codec->block_align;
  319. }
  320. get_private_data(track, st->codec);
  321. }
  322. if (track->is_video) {
  323. if (tracks->video_track < 0)
  324. tracks->video_track = tracks->nb_tracks;
  325. tracks->nb_video_tracks++;
  326. track->width = st->codec->width;
  327. track->height = st->codec->height;
  328. if (st->codec->codec_id == AV_CODEC_ID_H264)
  329. track->fourcc = "H264";
  330. else if (st->codec->codec_id == AV_CODEC_ID_VC1)
  331. track->fourcc = "WVC1";
  332. get_video_private_data(track, st->codec);
  333. }
  334. tracks->nb_tracks++;
  335. }
  336. avformat_close_input(&ctx);
  337. err = read_mfra(tracks, orig_tracks, file, split);
  338. fail:
  339. if (ctx)
  340. avformat_close_input(&ctx);
  341. return err;
  342. }
  343. static void output_server_manifest(struct Tracks *tracks,
  344. const char *basename)
  345. {
  346. char filename[1000];
  347. FILE *out;
  348. int i;
  349. snprintf(filename, sizeof(filename), "%s.ism", basename);
  350. out = fopen(filename, "w");
  351. if (!out) {
  352. perror(filename);
  353. return;
  354. }
  355. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  356. fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  357. fprintf(out, "\t<head>\n");
  358. fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
  359. "content=\"%s.ismc\" />\n", basename);
  360. fprintf(out, "\t</head>\n");
  361. fprintf(out, "\t<body>\n");
  362. fprintf(out, "\t\t<switch>\n");
  363. for (i = 0; i < tracks->nb_tracks; i++) {
  364. struct Track *track = tracks->tracks[i];
  365. const char *type = track->is_video ? "video" : "audio";
  366. fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
  367. type, track->name, track->bitrate);
  368. fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
  369. "valueType=\"data\" />\n", track->track_id);
  370. fprintf(out, "\t\t\t</%s>\n", type);
  371. }
  372. fprintf(out, "\t\t</switch>\n");
  373. fprintf(out, "\t</body>\n");
  374. fprintf(out, "</smil>\n");
  375. fclose(out);
  376. }
  377. static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
  378. const char *type)
  379. {
  380. int i, j;
  381. struct Track *track = tracks->tracks[main];
  382. for (i = 0; i < track->chunks; i++) {
  383. for (j = main + 1; j < tracks->nb_tracks; j++) {
  384. if (tracks->tracks[j]->is_audio == track->is_audio &&
  385. track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration)
  386. fprintf(stderr, "Mismatched duration of %s chunk %d in %s and %s\n",
  387. type, i, track->name, tracks->tracks[j]->name);
  388. }
  389. fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" />\n",
  390. i, track->offsets[i].duration);
  391. }
  392. }
  393. static void output_client_manifest(struct Tracks *tracks,
  394. const char *basename, int split)
  395. {
  396. char filename[1000];
  397. FILE *out;
  398. int i, j;
  399. if (split)
  400. snprintf(filename, sizeof(filename), "Manifest");
  401. else
  402. snprintf(filename, sizeof(filename), "%s.ismc", basename);
  403. out = fopen(filename, "w");
  404. if (!out) {
  405. perror(filename);
  406. return;
  407. }
  408. fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  409. fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
  410. "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
  411. if (tracks->video_track >= 0) {
  412. struct Track *track = tracks->tracks[tracks->video_track];
  413. struct Track *first_track = track;
  414. int index = 0;
  415. fprintf(out,
  416. "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
  417. "Chunks=\"%d\" "
  418. "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
  419. tracks->nb_video_tracks, track->chunks);
  420. for (i = 0; i < tracks->nb_tracks; i++) {
  421. track = tracks->tracks[i];
  422. if (!track->is_video)
  423. continue;
  424. fprintf(out,
  425. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  426. "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
  427. "CodecPrivateData=\"",
  428. index, track->bitrate, track->fourcc, track->width, track->height);
  429. for (j = 0; j < track->codec_private_size; j++)
  430. fprintf(out, "%02X", track->codec_private[j]);
  431. fprintf(out, "\" />\n");
  432. index++;
  433. if (track->chunks != first_track->chunks)
  434. fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
  435. track->name, first_track->name);
  436. }
  437. print_track_chunks(out, tracks, tracks->video_track, "video");
  438. fprintf(out, "\t</StreamIndex>\n");
  439. }
  440. if (tracks->audio_track >= 0) {
  441. struct Track *track = tracks->tracks[tracks->audio_track];
  442. struct Track *first_track = track;
  443. int index = 0;
  444. fprintf(out,
  445. "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
  446. "Chunks=\"%d\" "
  447. "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
  448. tracks->nb_audio_tracks, track->chunks);
  449. for (i = 0; i < tracks->nb_tracks; i++) {
  450. track = tracks->tracks[i];
  451. if (!track->is_audio)
  452. continue;
  453. fprintf(out,
  454. "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
  455. "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
  456. "BitsPerSample=\"16\" PacketSize=\"%d\" "
  457. "AudioTag=\"%d\" CodecPrivateData=\"",
  458. index, track->bitrate, track->fourcc, track->sample_rate,
  459. track->channels, track->blocksize, track->tag);
  460. for (j = 0; j < track->codec_private_size; j++)
  461. fprintf(out, "%02X", track->codec_private[j]);
  462. fprintf(out, "\" />\n");
  463. index++;
  464. if (track->chunks != first_track->chunks)
  465. fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
  466. track->name, first_track->name);
  467. }
  468. print_track_chunks(out, tracks, tracks->audio_track, "audio");
  469. fprintf(out, "\t</StreamIndex>\n");
  470. }
  471. fprintf(out, "</SmoothStreamingMedia>\n");
  472. fclose(out);
  473. }
  474. static void clean_tracks(struct Tracks *tracks)
  475. {
  476. int i;
  477. for (i = 0; i < tracks->nb_tracks; i++) {
  478. av_freep(&tracks->tracks[i]->codec_private);
  479. av_freep(&tracks->tracks[i]->offsets);
  480. av_freep(&tracks->tracks[i]);
  481. }
  482. av_freep(&tracks->tracks);
  483. tracks->nb_tracks = 0;
  484. }
  485. int main(int argc, char **argv)
  486. {
  487. const char *basename = NULL;
  488. int split = 0, i;
  489. struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
  490. av_register_all();
  491. for (i = 1; i < argc; i++) {
  492. if (!strcmp(argv[i], "-n")) {
  493. basename = argv[i + 1];
  494. i++;
  495. } else if (!strcmp(argv[i], "-split")) {
  496. split = 1;
  497. } else if (argv[i][0] == '-') {
  498. return usage(argv[0], 1);
  499. } else {
  500. if (handle_file(&tracks, argv[i], split))
  501. return 1;
  502. }
  503. }
  504. if (!tracks.nb_tracks || (!basename && !split))
  505. return usage(argv[0], 1);
  506. if (!split)
  507. output_server_manifest(&tracks, basename);
  508. output_client_manifest(&tracks, basename, split);
  509. clean_tracks(&tracks);
  510. return 0;
  511. }