ffmpeg-mux.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. #include <windows.h>
  20. #define inline __inline
  21. #endif
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "ffmpeg-mux.h"
  25. #include <libavformat/avformat.h>
  26. #if LIBAVCODEC_VERSION_MAJOR >= 58
  27. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  28. #else
  29. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  30. #endif
  31. /* ------------------------------------------------------------------------- */
  32. struct resize_buf {
  33. uint8_t *buf;
  34. size_t size;
  35. size_t capacity;
  36. };
  37. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  38. {
  39. if (!rb->buf) {
  40. rb->buf = malloc(size);
  41. rb->size = size;
  42. rb->capacity = size;
  43. } else {
  44. if (rb->capacity < size) {
  45. size_t capx2 = rb->capacity * 2;
  46. size_t new_cap = capx2 > size ? capx2 : size;
  47. rb->buf = realloc(rb->buf, new_cap);
  48. rb->capacity = new_cap;
  49. }
  50. rb->size = size;
  51. }
  52. }
  53. static inline void resize_buf_free(struct resize_buf *rb)
  54. {
  55. free(rb->buf);
  56. }
  57. /* ------------------------------------------------------------------------- */
  58. struct main_params {
  59. char *file;
  60. int has_video;
  61. int tracks;
  62. char *vcodec;
  63. int vbitrate;
  64. int gop;
  65. int width;
  66. int height;
  67. int fps_num;
  68. int fps_den;
  69. int color_primaries;
  70. int color_trc;
  71. int colorspace;
  72. int color_range;
  73. char *acodec;
  74. char *muxer_settings;
  75. };
  76. struct audio_params {
  77. char *name;
  78. int abitrate;
  79. int sample_rate;
  80. int channels;
  81. };
  82. struct header {
  83. uint8_t *data;
  84. int size;
  85. };
  86. struct audio_info {
  87. AVStream *stream;
  88. AVCodecContext *ctx;
  89. };
  90. struct ffmpeg_mux {
  91. AVFormatContext *output;
  92. AVStream *video_stream;
  93. AVCodecContext *video_ctx;
  94. struct audio_info *audio_infos;
  95. struct main_params params;
  96. struct audio_params *audio;
  97. struct header video_header;
  98. struct header *audio_header;
  99. int num_audio_streams;
  100. bool initialized;
  101. char error[4096];
  102. };
  103. static void header_free(struct header *header)
  104. {
  105. free(header->data);
  106. }
  107. static void free_avformat(struct ffmpeg_mux *ffm)
  108. {
  109. if (ffm->output) {
  110. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  111. avcodec_free_context(&ffm->video_ctx);
  112. #endif
  113. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  114. avio_close(ffm->output->pb);
  115. avformat_free_context(ffm->output);
  116. ffm->output = NULL;
  117. }
  118. if (ffm->audio_infos) {
  119. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  120. for (int i = 0; i < ffm->num_audio_streams; ++i)
  121. avcodec_free_context(&ffm->audio_infos[i].ctx);
  122. #endif
  123. free(ffm->audio_infos);
  124. }
  125. ffm->video_stream = NULL;
  126. ffm->audio_infos = NULL;
  127. ffm->num_audio_streams = 0;
  128. }
  129. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  130. {
  131. if (ffm->initialized) {
  132. av_write_trailer(ffm->output);
  133. }
  134. free_avformat(ffm);
  135. header_free(&ffm->video_header);
  136. if (ffm->audio_header) {
  137. for (int i = 0; i < ffm->params.tracks; i++) {
  138. header_free(&ffm->audio_header[i]);
  139. }
  140. free(ffm->audio_header);
  141. }
  142. if (ffm->audio) {
  143. free(ffm->audio);
  144. }
  145. memset(ffm, 0, sizeof(*ffm));
  146. }
  147. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  148. const char *opt)
  149. {
  150. int argc = *p_argc;
  151. char **argv = *p_argv;
  152. if (!argc) {
  153. printf("Missing expected option: '%s'\n", opt);
  154. return false;
  155. }
  156. (*p_argc)--;
  157. (*p_argv)++;
  158. *str = argv[0];
  159. return true;
  160. }
  161. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  162. {
  163. char *str;
  164. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  165. return false;
  166. }
  167. *i = atoi(str);
  168. return true;
  169. }
  170. static bool get_audio_params(struct audio_params *audio, int *argc,
  171. char ***argv)
  172. {
  173. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  174. return false;
  175. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  176. return false;
  177. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  178. return false;
  179. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  180. return false;
  181. return true;
  182. }
  183. static bool init_params(int *argc, char ***argv, struct main_params *params,
  184. struct audio_params **p_audio)
  185. {
  186. struct audio_params *audio = NULL;
  187. if (!get_opt_str(argc, argv, &params->file, "file name"))
  188. return false;
  189. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  190. return false;
  191. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  192. return false;
  193. if (params->has_video > 1 || params->has_video < 0) {
  194. puts("Invalid number of video tracks\n");
  195. return false;
  196. }
  197. if (params->tracks < 0) {
  198. puts("Invalid number of audio tracks\n");
  199. return false;
  200. }
  201. if (params->has_video == 0 && params->tracks == 0) {
  202. puts("Must have at least 1 audio track or 1 video track\n");
  203. return false;
  204. }
  205. if (params->has_video) {
  206. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  207. return false;
  208. if (!get_opt_int(argc, argv, &params->vbitrate,
  209. "video bitrate"))
  210. return false;
  211. if (!get_opt_int(argc, argv, &params->width, "video width"))
  212. return false;
  213. if (!get_opt_int(argc, argv, &params->height, "video height"))
  214. return false;
  215. if (!get_opt_int(argc, argv, &params->color_primaries,
  216. "video color primaries"))
  217. return false;
  218. if (!get_opt_int(argc, argv, &params->color_trc,
  219. "video color trc"))
  220. return false;
  221. if (!get_opt_int(argc, argv, &params->colorspace,
  222. "video colorspace"))
  223. return false;
  224. if (!get_opt_int(argc, argv, &params->color_range,
  225. "video color range"))
  226. return false;
  227. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  228. return false;
  229. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  230. return false;
  231. }
  232. if (params->tracks) {
  233. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  234. return false;
  235. audio = calloc(params->tracks, sizeof(*audio));
  236. for (int i = 0; i < params->tracks; i++) {
  237. if (!get_audio_params(&audio[i], argc, argv)) {
  238. free(audio);
  239. return false;
  240. }
  241. }
  242. }
  243. *p_audio = audio;
  244. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  245. return true;
  246. }
  247. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  248. const char *name, AVCodec **codec)
  249. {
  250. const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(name);
  251. if (!desc) {
  252. fprintf(stderr, "Couldn't find encoder '%s'\n", name);
  253. return false;
  254. }
  255. *codec = avcodec_find_encoder(desc->id);
  256. if (!*codec) {
  257. fprintf(stderr, "Couldn't create encoder\n");
  258. return false;
  259. }
  260. *stream = avformat_new_stream(ffm->output, *codec);
  261. if (!*stream) {
  262. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  263. name);
  264. return false;
  265. }
  266. (*stream)->id = ffm->output->nb_streams - 1;
  267. return true;
  268. }
  269. static void create_video_stream(struct ffmpeg_mux *ffm)
  270. {
  271. AVCodec *codec;
  272. AVCodecContext *context;
  273. void *extradata = NULL;
  274. if (!new_stream(ffm, &ffm->video_stream, ffm->params.vcodec, &codec))
  275. return;
  276. if (ffm->video_header.size) {
  277. extradata = av_memdup(ffm->video_header.data,
  278. ffm->video_header.size);
  279. }
  280. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  281. context = avcodec_alloc_context3(codec);
  282. #else
  283. context = ffm->video_stream->codec;
  284. #endif
  285. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  286. context->width = ffm->params.width;
  287. context->height = ffm->params.height;
  288. context->coded_width = ffm->params.width;
  289. context->coded_height = ffm->params.height;
  290. context->color_primaries = ffm->params.color_primaries;
  291. context->color_trc = ffm->params.color_trc;
  292. context->colorspace = ffm->params.colorspace;
  293. context->color_range = ffm->params.color_range;
  294. context->extradata = extradata;
  295. context->extradata_size = ffm->video_header.size;
  296. context->time_base =
  297. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  298. ffm->video_stream->time_base = context->time_base;
  299. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  300. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  301. context->flags |= CODEC_FLAG_GLOBAL_H;
  302. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  303. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  304. #endif
  305. ffm->video_ctx = context;
  306. }
  307. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  308. {
  309. AVCodec *codec;
  310. AVCodecContext *context;
  311. AVStream *stream;
  312. void *extradata = NULL;
  313. if (!new_stream(ffm, &stream, ffm->params.acodec, &codec))
  314. return;
  315. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  316. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  317. if (ffm->audio_header[idx].size) {
  318. extradata = av_memdup(ffm->audio_header[idx].data,
  319. ffm->audio_header[idx].size);
  320. }
  321. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  322. context = avcodec_alloc_context3(codec);
  323. #else
  324. context = stream->codec;
  325. #endif
  326. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  327. context->channels = ffm->audio[idx].channels;
  328. context->sample_rate = ffm->audio[idx].sample_rate;
  329. context->sample_fmt = AV_SAMPLE_FMT_S16;
  330. context->time_base = stream->time_base;
  331. context->extradata = extradata;
  332. context->extradata_size = ffm->audio_header[idx].size;
  333. context->channel_layout =
  334. av_get_default_channel_layout(context->channels);
  335. //AVlib default channel layout for 4 channels is 4.0 ; fix for quad
  336. if (context->channels == 4)
  337. context->channel_layout = av_get_channel_layout("quad");
  338. //AVlib default channel layout for 5 channels is 5.0 ; fix for 4.1
  339. if (context->channels == 5)
  340. context->channel_layout = av_get_channel_layout("4.1");
  341. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  342. context->flags |= CODEC_FLAG_GLOBAL_H;
  343. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  344. avcodec_parameters_from_context(stream->codecpar, context);
  345. #endif
  346. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  347. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  348. ffm->num_audio_streams++;
  349. }
  350. static bool init_streams(struct ffmpeg_mux *ffm)
  351. {
  352. if (ffm->params.has_video)
  353. create_video_stream(ffm);
  354. if (ffm->params.tracks) {
  355. ffm->audio_infos =
  356. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  357. for (int i = 0; i < ffm->params.tracks; i++)
  358. create_audio_stream(ffm, i);
  359. }
  360. if (!ffm->video_stream && !ffm->num_audio_streams)
  361. return false;
  362. return true;
  363. }
  364. static void set_header(struct header *header, uint8_t *data, size_t size)
  365. {
  366. header->size = (int)size;
  367. header->data = malloc(size);
  368. memcpy(header->data, data, size);
  369. }
  370. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  371. struct ffm_packet_info *info)
  372. {
  373. if (info->type == FFM_PACKET_VIDEO) {
  374. set_header(&ffm->video_header, data, (size_t)info->size);
  375. } else {
  376. set_header(&ffm->audio_header[info->index], data,
  377. (size_t)info->size);
  378. }
  379. }
  380. static size_t safe_read(void *vdata, size_t size)
  381. {
  382. uint8_t *data = vdata;
  383. size_t total = size;
  384. while (size > 0) {
  385. size_t in_size = fread(data, 1, size, stdin);
  386. if (in_size == 0)
  387. return 0;
  388. size -= in_size;
  389. data += in_size;
  390. }
  391. return total;
  392. }
  393. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  394. {
  395. struct ffm_packet_info info = {0};
  396. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  397. if (success) {
  398. uint8_t *data = malloc(info.size);
  399. if (safe_read(data, info.size) == info.size) {
  400. ffmpeg_mux_header(ffm, data, &info);
  401. } else {
  402. success = false;
  403. }
  404. free(data);
  405. }
  406. return success;
  407. }
  408. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  409. {
  410. if (ffm->params.has_video) {
  411. if (!ffmpeg_mux_get_header(ffm)) {
  412. return false;
  413. }
  414. }
  415. for (int i = 0; i < ffm->params.tracks; i++) {
  416. if (!ffmpeg_mux_get_header(ffm)) {
  417. return false;
  418. }
  419. }
  420. return true;
  421. }
  422. #ifdef _MSC_VER
  423. #pragma warning(disable : 4996)
  424. #endif
  425. static inline int open_output_file(struct ffmpeg_mux *ffm)
  426. {
  427. AVOutputFormat *format = ffm->output->oformat;
  428. int ret;
  429. if ((format->flags & AVFMT_NOFILE) == 0) {
  430. ret = avio_open(&ffm->output->pb, ffm->params.file,
  431. AVIO_FLAG_WRITE);
  432. if (ret < 0) {
  433. fprintf(stderr, "Couldn't open '%s', %s\n",
  434. ffm->params.file, av_err2str(ret));
  435. return FFM_ERROR;
  436. }
  437. }
  438. AVDictionary *dict = NULL;
  439. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  440. " ", 0))) {
  441. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  442. av_err2str(ret), ffm->params.muxer_settings);
  443. av_dict_free(&dict);
  444. }
  445. if (av_dict_count(dict) > 0) {
  446. printf("Using muxer settings:");
  447. AVDictionaryEntry *entry = NULL;
  448. while ((entry = av_dict_get(dict, "", entry,
  449. AV_DICT_IGNORE_SUFFIX)))
  450. printf("\n\t%s=%s", entry->key, entry->value);
  451. printf("\n");
  452. }
  453. ret = avformat_write_header(ffm->output, &dict);
  454. if (ret < 0) {
  455. fprintf(stderr, "Error opening '%s': %s\n", ffm->params.file,
  456. av_err2str(ret));
  457. av_dict_free(&dict);
  458. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  459. }
  460. av_dict_free(&dict);
  461. return FFM_SUCCESS;
  462. }
  463. #define SRT_PROTO "srt"
  464. #define UDP_PROTO "udp"
  465. #define TCP_PROTO "tcp"
  466. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  467. {
  468. AVOutputFormat *output_format;
  469. int ret;
  470. bool is_network = false;
  471. if (strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) == 0 ||
  472. strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) == 0 ||
  473. strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) == 0)
  474. is_network = true;
  475. if (is_network) {
  476. avformat_network_init();
  477. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  478. } else {
  479. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  480. }
  481. if (output_format == NULL) {
  482. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  483. ffm->params.file);
  484. return FFM_ERROR;
  485. }
  486. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  487. ffm->params.file);
  488. if (ret < 0) {
  489. fprintf(stderr, "Couldn't initialize output context: %s\n",
  490. av_err2str(ret));
  491. return FFM_ERROR;
  492. }
  493. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  494. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  495. if (!init_streams(ffm)) {
  496. free_avformat(ffm);
  497. return FFM_ERROR;
  498. }
  499. ret = open_output_file(ffm);
  500. if (ret != FFM_SUCCESS) {
  501. free_avformat(ffm);
  502. return ret;
  503. }
  504. return FFM_SUCCESS;
  505. }
  506. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  507. char *argv[])
  508. {
  509. argc--;
  510. argv++;
  511. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  512. return FFM_ERROR;
  513. if (ffm->params.tracks) {
  514. ffm->audio_header =
  515. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  516. }
  517. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  518. av_register_all();
  519. #endif
  520. if (!ffmpeg_mux_get_extra_data(ffm))
  521. return FFM_ERROR;
  522. /* ffmpeg does not have a way of telling what's supported
  523. * for a given output format, so we try each possibility */
  524. return ffmpeg_mux_init_context(ffm);
  525. }
  526. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  527. {
  528. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  529. if (ret != FFM_SUCCESS) {
  530. ffmpeg_mux_free(ffm);
  531. return ret;
  532. }
  533. ffm->initialized = true;
  534. return ret;
  535. }
  536. static inline int get_index(struct ffmpeg_mux *ffm,
  537. struct ffm_packet_info *info)
  538. {
  539. if (info->type == FFM_PACKET_VIDEO) {
  540. if (ffm->video_stream) {
  541. return ffm->video_stream->id;
  542. }
  543. } else {
  544. if ((int)info->index < ffm->num_audio_streams) {
  545. return ffm->audio_infos[info->index].stream->id;
  546. }
  547. }
  548. return -1;
  549. }
  550. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  551. struct ffm_packet_info *info)
  552. {
  553. if (info->type == FFM_PACKET_VIDEO) {
  554. if (ffm->video_stream) {
  555. return ffm->video_ctx;
  556. }
  557. } else {
  558. if ((int)info->index < ffm->num_audio_streams) {
  559. return ffm->audio_infos[info->index].ctx;
  560. }
  561. }
  562. return NULL;
  563. }
  564. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  565. {
  566. return ffm->output->streams[idx];
  567. }
  568. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  569. AVRational codec_time_base, int64_t val,
  570. int idx)
  571. {
  572. AVStream *stream = get_stream(ffm, idx);
  573. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  574. stream->time_base,
  575. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  576. }
  577. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  578. struct ffm_packet_info *info)
  579. {
  580. int idx = get_index(ffm, info);
  581. AVPacket packet = {0};
  582. /* The muxer might not support video/audio, or multiple audio tracks */
  583. if (idx == -1) {
  584. return true;
  585. }
  586. const AVRational codec_time_base =
  587. get_codec_context(ffm, info)->time_base;
  588. av_init_packet(&packet);
  589. packet.data = buf;
  590. packet.size = (int)info->size;
  591. packet.stream_index = idx;
  592. packet.pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  593. packet.dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  594. if (info->keyframe)
  595. packet.flags = AV_PKT_FLAG_KEY;
  596. int ret = av_interleaved_write_frame(ffm->output, &packet);
  597. if (ret < 0) {
  598. fprintf(stderr, "av_interleaved_write_frame failed: %s\n",
  599. av_err2str(ret));
  600. }
  601. return ret >= 0;
  602. }
  603. /* ------------------------------------------------------------------------- */
  604. #ifdef _WIN32
  605. int wmain(int argc, wchar_t *argv_w[])
  606. #else
  607. int main(int argc, char *argv[])
  608. #endif
  609. {
  610. struct ffm_packet_info info = {0};
  611. struct ffmpeg_mux ffm = {0};
  612. struct resize_buf rb = {0};
  613. bool fail = false;
  614. int ret;
  615. #ifdef _WIN32
  616. char **argv;
  617. SetErrorMode(SEM_FAILCRITICALERRORS);
  618. argv = malloc(argc * sizeof(char *));
  619. for (int i = 0; i < argc; i++) {
  620. size_t len = wcslen(argv_w[i]);
  621. int size;
  622. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  623. NULL, 0, NULL, NULL);
  624. argv[i] = malloc(size + 1);
  625. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  626. size + 1, NULL, NULL);
  627. argv[i][size] = 0;
  628. }
  629. _setmode(_fileno(stdin), O_BINARY);
  630. #endif
  631. setvbuf(stderr, NULL, _IONBF, 0);
  632. ret = ffmpeg_mux_init(&ffm, argc, argv);
  633. if (ret != FFM_SUCCESS) {
  634. fprintf(stderr, "Couldn't initialize muxer\n");
  635. return ret;
  636. }
  637. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  638. resize_buf_resize(&rb, info.size);
  639. if (safe_read(rb.buf, info.size) == info.size) {
  640. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  641. } else {
  642. fail = true;
  643. }
  644. }
  645. ffmpeg_mux_free(&ffm);
  646. resize_buf_free(&rb);
  647. #ifdef _WIN32
  648. for (int i = 0; i < argc; i++)
  649. free(argv[i]);
  650. free(argv);
  651. #endif
  652. return 0;
  653. }