1
0

media-remux.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /******************************************************************************
  2. Copyright (C) 2023 by Ruwen Hahn <[email protected]>
  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. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(59, 20, 100)
  20. #include <libavcodec/version.h>
  21. #endif
  22. #include <sys/types.h>
  23. #include <sys/stat.h>
  24. #ifndef FF_API_BUFFER_SIZE_T
  25. #define FF_API_BUFFER_SIZE_T (LIBAVUTIL_VERSION_MAJOR < 57)
  26. #endif
  27. struct media_remux_job {
  28. int64_t in_size;
  29. AVFormatContext *ifmt_ctx, *ofmt_ctx;
  30. };
  31. static inline void init_size(media_remux_job_t job, const char *in_filename)
  32. {
  33. #ifdef _MSC_VER
  34. struct _stat64 st = {0};
  35. _stat64(in_filename, &st);
  36. #else
  37. struct stat st = {0};
  38. stat(in_filename, &st);
  39. #endif
  40. job->in_size = st.st_size;
  41. }
  42. static inline bool init_input(media_remux_job_t job, const char *in_filename)
  43. {
  44. int ret = avformat_open_input(&job->ifmt_ctx, in_filename, NULL, NULL);
  45. if (ret < 0) {
  46. blog(LOG_ERROR, "media_remux: Could not open input file '%s'",
  47. in_filename);
  48. return false;
  49. }
  50. ret = avformat_find_stream_info(job->ifmt_ctx, NULL);
  51. if (ret < 0) {
  52. blog(LOG_ERROR, "media_remux: Failed to retrieve input stream"
  53. " information");
  54. return false;
  55. }
  56. #ifndef NDEBUG
  57. av_dump_format(job->ifmt_ctx, 0, in_filename, false);
  58. #endif
  59. return true;
  60. }
  61. static inline bool init_output(media_remux_job_t job, const char *out_filename)
  62. {
  63. int ret;
  64. avformat_alloc_output_context2(&job->ofmt_ctx, NULL, NULL,
  65. out_filename);
  66. if (!job->ofmt_ctx) {
  67. blog(LOG_ERROR, "media_remux: Could not create output context");
  68. return false;
  69. }
  70. for (unsigned i = 0; i < job->ifmt_ctx->nb_streams; i++) {
  71. AVStream *in_stream = job->ifmt_ctx->streams[i];
  72. AVStream *out_stream = avformat_new_stream(job->ofmt_ctx, NULL);
  73. if (!out_stream) {
  74. blog(LOG_ERROR, "media_remux: Failed to allocate output"
  75. " stream");
  76. return false;
  77. }
  78. #if FF_API_BUFFER_SIZE_T
  79. int content_size;
  80. #else
  81. size_t content_size;
  82. #endif
  83. const uint8_t *const content_src = av_stream_get_side_data(
  84. in_stream, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  85. &content_size);
  86. if (content_src) {
  87. uint8_t *const content_dst = av_stream_new_side_data(
  88. out_stream, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  89. content_size);
  90. if (content_dst)
  91. memcpy(content_dst, content_src, content_size);
  92. }
  93. #if FF_API_BUFFER_SIZE_T
  94. int mastering_size;
  95. #else
  96. size_t mastering_size;
  97. #endif
  98. const uint8_t *const mastering_src = av_stream_get_side_data(
  99. in_stream, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  100. &mastering_size);
  101. if (mastering_src) {
  102. uint8_t *const mastering_dst = av_stream_new_side_data(
  103. out_stream,
  104. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  105. mastering_size);
  106. if (mastering_dst) {
  107. memcpy(mastering_dst, mastering_src,
  108. mastering_size);
  109. }
  110. }
  111. ret = avcodec_parameters_copy(out_stream->codecpar,
  112. in_stream->codecpar);
  113. if (ret < 0) {
  114. blog(LOG_ERROR,
  115. "media_remux: Failed to copy parameters");
  116. return false;
  117. }
  118. av_dict_copy(&out_stream->metadata, in_stream->metadata, 0);
  119. if (in_stream->codecpar->codec_id == AV_CODEC_ID_HEVC &&
  120. job->ofmt_ctx->oformat->codec_tag &&
  121. av_codec_get_id(job->ofmt_ctx->oformat->codec_tag,
  122. MKTAG('h', 'v', 'c', '1')) ==
  123. out_stream->codecpar->codec_id) {
  124. // Tag HEVC files with industry standard HVC1 tag for wider device compatibility
  125. // when HVC1 tag is supported by out stream codec
  126. out_stream->codecpar->codec_tag =
  127. MKTAG('h', 'v', 'c', '1');
  128. } else {
  129. // Otherwise tag 0 to let FFmpeg automatically select the appropriate tag
  130. out_stream->codecpar->codec_tag = 0;
  131. }
  132. }
  133. #ifndef NDEBUG
  134. av_dump_format(job->ofmt_ctx, 0, out_filename, true);
  135. #endif
  136. if (!(job->ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
  137. ret = avio_open(&job->ofmt_ctx->pb, out_filename,
  138. AVIO_FLAG_WRITE);
  139. if (ret < 0) {
  140. blog(LOG_ERROR,
  141. "media_remux: Failed to open output"
  142. " file '%s'",
  143. out_filename);
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. bool media_remux_job_create(media_remux_job_t *job, const char *in_filename,
  150. const char *out_filename)
  151. {
  152. if (!job)
  153. return false;
  154. *job = NULL;
  155. if (!os_file_exists(in_filename))
  156. return false;
  157. if (strcmp(in_filename, out_filename) == 0)
  158. return false;
  159. *job = (media_remux_job_t)bzalloc(sizeof(struct media_remux_job));
  160. if (!*job)
  161. return false;
  162. init_size(*job, in_filename);
  163. if (!init_input(*job, in_filename))
  164. goto fail;
  165. if (!init_output(*job, out_filename))
  166. goto fail;
  167. return true;
  168. fail:
  169. media_remux_job_destroy(*job);
  170. return false;
  171. }
  172. static inline void process_packet(AVPacket *pkt, AVStream *in_stream,
  173. AVStream *out_stream)
  174. {
  175. pkt->pts = av_rescale_q_rnd(pkt->pts, in_stream->time_base,
  176. out_stream->time_base,
  177. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  178. pkt->dts = av_rescale_q_rnd(pkt->dts, in_stream->time_base,
  179. out_stream->time_base,
  180. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  181. pkt->duration = (int)av_rescale_q(pkt->duration, in_stream->time_base,
  182. out_stream->time_base);
  183. pkt->pos = -1;
  184. }
  185. static inline int process_packets(media_remux_job_t job,
  186. media_remux_progress_callback callback,
  187. void *data)
  188. {
  189. AVPacket pkt;
  190. int ret, throttle = 0;
  191. for (;;) {
  192. ret = av_read_frame(job->ifmt_ctx, &pkt);
  193. if (ret < 0) {
  194. if (ret != AVERROR_EOF)
  195. blog(LOG_ERROR,
  196. "media_remux: Error reading"
  197. " packet: %s",
  198. av_err2str(ret));
  199. break;
  200. }
  201. if (callback != NULL && throttle++ > 10) {
  202. float progress = pkt.pos / (float)job->in_size * 100.f;
  203. if (!callback(data, progress))
  204. break;
  205. throttle = 0;
  206. }
  207. process_packet(&pkt, job->ifmt_ctx->streams[pkt.stream_index],
  208. job->ofmt_ctx->streams[pkt.stream_index]);
  209. ret = av_interleaved_write_frame(job->ofmt_ctx, &pkt);
  210. av_packet_unref(&pkt);
  211. if (ret < 0) {
  212. blog(LOG_ERROR, "media_remux: Error muxing packet: %s",
  213. av_err2str(ret));
  214. /* Treat "Invalid data found when processing input" and
  215. * "Invalid argument" as non-fatal */
  216. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL)
  217. continue;
  218. break;
  219. }
  220. }
  221. return ret;
  222. }
  223. bool media_remux_job_process(media_remux_job_t job,
  224. media_remux_progress_callback callback, void *data)
  225. {
  226. int ret;
  227. bool success = false;
  228. if (!job)
  229. return success;
  230. ret = avformat_write_header(job->ofmt_ctx, NULL);
  231. if (ret < 0) {
  232. blog(LOG_ERROR, "media_remux: Error opening output file: %s",
  233. av_err2str(ret));
  234. return success;
  235. }
  236. if (callback != NULL)
  237. callback(data, 0.f);
  238. ret = process_packets(job, callback, data);
  239. success = ret >= 0 || ret == AVERROR_EOF;
  240. ret = av_write_trailer(job->ofmt_ctx);
  241. if (ret < 0) {
  242. blog(LOG_ERROR, "media_remux: av_write_trailer: %s",
  243. av_err2str(ret));
  244. success = false;
  245. }
  246. if (callback != NULL)
  247. callback(data, 100.f);
  248. return success;
  249. }
  250. void media_remux_job_destroy(media_remux_job_t job)
  251. {
  252. if (!job)
  253. return;
  254. avformat_close_input(&job->ifmt_ctx);
  255. if (job->ofmt_ctx && !(job->ofmt_ctx->oformat->flags & AVFMT_NOFILE))
  256. avio_close(job->ofmt_ctx->pb);
  257. avformat_free_context(job->ofmt_ctx);
  258. bfree(job);
  259. }