ffmpeg-mux.c 21 KB

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