ffmpeg-mux.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*
  2. * Copyright (c) 2015 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #ifdef _WIN32
  17. #include <io.h>
  18. #include <fcntl.h>
  19. #define inline __inline
  20. #endif
  21. #include <stdbool.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "ffmpeg-mux.h"
  25. #include <libavformat/avformat.h>
  26. /* ------------------------------------------------------------------------- */
  27. struct resize_buf {
  28. uint8_t *buf;
  29. size_t size;
  30. size_t capacity;
  31. };
  32. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  33. {
  34. if (!rb->buf) {
  35. rb->buf = malloc(size);
  36. rb->size = size;
  37. rb->capacity = size;
  38. } else {
  39. if (rb->capacity < size) {
  40. size_t capx2 = rb->capacity * 2;
  41. size_t new_cap = capx2 > size ? capx2 : size;
  42. rb->buf = realloc(rb->buf, new_cap);
  43. rb->capacity = new_cap;
  44. }
  45. rb->size = size;
  46. }
  47. }
  48. static inline void resize_buf_free(struct resize_buf *rb)
  49. {
  50. free(rb->buf);
  51. }
  52. /* ------------------------------------------------------------------------- */
  53. struct main_params {
  54. char *file;
  55. int has_video;
  56. int tracks;
  57. char *vcodec;
  58. int vbitrate;
  59. int gop;
  60. int width;
  61. int height;
  62. int fps_num;
  63. int fps_den;
  64. char *acodec;
  65. char *muxer_settings;
  66. };
  67. struct audio_params {
  68. char *name;
  69. int abitrate;
  70. int sample_rate;
  71. int channels;
  72. };
  73. struct header {
  74. uint8_t *data;
  75. int size;
  76. };
  77. struct ffmpeg_mux {
  78. AVFormatContext *output;
  79. AVStream *video_stream;
  80. AVStream **audio_streams;
  81. struct main_params params;
  82. struct audio_params *audio;
  83. struct header video_header;
  84. struct header *audio_header;
  85. int num_audio_streams;
  86. bool initialized;
  87. char error[4096];
  88. };
  89. static void header_free(struct header *header)
  90. {
  91. free(header->data);
  92. }
  93. static void free_avformat(struct ffmpeg_mux *ffm)
  94. {
  95. if (ffm->output) {
  96. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  97. avio_close(ffm->output->pb);
  98. avformat_free_context(ffm->output);
  99. ffm->output = NULL;
  100. }
  101. if (ffm->audio_streams) {
  102. free(ffm->audio_streams);
  103. }
  104. ffm->video_stream = NULL;
  105. ffm->audio_streams = NULL;
  106. ffm->num_audio_streams = 0;
  107. }
  108. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  109. {
  110. if (ffm->initialized) {
  111. av_write_trailer(ffm->output);
  112. }
  113. free_avformat(ffm);
  114. header_free(&ffm->video_header);
  115. if (ffm->audio_header) {
  116. for (int i = 0; i < ffm->params.tracks; i++) {
  117. header_free(&ffm->audio_header[i]);
  118. }
  119. free(ffm->audio_header);
  120. }
  121. if (ffm->audio) {
  122. free(ffm->audio);
  123. }
  124. memset(ffm, 0, sizeof(*ffm));
  125. }
  126. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  127. const char *opt)
  128. {
  129. int argc = *p_argc;
  130. char **argv = *p_argv;
  131. if (!argc) {
  132. printf("Missing expected option: '%s'\n", opt);
  133. return false;
  134. }
  135. (*p_argc)--;
  136. (*p_argv)++;
  137. *str = argv[0];
  138. return true;
  139. }
  140. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  141. {
  142. char *str;
  143. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  144. return false;
  145. }
  146. *i = atoi(str);
  147. return true;
  148. }
  149. static bool get_audio_params(struct audio_params *audio, int *argc,
  150. char ***argv)
  151. {
  152. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  153. return false;
  154. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  155. return false;
  156. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  157. return false;
  158. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  159. return false;
  160. return true;
  161. }
  162. static bool init_params(int *argc, char ***argv, struct main_params *params,
  163. struct audio_params **p_audio)
  164. {
  165. struct audio_params *audio = NULL;
  166. if (!get_opt_str(argc, argv, &params->file, "file name"))
  167. return false;
  168. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  169. return false;
  170. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  171. return false;
  172. if (params->has_video > 1 || params->has_video < 0) {
  173. puts("Invalid number of video tracks\n");
  174. return false;
  175. }
  176. if (params->tracks < 0) {
  177. puts("Invalid number of audio tracks\n");
  178. return false;
  179. }
  180. if (params->has_video == 0 && params->tracks == 0) {
  181. puts("Must have at least 1 audio track or 1 video track\n");
  182. return false;
  183. }
  184. if (params->has_video) {
  185. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  186. return false;
  187. if (!get_opt_int(argc, argv, &params->vbitrate,"video bitrate"))
  188. return false;
  189. if (!get_opt_int(argc, argv, &params->width, "video width"))
  190. return false;
  191. if (!get_opt_int(argc, argv, &params->height, "video height"))
  192. return false;
  193. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  194. return false;
  195. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  196. return false;
  197. }
  198. if (params->tracks) {
  199. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  200. return false;
  201. audio = calloc(1, sizeof(*audio) * params->tracks);
  202. for (int i = 0; i < params->tracks; i++) {
  203. if (!get_audio_params(&audio[i], argc, argv)) {
  204. free(audio);
  205. return false;
  206. }
  207. }
  208. }
  209. *p_audio = audio;
  210. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  211. return true;
  212. }
  213. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  214. const char *name, enum AVCodecID *id)
  215. {
  216. const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(name);
  217. AVCodec *codec;
  218. if (!desc) {
  219. printf("Couldn't find encoder '%s'\n", name);
  220. return false;
  221. }
  222. *id = desc->id;
  223. codec = avcodec_find_encoder(desc->id);
  224. if (!codec) {
  225. printf("Couldn't create encoder");
  226. return false;
  227. }
  228. *stream = avformat_new_stream(ffm->output, codec);
  229. if (!*stream) {
  230. printf("Couldn't create stream for encoder '%s'\n", name);
  231. return false;
  232. }
  233. (*stream)->id = ffm->output->nb_streams-1;
  234. return true;
  235. }
  236. static void create_video_stream(struct ffmpeg_mux *ffm)
  237. {
  238. AVCodecContext *context;
  239. void *extradata = NULL;
  240. if (!new_stream(ffm, &ffm->video_stream, ffm->params.vcodec,
  241. &ffm->output->oformat->video_codec))
  242. return;
  243. if (ffm->video_header.size) {
  244. extradata = av_memdup(ffm->video_header.data,
  245. ffm->video_header.size);
  246. }
  247. context = ffm->video_stream->codec;
  248. context->bit_rate = ffm->params.vbitrate * 1000;
  249. context->width = ffm->params.width;
  250. context->height = ffm->params.height;
  251. context->coded_width = ffm->params.width;
  252. context->coded_height = ffm->params.height;
  253. context->extradata = extradata;
  254. context->extradata_size = ffm->video_header.size;
  255. context->time_base =
  256. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  257. ffm->video_stream->time_base = context->time_base;
  258. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  259. context->flags |= CODEC_FLAG_GLOBAL_HEADER;
  260. }
  261. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  262. {
  263. AVCodecContext *context;
  264. AVStream *stream;
  265. void *extradata = NULL;
  266. if (!new_stream(ffm, &stream, ffm->params.acodec,
  267. &ffm->output->oformat->audio_codec))
  268. return;
  269. ffm->audio_streams[idx] = stream;
  270. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  271. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  272. if (ffm->audio_header[idx].size) {
  273. extradata = av_memdup(ffm->audio_header[idx].data,
  274. ffm->audio_header[idx].size);
  275. }
  276. context = stream->codec;
  277. context->bit_rate = ffm->audio[idx].abitrate * 1000;
  278. context->channels = ffm->audio[idx].channels;
  279. context->sample_rate = ffm->audio[idx].sample_rate;
  280. context->sample_fmt = AV_SAMPLE_FMT_S16;
  281. context->time_base = stream->time_base;
  282. context->extradata = extradata;
  283. context->extradata_size = ffm->audio_header[idx].size;
  284. context->channel_layout =
  285. av_get_default_channel_layout(context->channels);
  286. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  287. context->flags |= CODEC_FLAG_GLOBAL_HEADER;
  288. ffm->num_audio_streams++;
  289. }
  290. static bool init_streams(struct ffmpeg_mux *ffm)
  291. {
  292. create_video_stream(ffm);
  293. if (ffm->params.tracks) {
  294. ffm->audio_streams =
  295. calloc(1, ffm->params.tracks * sizeof(void*));
  296. for (int i = 0; i < ffm->params.tracks; i++)
  297. create_audio_stream(ffm, i);
  298. }
  299. if (!ffm->video_stream && !ffm->num_audio_streams)
  300. return false;
  301. return true;
  302. }
  303. static void set_header(struct header *header, uint8_t *data, size_t size)
  304. {
  305. header->size = (int)size;
  306. header->data = malloc(size);
  307. memcpy(header->data, data, size);
  308. }
  309. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  310. struct ffm_packet_info *info)
  311. {
  312. if (info->type == FFM_PACKET_VIDEO) {
  313. set_header(&ffm->video_header, data, (size_t)info->size);
  314. } else {
  315. set_header(&ffm->audio_header[info->index], data,
  316. (size_t)info->size);
  317. }
  318. }
  319. static size_t safe_read(void *vdata, size_t size)
  320. {
  321. uint8_t *data = vdata;
  322. size_t total = size;
  323. while (size > 0) {
  324. size_t in_size = fread(data, 1, size, stdin);
  325. if (in_size == 0)
  326. return 0;
  327. size -= in_size;
  328. data += in_size;
  329. }
  330. return total;
  331. }
  332. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  333. {
  334. struct ffm_packet_info info = {0};
  335. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  336. if (success) {
  337. uint8_t *data = malloc(info.size);
  338. if (safe_read(data, info.size) == info.size) {
  339. ffmpeg_mux_header(ffm, data, &info);
  340. } else {
  341. success = false;
  342. }
  343. free(data);
  344. }
  345. return success;
  346. }
  347. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  348. {
  349. if (ffm->params.has_video) {
  350. if (!ffmpeg_mux_get_header(ffm)) {
  351. return false;
  352. }
  353. }
  354. for (int i = 0; i < ffm->params.tracks; i++) {
  355. if (!ffmpeg_mux_get_header(ffm)) {
  356. return false;
  357. }
  358. }
  359. return true;
  360. }
  361. #ifdef _MSC_VER
  362. #pragma warning(disable : 4996)
  363. #endif
  364. static inline int open_output_file(struct ffmpeg_mux *ffm)
  365. {
  366. AVOutputFormat *format = ffm->output->oformat;
  367. int ret;
  368. if ((format->flags & AVFMT_NOFILE) == 0) {
  369. ret = avio_open(&ffm->output->pb, ffm->params.file,
  370. AVIO_FLAG_WRITE);
  371. if (ret < 0) {
  372. printf("Couldn't open '%s', %s",
  373. ffm->params.file, av_err2str(ret));
  374. return FFM_ERROR;
  375. }
  376. }
  377. strncpy(ffm->output->filename, ffm->params.file,
  378. sizeof(ffm->output->filename));
  379. ffm->output->filename[sizeof(ffm->output->filename) - 1] = 0;
  380. AVDictionary *dict = NULL;
  381. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings,
  382. "=", " ", 0))) {
  383. printf("Failed to parse muxer settings: %s\n%s",
  384. av_err2str(ret), ffm->params.muxer_settings);
  385. av_dict_free(&dict);
  386. }
  387. if (av_dict_count(dict) > 0) {
  388. printf("Using muxer settings:");
  389. AVDictionaryEntry *entry = NULL;
  390. while ((entry = av_dict_get(dict, "", entry,
  391. AV_DICT_IGNORE_SUFFIX)))
  392. printf("\n\t%s=%s", entry->key, entry->value);
  393. printf("\n");
  394. }
  395. ret = avformat_write_header(ffm->output, &dict);
  396. if (ret < 0) {
  397. printf("Error opening '%s': %s",
  398. ffm->params.file, av_err2str(ret));
  399. av_dict_free(&dict);
  400. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  401. }
  402. av_dict_free(&dict);
  403. return FFM_SUCCESS;
  404. }
  405. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  406. {
  407. AVOutputFormat *output_format;
  408. int ret;
  409. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  410. if (output_format == NULL) {
  411. printf("Couldn't find an appropriate muxer for '%s'\n",
  412. ffm->params.file);
  413. return FFM_ERROR;
  414. }
  415. ret = avformat_alloc_output_context2(&ffm->output, output_format,
  416. NULL, NULL);
  417. if (ret < 0) {
  418. printf("Couldn't initialize output context: %s\n",
  419. av_err2str(ret));
  420. return FFM_ERROR;
  421. }
  422. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  423. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  424. if (!init_streams(ffm)) {
  425. free_avformat(ffm);
  426. return FFM_ERROR;
  427. }
  428. ret = open_output_file(ffm);
  429. if (ret != FFM_SUCCESS) {
  430. free_avformat(ffm);
  431. return ret;
  432. }
  433. return FFM_SUCCESS;
  434. }
  435. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  436. char *argv[])
  437. {
  438. argc--;
  439. argv++;
  440. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  441. return FFM_ERROR;
  442. if (ffm->params.tracks) {
  443. ffm->audio_header =
  444. calloc(1, sizeof(struct header) * ffm->params.tracks);
  445. }
  446. av_register_all();
  447. if (!ffmpeg_mux_get_extra_data(ffm))
  448. return FFM_ERROR;
  449. /* ffmpeg does not have a way of telling what's supported
  450. * for a given output format, so we try each possibility */
  451. return ffmpeg_mux_init_context(ffm);
  452. }
  453. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  454. {
  455. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  456. if (ret != FFM_SUCCESS) {
  457. ffmpeg_mux_free(ffm);
  458. return ret;
  459. }
  460. ffm->initialized = true;
  461. return ret;
  462. }
  463. static inline int get_index(struct ffmpeg_mux *ffm,
  464. struct ffm_packet_info *info)
  465. {
  466. if (info->type == FFM_PACKET_VIDEO) {
  467. if (ffm->video_stream) {
  468. return ffm->video_stream->id;
  469. }
  470. } else {
  471. if ((int)info->index < ffm->num_audio_streams) {
  472. return ffm->audio_streams[info->index]->id;
  473. }
  474. }
  475. return -1;
  476. }
  477. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  478. {
  479. return ffm->output->streams[idx];
  480. }
  481. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm, int64_t val, int idx)
  482. {
  483. AVStream *stream = get_stream(ffm, idx);
  484. return av_rescale_q_rnd(val / stream->codec->time_base.num,
  485. stream->codec->time_base, stream->time_base,
  486. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  487. }
  488. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  489. struct ffm_packet_info *info)
  490. {
  491. int idx = get_index(ffm, info);
  492. AVPacket packet = {0};
  493. /* The muxer might not support video/audio, or multiple audio tracks */
  494. if (idx == -1) {
  495. return true;
  496. }
  497. av_init_packet(&packet);
  498. packet.data = buf;
  499. packet.size = (int)info->size;
  500. packet.stream_index = idx;
  501. packet.pts = rescale_ts(ffm, info->pts, idx);
  502. packet.dts = rescale_ts(ffm, info->dts, idx);
  503. if (info->keyframe)
  504. packet.flags = AV_PKT_FLAG_KEY;
  505. return av_interleaved_write_frame(ffm->output, &packet) >= 0;
  506. }
  507. /* ------------------------------------------------------------------------- */
  508. int main(int argc, char *argv[])
  509. {
  510. struct ffm_packet_info info = {0};
  511. struct ffmpeg_mux ffm = {0};
  512. struct resize_buf rb = {0};
  513. bool fail = false;
  514. int ret;
  515. #ifdef _WIN32
  516. _setmode(_fileno(stdin), O_BINARY);
  517. #endif
  518. setvbuf(stderr, NULL, _IONBF, 0);
  519. ret = ffmpeg_mux_init(&ffm, argc, argv);
  520. if (ret != FFM_SUCCESS) {
  521. puts("Couldn't initialize muxer");
  522. return ret;
  523. }
  524. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  525. resize_buf_resize(&rb, info.size);
  526. if (safe_read(rb.buf, info.size) == info.size) {
  527. ffmpeg_mux_packet(&ffm, rb.buf, &info);
  528. } else {
  529. fail = true;
  530. }
  531. }
  532. ffmpeg_mux_free(&ffm);
  533. resize_buf_free(&rb);
  534. return 0;
  535. }