ffmpeg-mux.c 21 KB

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