ismindex.c 18 KB

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