ffmpeg-mux.c 24 KB

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