ffmpeg-mux.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. /*
  2. * Copyright (c) 2023 Lain 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/threading.h>
  26. #include <util/platform.h>
  27. #include <util/deque.h>
  28. #include <util/dstr.h>
  29. #include <libavcodec/avcodec.h>
  30. #include <libavformat/avformat.h>
  31. #include <libavutil/channel_layout.h>
  32. #include <libavutil/mastering_display_metadata.h>
  33. #define ANSI_COLOR_RED "\x1b[0;91m"
  34. #define ANSI_COLOR_MAGENTA "\x1b[0;95m"
  35. #define ANSI_COLOR_RESET "\x1b[0m"
  36. #define AVIO_BUFFER_SIZE 65536
  37. /* ------------------------------------------------------------------------- */
  38. static char *global_stream_key = "";
  39. struct resize_buf {
  40. uint8_t *buf;
  41. size_t size;
  42. size_t capacity;
  43. };
  44. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  45. {
  46. if (!rb->buf) {
  47. rb->buf = malloc(size);
  48. rb->size = size;
  49. rb->capacity = size;
  50. } else {
  51. if (rb->capacity < size) {
  52. size_t capx2 = rb->capacity * 2;
  53. size_t new_cap = capx2 > size ? capx2 : size;
  54. rb->buf = realloc(rb->buf, new_cap);
  55. rb->capacity = new_cap;
  56. }
  57. rb->size = size;
  58. }
  59. }
  60. static inline void resize_buf_free(struct resize_buf *rb)
  61. {
  62. free(rb->buf);
  63. }
  64. /* ------------------------------------------------------------------------- */
  65. struct main_params {
  66. char *file;
  67. /* printable_file is file with any stream key information removed */
  68. struct dstr printable_file;
  69. int has_video;
  70. int tracks;
  71. char *vcodec;
  72. int vbitrate;
  73. int gop;
  74. int width;
  75. int height;
  76. int fps_num;
  77. int fps_den;
  78. int color_primaries;
  79. int color_trc;
  80. int colorspace;
  81. int color_range;
  82. int chroma_sample_location;
  83. int max_luminance;
  84. char *acodec;
  85. char *muxer_settings;
  86. int codec_tag;
  87. };
  88. struct audio_params {
  89. char *name;
  90. int abitrate;
  91. int sample_rate;
  92. int frame_size;
  93. int channels;
  94. };
  95. struct header {
  96. uint8_t *data;
  97. int size;
  98. };
  99. struct audio_info {
  100. AVStream *stream;
  101. AVCodecContext *ctx;
  102. };
  103. struct io_header {
  104. uint64_t seek_offset;
  105. size_t data_length;
  106. };
  107. struct io_buffer {
  108. bool active;
  109. bool shutdown_requested;
  110. bool output_error;
  111. os_event_t *buffer_space_available_event;
  112. os_event_t *new_data_available_event;
  113. pthread_t io_thread;
  114. pthread_mutex_t data_mutex;
  115. FILE *output_file;
  116. struct deque data;
  117. uint64_t next_pos;
  118. };
  119. struct ffmpeg_mux {
  120. AVFormatContext *output;
  121. AVStream *video_stream;
  122. AVCodecContext *video_ctx;
  123. AVPacket *packet;
  124. struct audio_info *audio_infos;
  125. struct main_params params;
  126. struct audio_params *audio;
  127. struct header video_header;
  128. struct header *audio_header;
  129. int num_audio_streams;
  130. bool initialized;
  131. struct io_buffer io;
  132. };
  133. #define SRT_PROTO "srt"
  134. #define UDP_PROTO "udp"
  135. #define TCP_PROTO "tcp"
  136. #define HTTP_PROTO "http"
  137. #define RIST_PROTO "rist"
  138. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  139. {
  140. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  141. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  142. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  143. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  144. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  145. }
  146. static void header_free(struct header *header)
  147. {
  148. free(header->data);
  149. }
  150. static void free_avformat(struct ffmpeg_mux *ffm)
  151. {
  152. if (ffm->output) {
  153. avcodec_free_context(&ffm->video_ctx);
  154. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0) {
  155. if (!ffmpeg_mux_is_network(ffm)) {
  156. av_free(ffm->output->pb->buffer);
  157. avio_context_free(&ffm->output->pb);
  158. } else {
  159. avio_close(ffm->output->pb);
  160. }
  161. }
  162. avformat_free_context(ffm->output);
  163. ffm->output = NULL;
  164. }
  165. if (ffm->audio_infos) {
  166. for (int i = 0; i < ffm->num_audio_streams; ++i)
  167. avcodec_free_context(&ffm->audio_infos[i].ctx);
  168. free(ffm->audio_infos);
  169. }
  170. ffm->video_stream = NULL;
  171. ffm->audio_infos = NULL;
  172. ffm->num_audio_streams = 0;
  173. }
  174. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  175. {
  176. if (ffm->initialized) {
  177. av_write_trailer(ffm->output);
  178. }
  179. // If we're writing to a file with the deque, shut it
  180. // down gracefully
  181. if (ffm->io.active) {
  182. os_atomic_set_bool(&ffm->io.shutdown_requested, true);
  183. // Wakes up the I/O thread and waits for it to finish
  184. pthread_mutex_lock(&ffm->io.data_mutex);
  185. os_event_signal(ffm->io.new_data_available_event);
  186. pthread_mutex_unlock(&ffm->io.data_mutex);
  187. pthread_join(ffm->io.io_thread, NULL);
  188. // Cleanup everything else
  189. os_event_destroy(ffm->io.new_data_available_event);
  190. os_event_destroy(ffm->io.buffer_space_available_event);
  191. pthread_mutex_destroy(&ffm->io.data_mutex);
  192. deque_free(&ffm->io.data);
  193. }
  194. free_avformat(ffm);
  195. header_free(&ffm->video_header);
  196. if (ffm->audio_header) {
  197. for (int i = 0; i < ffm->params.tracks; i++) {
  198. header_free(&ffm->audio_header[i]);
  199. }
  200. free(ffm->audio_header);
  201. }
  202. if (ffm->audio) {
  203. free(ffm->audio);
  204. }
  205. dstr_free(&ffm->params.printable_file);
  206. av_packet_free(&ffm->packet);
  207. memset(ffm, 0, sizeof(*ffm));
  208. }
  209. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  210. const char *opt)
  211. {
  212. int argc = *p_argc;
  213. char **argv = *p_argv;
  214. if (!argc) {
  215. printf("Missing expected option: '%s'\n", opt);
  216. return false;
  217. }
  218. (*p_argc)--;
  219. (*p_argv)++;
  220. *str = argv[0];
  221. return true;
  222. }
  223. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  224. {
  225. char *str;
  226. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  227. return false;
  228. }
  229. *i = atoi(str);
  230. return true;
  231. }
  232. static bool get_audio_params(struct audio_params *audio, int *argc,
  233. char ***argv)
  234. {
  235. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  236. return false;
  237. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  238. return false;
  239. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  240. return false;
  241. if (!get_opt_int(argc, argv, &audio->frame_size, "audio frame size"))
  242. return false;
  243. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  244. return false;
  245. return true;
  246. }
  247. static void ffmpeg_log_callback(void *param, int level, const char *format,
  248. va_list args)
  249. {
  250. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  251. char out_buffer[4096];
  252. struct dstr out = {0};
  253. vsnprintf(out_buffer, sizeof(out_buffer), format, args);
  254. dstr_copy(&out, out_buffer);
  255. if (global_stream_key && *global_stream_key) {
  256. dstr_replace(&out, global_stream_key, "{stream_key}");
  257. }
  258. switch (level) {
  259. case AV_LOG_INFO:
  260. fprintf(stdout, "info: [ffmpeg_muxer] %s", out.array);
  261. fflush(stdout);
  262. break;
  263. case AV_LOG_WARNING:
  264. fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s",
  265. ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET);
  266. fflush(stdout);
  267. break;
  268. case AV_LOG_ERROR:
  269. fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED,
  270. out.array, ANSI_COLOR_RESET);
  271. fflush(stderr);
  272. }
  273. dstr_free(&out);
  274. #else
  275. UNUSED_PARAMETER(level);
  276. UNUSED_PARAMETER(format);
  277. UNUSED_PARAMETER(args);
  278. #endif
  279. UNUSED_PARAMETER(param);
  280. }
  281. static bool init_params(int *argc, char ***argv, struct main_params *params,
  282. struct audio_params **p_audio)
  283. {
  284. struct audio_params *audio = NULL;
  285. if (!get_opt_str(argc, argv, &params->file, "file name"))
  286. return false;
  287. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  288. return false;
  289. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  290. return false;
  291. if (params->has_video > 1 || params->has_video < 0) {
  292. puts("Invalid number of video tracks\n");
  293. return false;
  294. }
  295. if (params->tracks < 0) {
  296. puts("Invalid number of audio tracks\n");
  297. return false;
  298. }
  299. if (params->has_video == 0 && params->tracks == 0) {
  300. puts("Must have at least 1 audio track or 1 video track\n");
  301. return false;
  302. }
  303. if (params->has_video) {
  304. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  305. return false;
  306. if (!get_opt_int(argc, argv, &params->vbitrate,
  307. "video bitrate"))
  308. return false;
  309. if (!get_opt_int(argc, argv, &params->width, "video width"))
  310. return false;
  311. if (!get_opt_int(argc, argv, &params->height, "video height"))
  312. return false;
  313. if (!get_opt_int(argc, argv, &params->color_primaries,
  314. "video color primaries"))
  315. return false;
  316. if (!get_opt_int(argc, argv, &params->color_trc,
  317. "video color trc"))
  318. return false;
  319. if (!get_opt_int(argc, argv, &params->colorspace,
  320. "video colorspace"))
  321. return false;
  322. if (!get_opt_int(argc, argv, &params->color_range,
  323. "video color range"))
  324. return false;
  325. if (!get_opt_int(argc, argv, &params->chroma_sample_location,
  326. "video chroma sample location"))
  327. return false;
  328. if (!get_opt_int(argc, argv, &params->max_luminance,
  329. "video max luminance"))
  330. return false;
  331. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  332. return false;
  333. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  334. return false;
  335. if (!get_opt_int(argc, argv, &params->codec_tag,
  336. "video codec tag"))
  337. params->codec_tag = 0;
  338. }
  339. if (params->tracks) {
  340. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  341. return false;
  342. audio = calloc(params->tracks, sizeof(*audio));
  343. for (int i = 0; i < params->tracks; i++) {
  344. if (!get_audio_params(&audio[i], argc, argv)) {
  345. free(audio);
  346. return false;
  347. }
  348. }
  349. }
  350. *p_audio = audio;
  351. dstr_copy(&params->printable_file, params->file);
  352. get_opt_str(argc, argv, &global_stream_key, "stream key");
  353. if (strcmp(global_stream_key, "") != 0) {
  354. dstr_replace(&params->printable_file, global_stream_key,
  355. "{stream_key}");
  356. }
  357. av_log_set_callback(ffmpeg_log_callback);
  358. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  359. return true;
  360. }
  361. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  362. const char *name)
  363. {
  364. *stream = avformat_new_stream(ffm->output, NULL);
  365. if (!*stream) {
  366. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  367. name);
  368. return false;
  369. }
  370. (*stream)->id = ffm->output->nb_streams - 1;
  371. return true;
  372. }
  373. static void create_video_stream(struct ffmpeg_mux *ffm)
  374. {
  375. AVCodecContext *context;
  376. void *extradata = NULL;
  377. const char *name = ffm->params.vcodec;
  378. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  379. if (!codec) {
  380. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  381. return;
  382. }
  383. if (!new_stream(ffm, &ffm->video_stream, name))
  384. return;
  385. if (ffm->video_header.size) {
  386. extradata = av_memdup(ffm->video_header.data,
  387. ffm->video_header.size);
  388. }
  389. context = avcodec_alloc_context3(NULL);
  390. context->codec_type = codec->type;
  391. context->codec_id = codec->id;
  392. context->codec_tag = ffm->params.codec_tag;
  393. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  394. context->width = ffm->params.width;
  395. context->height = ffm->params.height;
  396. context->coded_width = ffm->params.width;
  397. context->coded_height = ffm->params.height;
  398. context->color_primaries = ffm->params.color_primaries;
  399. context->color_trc = ffm->params.color_trc;
  400. context->colorspace = ffm->params.colorspace;
  401. context->color_range = ffm->params.color_range;
  402. context->chroma_sample_location = ffm->params.chroma_sample_location;
  403. context->extradata = extradata;
  404. context->extradata_size = ffm->video_header.size;
  405. context->time_base =
  406. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  407. ffm->video_stream->time_base = context->time_base;
  408. #if LIBAVFORMAT_VERSION_MAJOR < 59
  409. // codec->time_base may still be used if LIBAVFORMAT_VERSION_MAJOR < 59
  410. PRAGMA_WARN_PUSH
  411. PRAGMA_WARN_DEPRECATION
  412. ffm->video_stream->codec->time_base = context->time_base;
  413. PRAGMA_WARN_POP
  414. #endif
  415. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  416. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  417. context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  418. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  419. const int max_luminance = ffm->params.max_luminance;
  420. if (max_luminance > 0) {
  421. size_t content_size;
  422. AVContentLightMetadata *const content =
  423. av_content_light_metadata_alloc(&content_size);
  424. content->MaxCLL = max_luminance;
  425. content->MaxFALL = max_luminance;
  426. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(60, 31, 102)
  427. av_stream_add_side_data(ffm->video_stream,
  428. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  429. (uint8_t *)content, content_size);
  430. #else
  431. av_packet_side_data_add(
  432. &ffm->video_stream->codecpar->coded_side_data,
  433. &ffm->video_stream->codecpar->nb_coded_side_data,
  434. AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content,
  435. content_size, 0);
  436. #endif
  437. AVMasteringDisplayMetadata *const mastering =
  438. av_mastering_display_metadata_alloc();
  439. mastering->display_primaries[0][0] = av_make_q(17, 25);
  440. mastering->display_primaries[0][1] = av_make_q(8, 25);
  441. mastering->display_primaries[1][0] = av_make_q(53, 200);
  442. mastering->display_primaries[1][1] = av_make_q(69, 100);
  443. mastering->display_primaries[2][0] = av_make_q(3, 20);
  444. mastering->display_primaries[2][1] = av_make_q(3, 50);
  445. mastering->white_point[0] = av_make_q(3127, 10000);
  446. mastering->white_point[1] = av_make_q(329, 1000);
  447. mastering->min_luminance = av_make_q(0, 1);
  448. mastering->max_luminance = av_make_q(max_luminance, 1);
  449. mastering->has_primaries = 1;
  450. mastering->has_luminance = 1;
  451. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(60, 31, 102)
  452. av_stream_add_side_data(ffm->video_stream,
  453. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  454. (uint8_t *)mastering,
  455. sizeof(*mastering));
  456. #else
  457. av_packet_side_data_add(
  458. &ffm->video_stream->codecpar->coded_side_data,
  459. &ffm->video_stream->codecpar->nb_coded_side_data,
  460. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  461. (uint8_t *)mastering, sizeof(*mastering), 0);
  462. #endif
  463. }
  464. ffm->video_ctx = context;
  465. }
  466. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  467. {
  468. AVCodecContext *context;
  469. AVStream *stream;
  470. void *extradata = NULL;
  471. const char *name = ffm->params.acodec;
  472. int channels;
  473. const AVCodecDescriptor *codec_desc =
  474. avcodec_descriptor_get_by_name(name);
  475. if (!codec_desc) {
  476. fprintf(stderr, "Couldn't find codec descriptor '%s'\n", name);
  477. return;
  478. }
  479. const AVCodec *codec = avcodec_find_encoder(codec_desc->id);
  480. if (!codec) {
  481. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  482. return;
  483. }
  484. if (!new_stream(ffm, &stream, name))
  485. return;
  486. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  487. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  488. if (ffm->audio_header[idx].size) {
  489. extradata = av_memdup(ffm->audio_header[idx].data,
  490. ffm->audio_header[idx].size);
  491. }
  492. context = avcodec_alloc_context3(NULL);
  493. context->codec_type = codec->type;
  494. context->codec_id = codec->id;
  495. if (!(codec_desc->props & AV_CODEC_PROP_LOSSLESS))
  496. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  497. channels = ffm->audio[idx].channels;
  498. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  499. context->channels = channels;
  500. #endif
  501. context->sample_rate = ffm->audio[idx].sample_rate;
  502. if (!(codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  503. context->frame_size = ffm->audio[idx].frame_size;
  504. context->time_base = stream->time_base;
  505. context->extradata = extradata;
  506. context->extradata_size = ffm->audio_header[idx].size;
  507. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  508. context->channel_layout = av_get_default_channel_layout(channels);
  509. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  510. if (channels == 5)
  511. context->channel_layout = av_get_channel_layout("4.1");
  512. #else
  513. av_channel_layout_default(&context->ch_layout, channels);
  514. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  515. if (channels == 5)
  516. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  517. #endif
  518. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  519. context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  520. avcodec_parameters_from_context(stream->codecpar, context);
  521. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  522. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  523. ffm->num_audio_streams++;
  524. }
  525. static bool init_streams(struct ffmpeg_mux *ffm)
  526. {
  527. if (ffm->params.has_video)
  528. create_video_stream(ffm);
  529. if (ffm->params.tracks) {
  530. ffm->audio_infos =
  531. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  532. for (int i = 0; i < ffm->params.tracks; i++)
  533. create_audio_stream(ffm, i);
  534. }
  535. if (!ffm->video_stream && !ffm->num_audio_streams)
  536. return false;
  537. return true;
  538. }
  539. static void set_header(struct header *header, uint8_t *data, size_t size)
  540. {
  541. header->size = (int)size;
  542. header->data = malloc(size);
  543. memcpy(header->data, data, size);
  544. }
  545. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  546. struct ffm_packet_info *info)
  547. {
  548. if (info->type == FFM_PACKET_VIDEO) {
  549. set_header(&ffm->video_header, data, (size_t)info->size);
  550. } else {
  551. set_header(&ffm->audio_header[info->index], data,
  552. (size_t)info->size);
  553. }
  554. }
  555. static size_t safe_read(void *vdata, size_t size)
  556. {
  557. uint8_t *data = vdata;
  558. size_t total = size;
  559. while (size > 0) {
  560. size_t in_size = fread(data, 1, size, stdin);
  561. if (in_size == 0)
  562. return 0;
  563. size -= in_size;
  564. data += in_size;
  565. }
  566. return total;
  567. }
  568. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  569. {
  570. struct ffm_packet_info info = {0};
  571. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  572. if (success) {
  573. uint8_t *data = malloc(info.size);
  574. if (safe_read(data, info.size) == info.size) {
  575. ffmpeg_mux_header(ffm, data, &info);
  576. } else {
  577. success = false;
  578. }
  579. free(data);
  580. }
  581. return success;
  582. }
  583. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  584. {
  585. if (ffm->params.has_video) {
  586. if (!ffmpeg_mux_get_header(ffm)) {
  587. return false;
  588. }
  589. }
  590. for (int i = 0; i < ffm->params.tracks; i++) {
  591. if (!ffmpeg_mux_get_header(ffm)) {
  592. return false;
  593. }
  594. }
  595. return true;
  596. }
  597. #ifdef _MSC_VER
  598. #pragma warning(disable : 4996)
  599. #endif
  600. #define CHUNK_SIZE 1048576
  601. static void *ffmpeg_mux_io_thread(void *data)
  602. {
  603. struct ffmpeg_mux *ffm = data;
  604. // Chunk collects the writes into a larger batch
  605. size_t chunk_used = 0;
  606. unsigned char *chunk = malloc(CHUNK_SIZE);
  607. if (!chunk) {
  608. os_atomic_set_bool(&ffm->io.output_error, true);
  609. fprintf(stderr, "Error allocating memory for output\n");
  610. goto error;
  611. }
  612. bool shutting_down;
  613. bool want_seek = false;
  614. bool force_flush_chunk = false;
  615. // current_seek_position is a virtual position updated as we read from
  616. // the buffer, if it becomes discontinuous due to a seek request from
  617. // ffmpeg, then we flush the chunk. next_seek_position is the actual
  618. // offset we should seek to when we write the chunk.
  619. uint64_t current_seek_position = 0;
  620. uint64_t next_seek_position;
  621. for (;;) {
  622. // Wait for ffmpeg to write data to the buffer
  623. os_event_wait(ffm->io.new_data_available_event);
  624. // Loop to write in chunk_size chunks
  625. for (;;) {
  626. shutting_down = os_atomic_load_bool(
  627. &ffm->io.shutdown_requested);
  628. pthread_mutex_lock(&ffm->io.data_mutex);
  629. // Fetch as many writes as possible from the deque
  630. // and fill up our local chunk. This may involve seeking
  631. // if ffmpeg needs to, so take care of that as well.
  632. for (;;) {
  633. size_t available = ffm->io.data.size;
  634. // Buffer is empty (now) or was already empty (we got
  635. // woken up to exit)
  636. if (!available)
  637. break;
  638. // Get seek offset and data size
  639. struct io_header header;
  640. deque_peek_front(&ffm->io.data, &header,
  641. sizeof(header));
  642. // Do we need to seek?
  643. if (header.seek_offset !=
  644. current_seek_position) {
  645. // If there's already part of a chunk pending,
  646. // flush it at the current offset. Similarly,
  647. // if we already plan to seek, then seek.
  648. if (chunk_used || want_seek) {
  649. force_flush_chunk = true;
  650. break;
  651. }
  652. // Mark that we need to seek and where to
  653. want_seek = true;
  654. next_seek_position = header.seek_offset;
  655. // Update our virtual position
  656. current_seek_position =
  657. header.seek_offset;
  658. }
  659. // Make sure there's enough room for the data, if
  660. // not then force a flush
  661. if (header.data_length + chunk_used >
  662. CHUNK_SIZE) {
  663. force_flush_chunk = true;
  664. break;
  665. }
  666. // Remove header that we already read
  667. deque_pop_front(&ffm->io.data, NULL,
  668. sizeof(header));
  669. // Copy from the buffer to our local chunk
  670. deque_pop_front(&ffm->io.data,
  671. chunk + chunk_used,
  672. header.data_length);
  673. // Update offsets
  674. chunk_used += header.data_length;
  675. current_seek_position += header.data_length;
  676. }
  677. // Signal that there is more room in the buffer
  678. os_event_signal(ffm->io.buffer_space_available_event);
  679. // Try to avoid lots of small writes unless this was the final
  680. // data left in the buffer. The buffer might be entirely empty
  681. // if we were woken up to exit.
  682. if (!force_flush_chunk &&
  683. (!chunk_used ||
  684. (chunk_used < 65536 && !shutting_down))) {
  685. os_event_reset(
  686. ffm->io.new_data_available_event);
  687. pthread_mutex_unlock(&ffm->io.data_mutex);
  688. break;
  689. }
  690. pthread_mutex_unlock(&ffm->io.data_mutex);
  691. // Seek if we need to
  692. if (want_seek) {
  693. os_fseeki64(ffm->io.output_file,
  694. next_seek_position, SEEK_SET);
  695. // Update the next virtual position, making sure to take
  696. // into account the size of the chunk we're about to write.
  697. current_seek_position =
  698. next_seek_position + chunk_used;
  699. want_seek = false;
  700. }
  701. // Write the current chunk to the output file
  702. if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) !=
  703. 1) {
  704. os_atomic_set_bool(&ffm->io.output_error, true);
  705. fprintf(stderr, "Error writing to '%s', %s\n",
  706. ffm->params.printable_file.array,
  707. strerror(errno));
  708. goto error;
  709. }
  710. chunk_used = 0;
  711. force_flush_chunk = false;
  712. }
  713. // If this was the last chunk, time to exit
  714. if (shutting_down)
  715. break;
  716. }
  717. error:
  718. if (chunk)
  719. free(chunk);
  720. fclose(ffm->io.output_file);
  721. return NULL;
  722. }
  723. static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset,
  724. int whence)
  725. {
  726. struct ffmpeg_mux *ffm = opaque;
  727. // If the output thread failed, signal that back up the stack
  728. if (os_atomic_load_bool(&ffm->io.output_error))
  729. return -1;
  730. // Update where the next write should go
  731. pthread_mutex_lock(&ffm->io.data_mutex);
  732. if (whence == SEEK_SET)
  733. ffm->io.next_pos = offset;
  734. else if (whence == SEEK_CUR)
  735. ffm->io.next_pos += offset;
  736. pthread_mutex_unlock(&ffm->io.data_mutex);
  737. return 0;
  738. }
  739. #if LIBAVFORMAT_VERSION_MAJOR >= 61
  740. static int ffmpeg_mux_write_av_buffer(void *opaque, const uint8_t *buf,
  741. int buf_size)
  742. #else
  743. static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size)
  744. #endif
  745. {
  746. struct ffmpeg_mux *ffm = opaque;
  747. // If the output thread failed, signal that back up the stack
  748. if (os_atomic_load_bool(&ffm->io.output_error))
  749. return -1;
  750. for (;;) {
  751. pthread_mutex_lock(&ffm->io.data_mutex);
  752. // Avoid unbounded growth of the deque, cap to 256 MB
  753. if (ffm->io.data.capacity >= 256 * 1048576 &&
  754. ffm->io.data.capacity - ffm->io.data.size <
  755. buf_size + sizeof(struct io_header)) {
  756. // No space, wait for the I/O thread to make space
  757. os_event_reset(ffm->io.buffer_space_available_event);
  758. pthread_mutex_unlock(&ffm->io.data_mutex);
  759. os_event_wait(ffm->io.buffer_space_available_event);
  760. } else {
  761. break;
  762. }
  763. }
  764. struct io_header header;
  765. header.data_length = buf_size;
  766. header.seek_offset = ffm->io.next_pos;
  767. // Copy the data into the buffer
  768. deque_push_back(&ffm->io.data, &header, sizeof(header));
  769. deque_push_back(&ffm->io.data, buf, buf_size);
  770. // Advance the next write position
  771. ffm->io.next_pos += buf_size;
  772. // Tell the I/O thread that there's new data to be written
  773. os_event_signal(ffm->io.new_data_available_event);
  774. pthread_mutex_unlock(&ffm->io.data_mutex);
  775. return buf_size;
  776. }
  777. static inline int open_output_file(struct ffmpeg_mux *ffm)
  778. {
  779. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  780. AVOutputFormat *format = ffm->output->oformat;
  781. #else
  782. const AVOutputFormat *format = ffm->output->oformat;
  783. #endif
  784. int ret;
  785. if ((format->flags & AVFMT_NOFILE) == 0) {
  786. if (!ffmpeg_mux_is_network(ffm)) {
  787. // If not outputting to a network, write to a deque
  788. // instead of relying on ffmpeg disk output. This hopefully
  789. // works around too small buffers somewhere causing output
  790. // stalls when recording.
  791. // We're in charge of managing the actual file now
  792. ffm->io.output_file = os_fopen(ffm->params.file, "wb");
  793. if (!ffm->io.output_file) {
  794. fprintf(stderr, "Couldn't open '%s', %s\n",
  795. ffm->params.printable_file.array,
  796. strerror(errno));
  797. return FFM_ERROR;
  798. }
  799. // Start at 1MB, this can grow up to 256 MB depending
  800. // how fast data is going in and out (limited in
  801. // ffmpeg_mux_write_av_buffer)
  802. deque_reserve(&ffm->io.data, 1048576);
  803. pthread_mutex_init(&ffm->io.data_mutex, NULL);
  804. os_event_init(&ffm->io.buffer_space_available_event,
  805. OS_EVENT_TYPE_AUTO);
  806. os_event_init(&ffm->io.new_data_available_event,
  807. OS_EVENT_TYPE_AUTO);
  808. pthread_create(&ffm->io.io_thread, NULL,
  809. ffmpeg_mux_io_thread, ffm);
  810. unsigned char *avio_ctx_buffer =
  811. av_malloc(AVIO_BUFFER_SIZE);
  812. ffm->output->pb = avio_alloc_context(
  813. avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL,
  814. ffmpeg_mux_write_av_buffer,
  815. ffmpeg_mux_seek_av_buffer);
  816. ffm->io.active = true;
  817. } else {
  818. ret = avio_open(&ffm->output->pb, ffm->params.file,
  819. AVIO_FLAG_WRITE);
  820. if (ret < 0) {
  821. fprintf(stderr, "Couldn't open '%s', %s\n",
  822. ffm->params.printable_file.array,
  823. av_err2str(ret));
  824. return FFM_ERROR;
  825. }
  826. }
  827. }
  828. AVDictionary *dict = NULL;
  829. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  830. " ", 0))) {
  831. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  832. av_err2str(ret), ffm->params.muxer_settings);
  833. av_dict_free(&dict);
  834. }
  835. if (av_dict_count(dict) > 0) {
  836. printf("Using muxer settings:");
  837. AVDictionaryEntry *entry = NULL;
  838. while ((entry = av_dict_get(dict, "", entry,
  839. AV_DICT_IGNORE_SUFFIX)))
  840. printf("\n\t%s=%s", entry->key, entry->value);
  841. printf("\n");
  842. }
  843. ret = avformat_write_header(ffm->output, &dict);
  844. if (ret < 0) {
  845. fprintf(stderr, "Error opening '%s': %s",
  846. ffm->params.printable_file.array, av_err2str(ret));
  847. av_dict_free(&dict);
  848. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  849. }
  850. av_dict_free(&dict);
  851. return FFM_SUCCESS;
  852. }
  853. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  854. {
  855. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  856. AVOutputFormat *output_format;
  857. #else
  858. const AVOutputFormat *output_format;
  859. #endif
  860. int ret;
  861. bool is_http = false;
  862. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  863. sizeof(HTTP_PROTO) - 1) == 0);
  864. bool is_network = ffmpeg_mux_is_network(ffm);
  865. if (is_network) {
  866. avformat_network_init();
  867. }
  868. if (is_network && !is_http)
  869. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  870. else
  871. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  872. if (output_format == NULL) {
  873. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  874. ffm->params.printable_file.array);
  875. return FFM_ERROR;
  876. }
  877. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  878. printf("info: Output format name and long_name: %s, %s\n",
  879. output_format->name ? output_format->name : "unknown",
  880. output_format->long_name ? output_format->long_name : "unknown");
  881. #endif
  882. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  883. ffm->params.file);
  884. if (ret < 0) {
  885. fprintf(stderr, "Couldn't initialize output context: %s\n",
  886. av_err2str(ret));
  887. return FFM_ERROR;
  888. }
  889. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  890. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  891. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  892. #endif
  893. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 0, 100)
  894. /* Allow FLAC/OPUS in MP4 */
  895. ffm->output->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  896. #endif
  897. if (!init_streams(ffm)) {
  898. free_avformat(ffm);
  899. return FFM_ERROR;
  900. }
  901. ret = open_output_file(ffm);
  902. if (ret != FFM_SUCCESS) {
  903. free_avformat(ffm);
  904. return ret;
  905. }
  906. return FFM_SUCCESS;
  907. }
  908. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  909. char *argv[])
  910. {
  911. argc--;
  912. argv++;
  913. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  914. return FFM_ERROR;
  915. if (ffm->params.tracks) {
  916. ffm->audio_header =
  917. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  918. }
  919. if (!ffmpeg_mux_get_extra_data(ffm))
  920. return FFM_ERROR;
  921. ffm->packet = av_packet_alloc();
  922. /* ffmpeg does not have a way of telling what's supported
  923. * for a given output format, so we try each possibility */
  924. return ffmpeg_mux_init_context(ffm);
  925. }
  926. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  927. {
  928. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  929. if (ret != FFM_SUCCESS) {
  930. ffmpeg_mux_free(ffm);
  931. return ret;
  932. }
  933. ffm->initialized = true;
  934. return ret;
  935. }
  936. static inline int get_index(struct ffmpeg_mux *ffm,
  937. struct ffm_packet_info *info)
  938. {
  939. if (info->type == FFM_PACKET_VIDEO) {
  940. if (ffm->video_stream) {
  941. return ffm->video_stream->id;
  942. }
  943. } else {
  944. if ((int)info->index < ffm->num_audio_streams) {
  945. return ffm->audio_infos[info->index].stream->id;
  946. }
  947. }
  948. return -1;
  949. }
  950. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  951. struct ffm_packet_info *info)
  952. {
  953. if (info->type == FFM_PACKET_VIDEO) {
  954. if (ffm->video_stream) {
  955. return ffm->video_ctx;
  956. }
  957. } else {
  958. if ((int)info->index < ffm->num_audio_streams) {
  959. return ffm->audio_infos[info->index].ctx;
  960. }
  961. }
  962. return NULL;
  963. }
  964. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  965. {
  966. return ffm->output->streams[idx];
  967. }
  968. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  969. AVRational codec_time_base, int64_t val,
  970. int idx)
  971. {
  972. AVStream *stream = get_stream(ffm, idx);
  973. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  974. stream->time_base,
  975. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  976. }
  977. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  978. struct ffm_packet_info *info)
  979. {
  980. int idx = get_index(ffm, info);
  981. /* The muxer might not support video/audio, or multiple audio tracks */
  982. if (idx == -1) {
  983. return true;
  984. }
  985. const AVRational codec_time_base =
  986. get_codec_context(ffm, info)->time_base;
  987. ffm->packet->data = buf;
  988. ffm->packet->size = (int)info->size;
  989. ffm->packet->stream_index = idx;
  990. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  991. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  992. if (info->keyframe)
  993. ffm->packet->flags = AV_PKT_FLAG_KEY;
  994. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  995. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  996. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  997. return true;
  998. }
  999. if (ret < 0) {
  1000. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  1001. ret, av_err2str(ret));
  1002. }
  1003. return ret >= 0;
  1004. }
  1005. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  1006. struct resize_buf *filename, int argc,
  1007. char **argv)
  1008. {
  1009. resize_buf_resize(filename, size + 1);
  1010. if (safe_read(filename->buf, size) != size) {
  1011. return false;
  1012. }
  1013. filename->buf[size] = 0;
  1014. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  1015. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  1016. #endif
  1017. int ret;
  1018. char *argv1_backup = argv[1];
  1019. argv[1] = (char *)filename->buf;
  1020. ffmpeg_mux_free(ffm);
  1021. ret = ffmpeg_mux_init(ffm, argc, argv);
  1022. if (ret != FFM_SUCCESS) {
  1023. fprintf(stderr, "Couldn't initialize muxer\n");
  1024. return false;
  1025. }
  1026. argv[1] = argv1_backup;
  1027. return true;
  1028. }
  1029. /* ------------------------------------------------------------------------- */
  1030. #ifdef _WIN32
  1031. int wmain(int argc, wchar_t *argv_w[])
  1032. #else
  1033. int main(int argc, char *argv[])
  1034. #endif
  1035. {
  1036. struct ffm_packet_info info = {0};
  1037. struct ffmpeg_mux ffm = {0};
  1038. struct resize_buf rb = {0};
  1039. struct resize_buf rb_filename = {0};
  1040. bool fail = false;
  1041. int ret;
  1042. #ifdef _WIN32
  1043. char **argv;
  1044. SetErrorMode(SEM_FAILCRITICALERRORS);
  1045. argv = malloc(argc * sizeof(char *));
  1046. for (int i = 0; i < argc; i++) {
  1047. size_t len = wcslen(argv_w[i]);
  1048. int size;
  1049. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  1050. NULL, 0, NULL, NULL);
  1051. argv[i] = malloc(size + 1);
  1052. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  1053. size + 1, NULL, NULL);
  1054. argv[i][size] = 0;
  1055. }
  1056. _setmode(_fileno(stdin), O_BINARY);
  1057. #endif
  1058. setvbuf(stderr, NULL, _IONBF, 0);
  1059. ret = ffmpeg_mux_init(&ffm, argc, argv);
  1060. if (ret != FFM_SUCCESS) {
  1061. fprintf(stderr, "Couldn't initialize muxer\n");
  1062. return ret;
  1063. }
  1064. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  1065. if (info.type == FFM_PACKET_CHANGE_FILE) {
  1066. fail = !read_change_file(&ffm, info.size, &rb_filename,
  1067. argc, argv);
  1068. continue;
  1069. }
  1070. resize_buf_resize(&rb, info.size);
  1071. if (safe_read(rb.buf, info.size) == info.size) {
  1072. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  1073. } else {
  1074. fail = true;
  1075. }
  1076. }
  1077. ffmpeg_mux_free(&ffm);
  1078. resize_buf_free(&rb);
  1079. resize_buf_free(&rb_filename);
  1080. #ifdef _WIN32
  1081. for (int i = 0; i < argc; i++)
  1082. free(argv[i]);
  1083. free(argv);
  1084. #endif
  1085. return 0;
  1086. }