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.

579 lines
19KB

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