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.

591 lines
20KB

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