ismindex.c 18 KB

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