media-remux.c 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /******************************************************************************
  2. Copyright (C) 2023 by Ruwen Hahn <palana@stunned.de>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "media-remux.h"
  15. #include "../util/base.h"
  16. #include "../util/bmem.h"
  17. #include "../util/platform.h"
  18. #include <libavformat/avformat.h>
  19. #include <libavcodec/version.h>
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. struct media_remux_job {
  23. int64_t in_size;
  24. AVFormatContext *ifmt_ctx, *ofmt_ctx;
  25. };
  26. static inline void init_size(media_remux_job_t job, const char *in_filename)
  27. {
  28. #ifdef _MSC_VER
  29. struct _stat64 st = {0};
  30. _stat64(in_filename, &st);
  31. #else
  32. struct stat st = {0};
  33. stat(in_filename, &st);
  34. #endif
  35. job->in_size = st.st_size;
  36. }
  37. static inline bool init_input(media_remux_job_t job, const char *in_filename)
  38. {
  39. int ret = avformat_open_input(&job->ifmt_ctx, in_filename, NULL, NULL);
  40. if (ret < 0) {
  41. blog(LOG_ERROR, "media_remux: Could not open input file '%s'", in_filename);
  42. return false;
  43. }
  44. ret = avformat_find_stream_info(job->ifmt_ctx, NULL);
  45. if (ret < 0) {
  46. blog(LOG_ERROR, "media_remux: Failed to retrieve input stream"
  47. " information");
  48. return false;
  49. }
  50. #ifndef NDEBUG
  51. av_dump_format(job->ifmt_ctx, 0, in_filename, false);
  52. #endif
  53. return true;
  54. }
  55. static inline bool init_output(media_remux_job_t job, const char *out_filename)
  56. {
  57. int ret;
  58. avformat_alloc_output_context2(&job->ofmt_ctx, NULL, NULL, out_filename);
  59. if (!job->ofmt_ctx) {
  60. blog(LOG_ERROR, "media_remux: Could not create output context");
  61. return false;
  62. }
  63. for (unsigned i = 0; i < job->ifmt_ctx->nb_streams; i++) {
  64. AVStream *in_stream = job->ifmt_ctx->streams[i];
  65. AVStream *out_stream = avformat_new_stream(job->ofmt_ctx, NULL);
  66. if (!out_stream) {
  67. blog(LOG_ERROR, "media_remux: Failed to allocate output"
  68. " stream");
  69. return false;
  70. }
  71. ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
  72. if (ret < 0) {
  73. blog(LOG_ERROR, "media_remux: Failed to copy parameters");
  74. return false;
  75. }
  76. av_dict_copy(&out_stream->metadata, in_stream->metadata, 0);
  77. if (in_stream->codecpar->codec_id == AV_CODEC_ID_HEVC && job->ofmt_ctx->oformat->codec_tag &&
  78. av_codec_get_id(job->ofmt_ctx->oformat->codec_tag, MKTAG('h', 'v', 'c', '1')) ==
  79. out_stream->codecpar->codec_id) {
  80. // Tag HEVC files with industry standard HVC1 tag for wider device compatibility
  81. // when HVC1 tag is supported by out stream codec
  82. out_stream->codecpar->codec_tag = MKTAG('h', 'v', 'c', '1');
  83. } else {
  84. // Otherwise tag 0 to let FFmpeg automatically select the appropriate tag
  85. out_stream->codecpar->codec_tag = 0;
  86. }
  87. if (in_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  88. av_channel_layout_default(&out_stream->codecpar->ch_layout,
  89. in_stream->codecpar->ch_layout.nb_channels);
  90. /* The avutil default channel layout for 5 channels is
  91. * 5.0, which OBS does not support. Manually set 5
  92. * channels to 4.1. */
  93. if (in_stream->codecpar->ch_layout.nb_channels == 5)
  94. out_stream->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  95. }
  96. }
  97. #ifndef NDEBUG
  98. av_dump_format(job->ofmt_ctx, 0, out_filename, true);
  99. #endif
  100. if (!(job->ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
  101. ret = avio_open(&job->ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
  102. if (ret < 0) {
  103. blog(LOG_ERROR,
  104. "media_remux: Failed to open output"
  105. " file '%s'",
  106. out_filename);
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. bool media_remux_job_create(media_remux_job_t *job, const char *in_filename, const char *out_filename)
  113. {
  114. if (!job)
  115. return false;
  116. *job = NULL;
  117. if (!os_file_exists(in_filename))
  118. return false;
  119. if (strcmp(in_filename, out_filename) == 0)
  120. return false;
  121. *job = (media_remux_job_t)bzalloc(sizeof(struct media_remux_job));
  122. if (!*job)
  123. return false;
  124. init_size(*job, in_filename);
  125. if (!init_input(*job, in_filename))
  126. goto fail;
  127. if (!init_output(*job, out_filename))
  128. goto fail;
  129. return true;
  130. fail:
  131. media_remux_job_destroy(*job);
  132. return false;
  133. }
  134. static inline void process_packet(AVPacket *pkt, AVStream *in_stream, AVStream *out_stream)
  135. {
  136. pkt->pts = av_rescale_q_rnd(pkt->pts, in_stream->time_base, out_stream->time_base,
  137. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  138. pkt->dts = av_rescale_q_rnd(pkt->dts, in_stream->time_base, out_stream->time_base,
  139. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  140. pkt->duration = (int)av_rescale_q(pkt->duration, in_stream->time_base, out_stream->time_base);
  141. pkt->pos = -1;
  142. }
  143. static inline int process_packets(media_remux_job_t job, media_remux_progress_callback callback, void *data)
  144. {
  145. AVPacket pkt;
  146. int ret, throttle = 0;
  147. for (;;) {
  148. ret = av_read_frame(job->ifmt_ctx, &pkt);
  149. if (ret < 0) {
  150. if (ret != AVERROR_EOF)
  151. blog(LOG_ERROR,
  152. "media_remux: Error reading"
  153. " packet: %s",
  154. av_err2str(ret));
  155. break;
  156. }
  157. if (callback != NULL && throttle++ > 10) {
  158. float progress = pkt.pos / (float)job->in_size * 100.f;
  159. if (!callback(data, progress))
  160. break;
  161. throttle = 0;
  162. }
  163. process_packet(&pkt, job->ifmt_ctx->streams[pkt.stream_index],
  164. job->ofmt_ctx->streams[pkt.stream_index]);
  165. ret = av_interleaved_write_frame(job->ofmt_ctx, &pkt);
  166. av_packet_unref(&pkt);
  167. if (ret < 0) {
  168. blog(LOG_ERROR, "media_remux: Error muxing packet: %s", av_err2str(ret));
  169. /* Treat "Invalid data found when processing input" and
  170. * "Invalid argument" as non-fatal */
  171. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL)
  172. continue;
  173. break;
  174. }
  175. }
  176. return ret;
  177. }
  178. bool media_remux_job_process(media_remux_job_t job, media_remux_progress_callback callback, void *data)
  179. {
  180. int ret;
  181. bool success = false;
  182. if (!job)
  183. return success;
  184. ret = avformat_write_header(job->ofmt_ctx, NULL);
  185. if (ret < 0) {
  186. blog(LOG_ERROR, "media_remux: Error opening output file: %s", av_err2str(ret));
  187. return success;
  188. }
  189. if (callback != NULL)
  190. callback(data, 0.f);
  191. ret = process_packets(job, callback, data);
  192. success = ret >= 0 || ret == AVERROR_EOF;
  193. ret = av_write_trailer(job->ofmt_ctx);
  194. if (ret < 0) {
  195. blog(LOG_ERROR, "media_remux: av_write_trailer: %s", av_err2str(ret));
  196. success = false;
  197. }
  198. if (callback != NULL)
  199. callback(data, 100.f);
  200. return success;
  201. }
  202. void media_remux_job_destroy(media_remux_job_t job)
  203. {
  204. if (!job)
  205. return;
  206. avformat_close_input(&job->ifmt_ctx);
  207. if (job->ofmt_ctx && !(job->ofmt_ctx->oformat->flags & AVFMT_NOFILE))
  208. avio_close(job->ofmt_ctx->pb);
  209. avformat_free_context(job->ofmt_ctx);
  210. bfree(job);
  211. }