obs-ffmpeg-mpegts.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. /******************************************************************************
  2. Copyright (C) 2014 by Hugh Bailey <[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 <obs-module.h>
  15. #include <util/circlebuf.h>
  16. #include <util/threading.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include "obs-ffmpeg-output.h"
  21. #include "obs-ffmpeg-formats.h"
  22. #include "obs-ffmpeg-compat.h"
  23. #include "obs-ffmpeg-rist.h"
  24. #include "obs-ffmpeg-srt.h"
  25. #include <libavutil/channel_layout.h>
  26. #include <libavutil/mastering_display_metadata.h>
  27. /* ------------------------------------------------------------------------- */
  28. #define do_log(level, format, ...) \
  29. blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, \
  30. obs_output_get_name(stream->output), ##__VA_ARGS__)
  31. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  32. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  33. #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
  34. static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data,
  35. const char *error)
  36. {
  37. if (data->last_error)
  38. bfree(data->last_error);
  39. data->last_error = bstrdup(error);
  40. }
  41. void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data,
  42. const char *format, ...)
  43. {
  44. va_list args;
  45. char out[4096];
  46. va_start(args, format);
  47. vsnprintf(out, sizeof(out), format, args);
  48. va_end(args);
  49. ffmpeg_mpegts_set_last_error(data, out);
  50. blog(log_level, "%s", out);
  51. }
  52. static bool is_rist(struct ffmpeg_output *stream)
  53. {
  54. return !strncmp(stream->ff_data.config.url, RIST_PROTO,
  55. sizeof(RIST_PROTO) - 1);
  56. }
  57. static bool is_srt(struct ffmpeg_output *stream)
  58. {
  59. return !strncmp(stream->ff_data.config.url, SRT_PROTO,
  60. sizeof(SRT_PROTO) - 1);
  61. }
  62. static bool proto_is_allowed(struct ffmpeg_output *stream)
  63. {
  64. return !strncmp(stream->ff_data.config.url, UDP_PROTO,
  65. sizeof(UDP_PROTO) - 1) ||
  66. !strncmp(stream->ff_data.config.url, TCP_PROTO,
  67. sizeof(TCP_PROTO) - 1) ||
  68. !strncmp(stream->ff_data.config.url, HTTP_PROTO,
  69. sizeof(HTTP_PROTO) - 1);
  70. }
  71. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  72. const char *name)
  73. {
  74. *stream = avformat_new_stream(data->output, NULL);
  75. if (!*stream) {
  76. ffmpeg_mpegts_log_error(
  77. LOG_WARNING, data,
  78. "Couldn't create stream for encoder '%s'", name);
  79. return false;
  80. }
  81. (*stream)->id = data->output->nb_streams - 1;
  82. return true;
  83. }
  84. static bool get_audio_headers(struct ffmpeg_output *stream,
  85. struct ffmpeg_data *data, int idx)
  86. {
  87. AVCodecParameters *par = data->audio_infos[idx].stream->codecpar;
  88. obs_encoder_t *aencoder =
  89. obs_output_get_audio_encoder(stream->output, idx);
  90. struct encoder_packet packet = {
  91. .type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx};
  92. if (obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) {
  93. par->extradata = av_memdup(packet.data, packet.size);
  94. par->extradata_size = (int)packet.size;
  95. avcodec_parameters_to_context(data->audio_infos[idx].ctx, par);
  96. return 1;
  97. }
  98. return 0;
  99. }
  100. static bool get_video_headers(struct ffmpeg_output *stream,
  101. struct ffmpeg_data *data)
  102. {
  103. AVCodecParameters *par = data->video->codecpar;
  104. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  105. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  106. .timebase_den = 1};
  107. if (obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) {
  108. par->extradata = av_memdup(packet.data, packet.size);
  109. par->extradata_size = (int)packet.size;
  110. avcodec_parameters_to_context(data->video_ctx,
  111. data->video->codecpar);
  112. return 1;
  113. }
  114. return 0;
  115. }
  116. static bool create_video_stream(struct ffmpeg_output *stream,
  117. struct ffmpeg_data *data)
  118. {
  119. AVCodecContext *context;
  120. void *extradata = NULL;
  121. struct obs_video_info ovi;
  122. if (!obs_get_video_info(&ovi)) {
  123. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active video");
  124. return false;
  125. }
  126. const char *name = data->config.video_encoder;
  127. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  128. if (!codec) {
  129. error("Couldn't find codec '%s'", name);
  130. return false;
  131. }
  132. if (!new_stream(data, &data->video, name))
  133. return false;
  134. const bool pq = data->config.color_trc == AVCOL_TRC_SMPTE2084;
  135. const bool hlg = data->config.color_trc == AVCOL_TRC_ARIB_STD_B67;
  136. if (pq || hlg) {
  137. const int hdr_nominal_peak_level =
  138. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  139. : (hlg ? 1000 : 0);
  140. size_t content_size;
  141. AVContentLightMetadata *const content =
  142. av_content_light_metadata_alloc(&content_size);
  143. content->MaxCLL = hdr_nominal_peak_level;
  144. content->MaxFALL = hdr_nominal_peak_level;
  145. av_stream_add_side_data(data->video,
  146. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  147. (uint8_t *)content, content_size);
  148. AVMasteringDisplayMetadata *const mastering =
  149. av_mastering_display_metadata_alloc();
  150. mastering->display_primaries[0][0] = av_make_q(17, 25);
  151. mastering->display_primaries[0][1] = av_make_q(8, 25);
  152. mastering->display_primaries[1][0] = av_make_q(53, 200);
  153. mastering->display_primaries[1][1] = av_make_q(69, 100);
  154. mastering->display_primaries[2][0] = av_make_q(3, 20);
  155. mastering->display_primaries[2][1] = av_make_q(3, 50);
  156. mastering->white_point[0] = av_make_q(3127, 10000);
  157. mastering->white_point[1] = av_make_q(329, 1000);
  158. mastering->min_luminance = av_make_q(0, 1);
  159. mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1);
  160. mastering->has_primaries = 1;
  161. mastering->has_luminance = 1;
  162. av_stream_add_side_data(data->video,
  163. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  164. (uint8_t *)mastering,
  165. sizeof(*mastering));
  166. }
  167. context = avcodec_alloc_context3(NULL);
  168. context->codec_type = codec->type;
  169. context->codec_id = codec->id;
  170. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  171. context->width = data->config.scale_width;
  172. context->height = data->config.scale_height;
  173. context->coded_width = data->config.scale_width;
  174. context->coded_height = data->config.scale_height;
  175. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  176. context->gop_size = data->config.gop_size;
  177. context->pix_fmt = data->config.format;
  178. context->color_range = data->config.color_range;
  179. context->color_primaries = data->config.color_primaries;
  180. context->color_trc = data->config.color_trc;
  181. context->colorspace = data->config.colorspace;
  182. context->chroma_sample_location = determine_chroma_location(
  183. data->config.format, data->config.colorspace);
  184. context->thread_count = 0;
  185. data->video->time_base = context->time_base;
  186. #if LIBAVFORMAT_VERSION_MAJOR < 59
  187. data->video->codec->time_base = context->time_base;
  188. #endif
  189. data->video->avg_frame_rate = av_inv_q(context->time_base);
  190. data->video_ctx = context;
  191. data->config.width = data->config.scale_width;
  192. data->config.height = data->config.scale_height;
  193. avcodec_parameters_from_context(data->video->codecpar, context);
  194. return true;
  195. }
  196. static bool create_audio_stream(struct ffmpeg_output *stream,
  197. struct ffmpeg_data *data, int idx)
  198. {
  199. AVCodecContext *context;
  200. AVStream *avstream;
  201. void *extradata = NULL;
  202. struct obs_audio_info aoi;
  203. const char *name = data->config.audio_encoder;
  204. int channels;
  205. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  206. if (!codec) {
  207. warn("Couldn't find codec '%s'", name);
  208. return false;
  209. }
  210. if (!obs_get_audio_info(&aoi)) {
  211. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active audio");
  212. return false;
  213. }
  214. if (!new_stream(data, &avstream, data->config.audio_encoder))
  215. return false;
  216. context = avcodec_alloc_context3(NULL);
  217. context->codec_type = codec->type;
  218. context->codec_id = codec->id;
  219. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  220. context->time_base = (AVRational){1, aoi.samples_per_sec};
  221. channels = get_audio_channels(aoi.speakers);
  222. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  223. context->channels = get_audio_channels(aoi.speakers);
  224. #endif
  225. context->sample_rate = aoi.samples_per_sec;
  226. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  227. context->channel_layout =
  228. av_get_default_channel_layout(context->channels);
  229. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  230. if (aoi.speakers == SPEAKERS_4POINT1)
  231. context->channel_layout = av_get_channel_layout("4.1");
  232. #else
  233. av_channel_layout_default(&context->ch_layout, channels);
  234. if (aoi.speakers == SPEAKERS_4POINT1)
  235. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  236. #endif
  237. context->sample_fmt = AV_SAMPLE_FMT_S16;
  238. context->frame_size = data->config.frame_size;
  239. avstream->time_base = context->time_base;
  240. data->audio_samplerate = aoi.samples_per_sec;
  241. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  242. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  243. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  244. data->audio_infos[idx].stream = avstream;
  245. data->audio_infos[idx].ctx = context;
  246. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
  247. context);
  248. return true;
  249. }
  250. static inline bool init_streams(struct ffmpeg_output *stream,
  251. struct ffmpeg_data *data)
  252. {
  253. if (!create_video_stream(stream, data))
  254. return false;
  255. if (data->num_audio_streams) {
  256. data->audio_infos = calloc(data->num_audio_streams,
  257. sizeof(*data->audio_infos));
  258. for (int i = 0; i < data->num_audio_streams; i++) {
  259. if (!create_audio_stream(stream, data, i))
  260. return false;
  261. }
  262. }
  263. return true;
  264. }
  265. int ff_network_init(void)
  266. {
  267. #if HAVE_WINSOCK2_H
  268. WSADATA wsaData;
  269. if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  270. return 0;
  271. #endif
  272. return 1;
  273. }
  274. static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  275. {
  276. int err = 0;
  277. const char *url = stream->ff_data.config.url;
  278. if (!ff_network_init()) {
  279. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  280. "Couldn't initialize network");
  281. return AVERROR(EIO);
  282. }
  283. URLContext *uc = av_mallocz(sizeof(URLContext) + strlen(url) + 1);
  284. if (!uc) {
  285. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  286. "Couldn't allocate memory");
  287. goto fail;
  288. }
  289. uc->url = (char *)url;
  290. uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE
  291. : SRT_LIVE_DEFAULT_PAYLOAD_SIZE;
  292. uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext))
  293. : av_mallocz(sizeof(SRTContext));
  294. if (!uc->priv_data) {
  295. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  296. "Couldn't allocate memory");
  297. goto fail;
  298. }
  299. /* For SRT, pass streamid & passphrase; for RIST, pass passphrase, username
  300. * & password.
  301. */
  302. if (!is_rist) {
  303. SRTContext *context = (SRTContext *)uc->priv_data;
  304. context->streamid = NULL;
  305. if (stream->ff_data.config.key != NULL) {
  306. if (strlen(stream->ff_data.config.key))
  307. context->streamid =
  308. av_strdup(stream->ff_data.config.key);
  309. }
  310. context->passphrase = NULL;
  311. if (stream->ff_data.config.password != NULL) {
  312. if (strlen(stream->ff_data.config.password))
  313. context->passphrase = av_strdup(
  314. stream->ff_data.config.password);
  315. }
  316. } else {
  317. RISTContext *context = (RISTContext *)uc->priv_data;
  318. context->secret = NULL;
  319. if (stream->ff_data.config.key != NULL) {
  320. if (strlen(stream->ff_data.config.key))
  321. context->secret =
  322. bstrdup(stream->ff_data.config.key);
  323. }
  324. context->username = NULL;
  325. if (stream->ff_data.config.username != NULL) {
  326. if (strlen(stream->ff_data.config.username))
  327. context->username = bstrdup(
  328. stream->ff_data.config.username);
  329. }
  330. context->password = NULL;
  331. if (stream->ff_data.config.password != NULL) {
  332. if (strlen(stream->ff_data.config.password))
  333. context->password = bstrdup(
  334. stream->ff_data.config.password);
  335. }
  336. }
  337. stream->h = uc;
  338. if (is_rist)
  339. err = librist_open(uc, uc->url);
  340. else
  341. err = libsrt_open(uc, uc->url);
  342. if (err < 0)
  343. goto fail;
  344. return 0;
  345. fail:
  346. if (uc)
  347. av_freep(&uc->priv_data);
  348. av_freep(&uc);
  349. #if HAVE_WINSOCK2_H
  350. WSACleanup();
  351. #endif
  352. return err;
  353. }
  354. static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream,
  355. bool is_rist)
  356. {
  357. /* allocate buffers */
  358. uint8_t *buffer = NULL;
  359. int buffer_size;
  360. URLContext *h = stream->h;
  361. AVIOContext *s = NULL;
  362. buffer_size = UDP_DEFAULT_PAYLOAD_SIZE;
  363. buffer = av_malloc(buffer_size);
  364. if (!buffer)
  365. return AVERROR(ENOMEM);
  366. /* allocate custom avio_context */
  367. if (is_rist)
  368. s = avio_alloc_context(
  369. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  370. (int (*)(void *, uint8_t *, int))librist_write, NULL);
  371. else
  372. s = avio_alloc_context(
  373. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  374. (int (*)(void *, uint8_t *, int))libsrt_write, NULL);
  375. if (!s)
  376. goto fail;
  377. s->max_packet_size = h->max_packet_size;
  378. s->opaque = h;
  379. stream->s = s;
  380. stream->ff_data.output->pb = s;
  381. return 0;
  382. fail:
  383. av_freep(&buffer);
  384. return AVERROR(ENOMEM);
  385. }
  386. static inline int open_output_file(struct ffmpeg_output *stream,
  387. struct ffmpeg_data *data)
  388. {
  389. int ret;
  390. bool rist = is_rist(stream);
  391. bool srt = is_srt(stream);
  392. bool allowed_proto = proto_is_allowed(stream);
  393. AVDictionary *dict = NULL;
  394. /* Retrieve protocol settings for udp, tcp, rtp ... (not srt or rist).
  395. * These options will be passed to protocol by avio_open2 through dict.
  396. * The invalid options will be left in dict. */
  397. if (!rist && !srt) {
  398. if ((ret = av_dict_parse_string(&dict,
  399. data->config.protocol_settings,
  400. "=", " ", 0))) {
  401. ffmpeg_mpegts_log_error(
  402. LOG_WARNING, data,
  403. "Failed to parse protocol settings: %s, %s",
  404. data->config.protocol_settings,
  405. av_err2str(ret));
  406. av_dict_free(&dict);
  407. return OBS_OUTPUT_INVALID_STREAM;
  408. }
  409. if (av_dict_count(dict) > 0) {
  410. struct dstr str = {0};
  411. AVDictionaryEntry *entry = NULL;
  412. while ((entry = av_dict_get(dict, "", entry,
  413. AV_DICT_IGNORE_SUFFIX)))
  414. dstr_catf(&str, "\n\t%s=%s", entry->key,
  415. entry->value);
  416. info("Using protocol settings: %s", str.array);
  417. dstr_free(&str);
  418. }
  419. }
  420. /* Ensure h264 bitstream auto conversion from avcc to annex B */
  421. data->output->flags |= AVFMT_FLAG_AUTO_BSF;
  422. /* Open URL for rist, srt or other protocols compatible with mpegts
  423. * muxer supported by avformat (udp, tcp, rtp ...).
  424. */
  425. if (rist) {
  426. ret = connect_mpegts_url(stream, true);
  427. } else if (srt) {
  428. ret = connect_mpegts_url(stream, false);
  429. } else if (allowed_proto) {
  430. ret = avio_open2(&data->output->pb, data->config.url,
  431. AVIO_FLAG_WRITE, NULL, &dict);
  432. } else {
  433. info("[ffmpeg mpegts muxer]: Invalid protocol: %s",
  434. data->config.url);
  435. return OBS_OUTPUT_BAD_PATH;
  436. }
  437. if (ret < 0) {
  438. if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED ||
  439. ret == OBS_OUTPUT_INVALID_STREAM)) {
  440. error("Failed to open the url or invalid stream");
  441. } else {
  442. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  443. "Couldn't open '%s', %s",
  444. data->config.url,
  445. av_err2str(ret));
  446. av_dict_free(&dict);
  447. }
  448. return ret;
  449. }
  450. /* Log invalid protocol settings for all protocols except srt or rist.
  451. * Or for srt & rist, allocate custom avio_ctx which will host the
  452. * protocols write callbacks.
  453. */
  454. if (!rist && !srt) {
  455. if (av_dict_count(dict) > 0) {
  456. struct dstr str = {0};
  457. AVDictionaryEntry *entry = NULL;
  458. while ((entry = av_dict_get(dict, "", entry,
  459. AV_DICT_IGNORE_SUFFIX)))
  460. dstr_catf(&str, "\n\t%s=%s", entry->key,
  461. entry->value);
  462. info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s",
  463. str.array);
  464. dstr_free(&str);
  465. }
  466. av_dict_free(&dict);
  467. } else {
  468. ret = allocate_custom_aviocontext(stream, rist);
  469. if (ret < 0) {
  470. info("Couldn't allocate custom avio_context for url: '%s', %s",
  471. data->config.url, av_err2str(ret));
  472. return OBS_OUTPUT_INVALID_STREAM;
  473. }
  474. }
  475. return 0;
  476. }
  477. static void close_video(struct ffmpeg_data *data)
  478. {
  479. avcodec_free_context(&data->video_ctx);
  480. }
  481. static void close_audio(struct ffmpeg_data *data)
  482. {
  483. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  484. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  485. circlebuf_free(&data->excess_frames[idx][i]);
  486. if (data->samples[idx][0])
  487. av_freep(&data->samples[idx][0]);
  488. if (data->audio_infos[idx].ctx) {
  489. avcodec_free_context(&data->audio_infos[idx].ctx);
  490. }
  491. if (data->aframe[idx])
  492. av_frame_free(&data->aframe[idx]);
  493. }
  494. }
  495. static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  496. {
  497. int err = 0;
  498. AVIOContext *s = stream->s;
  499. if (!s)
  500. return;
  501. URLContext *h = s->opaque;
  502. if (!h)
  503. return; /* can happen when opening the url fails */
  504. /* close rist or srt URLs ; free URLContext */
  505. if (is_rist) {
  506. err = librist_close(h);
  507. } else {
  508. err = libsrt_close(h);
  509. }
  510. av_freep(&h->priv_data);
  511. av_freep(h);
  512. /* close custom avio_context for srt or rist */
  513. avio_flush(stream->s);
  514. stream->s->opaque = NULL;
  515. av_freep(&stream->s->buffer);
  516. avio_context_free(&stream->s);
  517. if (err)
  518. info("[ffmpeg mpegts muxer]: Error closing URL %s",
  519. stream->ff_data.config.url);
  520. }
  521. void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream,
  522. struct ffmpeg_data *data)
  523. {
  524. if (data->initialized)
  525. av_write_trailer(data->output);
  526. if (data->video)
  527. close_video(data);
  528. if (data->audio_infos) {
  529. close_audio(data);
  530. free(data->audio_infos);
  531. }
  532. if (data->output) {
  533. if (is_rist(stream) || is_srt(stream)) {
  534. close_mpegts_url(stream, is_rist(stream));
  535. } else {
  536. avio_close(data->output->pb);
  537. }
  538. avformat_free_context(data->output);
  539. data->video = NULL;
  540. data->audio_infos = NULL;
  541. data->output = NULL;
  542. data->num_audio_streams = 0;
  543. }
  544. if (data->last_error)
  545. bfree(data->last_error);
  546. memset(data, 0, sizeof(struct ffmpeg_data));
  547. }
  548. static inline const char *safe_str(const char *s)
  549. {
  550. if (s == NULL)
  551. return "(NULL)";
  552. else
  553. return s;
  554. }
  555. bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream,
  556. struct ffmpeg_data *data,
  557. struct ffmpeg_cfg *config)
  558. {
  559. memset(data, 0, sizeof(struct ffmpeg_data));
  560. data->config = *config;
  561. data->num_audio_streams = config->audio_mix_count;
  562. data->audio_tracks = config->audio_tracks;
  563. if (!config->url || !*config->url)
  564. return false;
  565. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  566. av_register_all();
  567. #endif
  568. avformat_network_init();
  569. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  570. AVOutputFormat *output_format;
  571. #else
  572. const AVOutputFormat *output_format;
  573. #endif
  574. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  575. if (output_format == NULL) {
  576. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  577. "Couldn't set output format to mpegts");
  578. goto fail;
  579. } else {
  580. info("Output format name and long_name: %s, %s",
  581. output_format->name ? output_format->name : "unknown",
  582. output_format->long_name ? output_format->long_name
  583. : "unknown");
  584. }
  585. avformat_alloc_output_context2(&data->output, output_format, NULL,
  586. data->config.url);
  587. if (!data->output) {
  588. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  589. "Couldn't create avformat context");
  590. goto fail;
  591. }
  592. return true;
  593. fail:
  594. warn("ffmpeg_data_init failed");
  595. return false;
  596. }
  597. /* ------------------------------------------------------------------------- */
  598. static inline bool stopping(struct ffmpeg_output *output)
  599. {
  600. return os_atomic_load_bool(&output->stopping);
  601. }
  602. static const char *ffmpeg_mpegts_getname(void *unused)
  603. {
  604. UNUSED_PARAMETER(unused);
  605. return obs_module_text("FFmpegMpegts");
  606. }
  607. static void ffmpeg_mpegts_log_callback(void *param, int level,
  608. const char *format, va_list args)
  609. {
  610. if (level <= AV_LOG_INFO)
  611. blogva(LOG_DEBUG, format, args);
  612. UNUSED_PARAMETER(param);
  613. }
  614. static void *ffmpeg_mpegts_create(obs_data_t *settings, obs_output_t *output)
  615. {
  616. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  617. pthread_mutex_init_value(&data->write_mutex);
  618. data->output = output;
  619. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  620. goto fail;
  621. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  622. goto fail;
  623. if (os_sem_init(&data->write_sem, 0) != 0)
  624. goto fail;
  625. av_log_set_callback(ffmpeg_mpegts_log_callback);
  626. UNUSED_PARAMETER(settings);
  627. return data;
  628. fail:
  629. pthread_mutex_destroy(&data->write_mutex);
  630. os_event_destroy(data->stop_event);
  631. bfree(data);
  632. return NULL;
  633. }
  634. static void ffmpeg_mpegts_full_stop(void *data);
  635. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output);
  636. static void ffmpeg_mpegts_destroy(void *data)
  637. {
  638. struct ffmpeg_output *output = data;
  639. if (output) {
  640. if (output->connecting)
  641. pthread_join(output->start_thread, NULL);
  642. ffmpeg_mpegts_full_stop(output);
  643. pthread_mutex_destroy(&output->write_mutex);
  644. os_sem_destroy(output->write_sem);
  645. os_event_destroy(output->stop_event);
  646. bfree(data);
  647. }
  648. }
  649. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  650. AVPacket *packet)
  651. {
  652. struct ffmpeg_data *data = &output->ff_data;
  653. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  654. uint64_t start_ts;
  655. AVRational time_base;
  656. if (data->video && data->video->index == packet->stream_index) {
  657. time_base = data->video->time_base;
  658. start_ts = output->video_start_ts;
  659. } else {
  660. time_base = data->audio_infos[0].stream->time_base;
  661. start_ts = output->audio_start_ts;
  662. }
  663. return start_ts + pause_offset +
  664. (uint64_t)av_rescale_q(packet->dts, time_base,
  665. (AVRational){1, 1000000000});
  666. }
  667. static int mpegts_process_packet(struct ffmpeg_output *output)
  668. {
  669. AVPacket *packet = NULL;
  670. int ret = 0;
  671. pthread_mutex_lock(&output->write_mutex);
  672. if (output->packets.num) {
  673. packet = output->packets.array[0];
  674. da_erase(output->packets, 0);
  675. }
  676. pthread_mutex_unlock(&output->write_mutex);
  677. if (!packet)
  678. return 0;
  679. //blog(LOG_DEBUG,
  680. // "size = %d, flags = %lX, stream = %d, "
  681. // "packets queued: %lu",
  682. // packet->size, packet->flags, packet->stream_index,
  683. // output->packets.num);
  684. if (stopping(output)) {
  685. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  686. if (sys_ts >= output->stop_ts) {
  687. ret = 0;
  688. goto end;
  689. }
  690. }
  691. output->total_bytes += packet->size;
  692. uint8_t *buf = packet->data;
  693. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  694. av_freep(&buf);
  695. if (ret < 0) {
  696. ffmpeg_mpegts_log_error(
  697. LOG_WARNING, &output->ff_data,
  698. "process_packet: Error writing packet: %s",
  699. av_err2str(ret));
  700. /* Treat "Invalid data found when processing input" and
  701. * "Invalid argument" as non-fatal */
  702. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  703. ret = 0;
  704. }
  705. }
  706. end:
  707. av_packet_free(&packet);
  708. return ret;
  709. }
  710. static void *write_thread(void *data)
  711. {
  712. struct ffmpeg_output *output = data;
  713. while (os_sem_wait(output->write_sem) == 0) {
  714. /* check to see if shutting down */
  715. if (os_event_try(output->stop_event) == 0)
  716. break;
  717. int ret = mpegts_process_packet(output);
  718. if (ret != 0) {
  719. int code = OBS_OUTPUT_DISCONNECTED;
  720. pthread_detach(output->write_thread);
  721. output->write_thread_active = false;
  722. if (ret == -ENOSPC)
  723. code = OBS_OUTPUT_NO_SPACE;
  724. obs_output_signal_stop(output->output, code);
  725. ffmpeg_mpegts_deactivate(output);
  726. break;
  727. }
  728. }
  729. os_atomic_set_bool(&output->active, false);
  730. return NULL;
  731. }
  732. static bool get_extradata(struct ffmpeg_output *stream)
  733. {
  734. struct ffmpeg_data *ff_data = &stream->ff_data;
  735. /* get extradata for av headers from encoders */
  736. if (!get_video_headers(stream, ff_data))
  737. return false;
  738. for (int i = 0; i < ff_data->num_audio_streams; i++) {
  739. if (!get_audio_headers(stream, ff_data, i))
  740. return false;
  741. }
  742. return true;
  743. }
  744. /* set ffmpeg_config & init write_thread & capture */
  745. static bool set_config(struct ffmpeg_output *stream)
  746. {
  747. struct ffmpeg_cfg config;
  748. bool success;
  749. int ret;
  750. int code;
  751. /* 1. Get URL/username/password from service & set format + mime-type. */
  752. obs_service_t *service;
  753. service = obs_output_get_service(stream->output);
  754. if (!service)
  755. return false;
  756. config.url = obs_service_get_url(service);
  757. config.username = obs_service_get_username(service);
  758. config.password = obs_service_get_password(service);
  759. config.key = obs_service_get_key(service);
  760. config.format_name = "mpegts";
  761. config.format_mime_type = "video/M2PT";
  762. /* 2. video settings */
  763. // 2.a) set video format from obs to FFmpeg
  764. video_t *video = obs_output_video(stream->output);
  765. config.format =
  766. obs_to_ffmpeg_video_format(video_output_get_format(video));
  767. if (config.format == AV_PIX_FMT_NONE) {
  768. blog(LOG_WARNING,
  769. "Invalid pixel format used for mpegts output");
  770. return false;
  771. }
  772. // 2.b) set colorspace, color_range & transfer characteristic (from voi)
  773. const struct video_output_info *voi = video_output_get_info(video);
  774. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  775. : AVCOL_RANGE_MPEG;
  776. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  777. : AVCOL_SPC_RGB;
  778. switch (voi->colorspace) {
  779. case VIDEO_CS_601:
  780. config.color_primaries = AVCOL_PRI_SMPTE170M;
  781. config.color_trc = AVCOL_TRC_SMPTE170M;
  782. config.colorspace = AVCOL_SPC_SMPTE170M;
  783. break;
  784. case VIDEO_CS_DEFAULT:
  785. case VIDEO_CS_709:
  786. config.color_primaries = AVCOL_PRI_BT709;
  787. config.color_trc = AVCOL_TRC_BT709;
  788. config.colorspace = AVCOL_SPC_BT709;
  789. break;
  790. case VIDEO_CS_SRGB:
  791. config.color_primaries = AVCOL_PRI_BT709;
  792. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  793. config.colorspace = AVCOL_SPC_BT709;
  794. break;
  795. case VIDEO_CS_2100_PQ:
  796. config.color_primaries = AVCOL_PRI_BT2020;
  797. config.color_trc = AVCOL_TRC_SMPTE2084;
  798. config.colorspace = AVCOL_SPC_BT2020_NCL;
  799. break;
  800. case VIDEO_CS_2100_HLG:
  801. config.color_primaries = AVCOL_PRI_BT2020;
  802. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  803. config.colorspace = AVCOL_SPC_BT2020_NCL;
  804. }
  805. // 2.c) set width & height
  806. config.width = (int)obs_output_get_width(stream->output);
  807. config.height = (int)obs_output_get_height(stream->output);
  808. config.scale_width = config.width;
  809. config.scale_height = config.height;
  810. // 2.d) set video codec & id from video encoder
  811. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  812. config.video_encoder = obs_encoder_get_codec(vencoder);
  813. if (strcmp(config.video_encoder, "h264") == 0)
  814. config.video_encoder_id = AV_CODEC_ID_H264;
  815. else
  816. config.video_encoder_id = AV_CODEC_ID_AV1;
  817. // 2.e) set video bitrate & gop through video encoder settings
  818. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  819. config.video_bitrate = (int)obs_data_get_int(settings, "bitrate");
  820. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  821. config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den
  822. : 250;
  823. obs_data_release(settings);
  824. /* 3. Audio settings */
  825. // 3.a) set audio encoder and id to aac
  826. obs_encoder_t *aencoder =
  827. obs_output_get_audio_encoder(stream->output, 0);
  828. config.audio_encoder = "aac";
  829. config.audio_encoder_id = AV_CODEC_ID_AAC;
  830. // 3.b) get audio bitrate from the audio encoder.
  831. settings = obs_encoder_get_settings(aencoder);
  832. config.audio_bitrate = (int)obs_data_get_int(settings, "bitrate");
  833. obs_data_release(settings);
  834. // 3.c set audio frame size
  835. config.frame_size = (int)obs_encoder_get_frame_size(aencoder);
  836. // 3.d) set the number of tracks
  837. // The UI for multiple tracks is not written for streaming outputs.
  838. // When it is, modify write_packet & uncomment :
  839. // config.audio_tracks = (int)obs_output_get_mixers(stream->output);
  840. // config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  841. config.audio_tracks = 1;
  842. config.audio_mix_count = 1;
  843. /* 4. Muxer & protocol settings */
  844. // This requires some UI to be written for the output.
  845. // at the service level unless one can load the output in the settings/stream screen.
  846. settings = obs_output_get_settings(stream->output);
  847. obs_data_set_default_string(settings, "muxer_settings", "");
  848. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  849. obs_data_release(settings);
  850. config.protocol_settings = "";
  851. /* 5. unused ffmpeg codec settings */
  852. config.video_settings = "";
  853. config.audio_settings = "";
  854. success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config);
  855. if (!success) {
  856. if (stream->ff_data.last_error) {
  857. obs_output_set_last_error(stream->output,
  858. stream->ff_data.last_error);
  859. }
  860. ffmpeg_mpegts_data_free(stream, &stream->ff_data);
  861. code = OBS_OUTPUT_INVALID_STREAM;
  862. goto fail;
  863. }
  864. struct ffmpeg_data *ff_data = &stream->ff_data;
  865. if (!stream->got_headers) {
  866. if (!init_streams(stream, ff_data)) {
  867. error("mpegts avstream failed to be created");
  868. code = OBS_OUTPUT_INVALID_STREAM;
  869. goto fail;
  870. }
  871. code = open_output_file(stream, ff_data);
  872. if (code != 0) {
  873. error("Failed to open the url");
  874. goto fail;
  875. }
  876. av_dump_format(ff_data->output, 0, NULL, 1);
  877. }
  878. if (!obs_output_can_begin_data_capture(stream->output, 0))
  879. return false;
  880. if (!obs_output_initialize_encoders(stream->output, 0))
  881. return false;
  882. ret = pthread_create(&stream->write_thread, NULL, write_thread, stream);
  883. if (ret != 0) {
  884. ffmpeg_mpegts_log_error(
  885. LOG_WARNING, &stream->ff_data,
  886. "ffmpeg_output_start: Failed to create write "
  887. "thread.");
  888. code = OBS_OUTPUT_ERROR;
  889. goto fail;
  890. }
  891. os_atomic_set_bool(&stream->active, true);
  892. stream->write_thread_active = true;
  893. stream->total_bytes = 0;
  894. obs_output_begin_data_capture(stream->output, 0);
  895. return true;
  896. fail:
  897. obs_output_signal_stop(stream->output, code);
  898. ffmpeg_mpegts_full_stop(stream);
  899. return false;
  900. }
  901. static void *start_thread(void *data)
  902. {
  903. struct ffmpeg_output *output = data;
  904. set_config(output);
  905. output->connecting = false;
  906. return NULL;
  907. }
  908. static bool ffmpeg_mpegts_start(void *data)
  909. {
  910. struct ffmpeg_output *output = data;
  911. int ret;
  912. if (output->connecting)
  913. return false;
  914. os_atomic_set_bool(&output->stopping, false);
  915. output->audio_start_ts = 0;
  916. output->video_start_ts = 0;
  917. output->total_bytes = 0;
  918. output->got_headers = false;
  919. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  920. return (output->connecting = (ret == 0));
  921. }
  922. static void ffmpeg_mpegts_full_stop(void *data)
  923. {
  924. struct ffmpeg_output *output = data;
  925. if (output->active) {
  926. obs_output_end_data_capture(output->output);
  927. ffmpeg_mpegts_deactivate(output);
  928. }
  929. }
  930. static void ffmpeg_mpegts_stop(void *data, uint64_t ts)
  931. {
  932. struct ffmpeg_output *output = data;
  933. if (output->active) {
  934. if (ts > 0) {
  935. output->stop_ts = ts;
  936. os_atomic_set_bool(&output->stopping, true);
  937. }
  938. ffmpeg_mpegts_full_stop(output);
  939. } else {
  940. obs_output_signal_stop(output->output, OBS_OUTPUT_SUCCESS);
  941. }
  942. }
  943. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output)
  944. {
  945. if (output->write_thread_active) {
  946. os_event_signal(output->stop_event);
  947. os_sem_post(output->write_sem);
  948. pthread_join(output->write_thread, NULL);
  949. output->write_thread_active = false;
  950. }
  951. pthread_mutex_lock(&output->write_mutex);
  952. for (size_t i = 0; i < output->packets.num; i++)
  953. av_packet_free(output->packets.array + i);
  954. da_free(output->packets);
  955. pthread_mutex_unlock(&output->write_mutex);
  956. ffmpeg_mpegts_data_free(output, &output->ff_data);
  957. }
  958. static uint64_t ffmpeg_mpegts_total_bytes(void *data)
  959. {
  960. struct ffmpeg_output *output = data;
  961. return output->total_bytes;
  962. }
  963. static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base,
  964. int64_t val)
  965. {
  966. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  967. stream->time_base,
  968. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  969. }
  970. /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer
  971. * where it will be processed in the write_thread by process_packet.
  972. */
  973. void mpegts_write_packet(struct ffmpeg_output *stream,
  974. struct encoder_packet *encpacket)
  975. {
  976. if (stopping(stream) || !stream->ff_data.video ||
  977. !stream->ff_data.video_ctx || !stream->ff_data.audio_infos)
  978. return;
  979. if (!stream->ff_data.audio_infos[encpacket->track_idx].stream)
  980. return;
  981. bool is_video = encpacket->type == OBS_ENCODER_VIDEO;
  982. AVStream *avstream =
  983. is_video ? stream->ff_data.video
  984. : stream->ff_data.audio_infos[encpacket->track_idx]
  985. .stream;
  986. AVPacket *packet = NULL;
  987. const AVRational codec_time_base =
  988. is_video ? stream->ff_data.video_ctx->time_base
  989. : stream->ff_data.audio_infos[encpacket->track_idx]
  990. .ctx->time_base;
  991. packet = av_packet_alloc();
  992. packet->data = av_memdup(encpacket->data, (int)encpacket->size);
  993. if (packet->data == NULL) {
  994. error("Couldn't allocate packet data");
  995. goto fail;
  996. }
  997. packet->size = (int)encpacket->size;
  998. packet->stream_index = avstream->id;
  999. packet->pts = rescale_ts2(avstream, codec_time_base, encpacket->pts);
  1000. packet->dts = rescale_ts2(avstream, codec_time_base, encpacket->dts);
  1001. if (encpacket->keyframe)
  1002. packet->flags = AV_PKT_FLAG_KEY;
  1003. pthread_mutex_lock(&stream->write_mutex);
  1004. da_push_back(stream->packets, &packet);
  1005. pthread_mutex_unlock(&stream->write_mutex);
  1006. os_sem_post(stream->write_sem);
  1007. return;
  1008. fail:
  1009. av_packet_free(&packet);
  1010. }
  1011. static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data)
  1012. {
  1013. AVDictionary *dict = NULL;
  1014. int ret;
  1015. /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */
  1016. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  1017. " ", 0))) {
  1018. ffmpeg_mpegts_log_error(
  1019. LOG_WARNING, data,
  1020. "Failed to parse muxer settings: %s, %s",
  1021. data->config.muxer_settings, av_err2str(ret));
  1022. av_dict_free(&dict);
  1023. return false;
  1024. }
  1025. if (av_dict_count(dict) > 0) {
  1026. struct dstr str = {0};
  1027. AVDictionaryEntry *entry = NULL;
  1028. while ((entry = av_dict_get(dict, "", entry,
  1029. AV_DICT_IGNORE_SUFFIX)))
  1030. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1031. info("Using muxer settings: %s", str.array);
  1032. dstr_free(&str);
  1033. }
  1034. /* Allocate the stream private data and write the stream header. */
  1035. ret = avformat_write_header(data->output, &dict);
  1036. if (ret < 0) {
  1037. ffmpeg_mpegts_log_error(
  1038. LOG_WARNING, data,
  1039. "Error setting stream header for '%s': %s",
  1040. data->config.url, av_err2str(ret));
  1041. return false;
  1042. }
  1043. /* Log invalid muxer settings. */
  1044. if (av_dict_count(dict) > 0) {
  1045. struct dstr str = {0};
  1046. AVDictionaryEntry *entry = NULL;
  1047. while ((entry = av_dict_get(dict, "", entry,
  1048. AV_DICT_IGNORE_SUFFIX)))
  1049. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1050. info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s",
  1051. str.array);
  1052. dstr_free(&str);
  1053. }
  1054. av_dict_free(&dict);
  1055. return true;
  1056. }
  1057. static void ffmpeg_mpegts_data(void *data, struct encoder_packet *packet)
  1058. {
  1059. struct ffmpeg_output *stream = data;
  1060. struct ffmpeg_data *ff_data = &stream->ff_data;
  1061. int code;
  1062. if (!stream->got_headers) {
  1063. if (get_extradata(stream)) {
  1064. stream->got_headers = true;
  1065. } else {
  1066. warn("Failed to retrieve headers");
  1067. code = OBS_OUTPUT_INVALID_STREAM;
  1068. goto fail;
  1069. }
  1070. if (!write_header(stream, ff_data)) {
  1071. error("Failed to write headers");
  1072. code = OBS_OUTPUT_INVALID_STREAM;
  1073. goto fail;
  1074. }
  1075. av_dump_format(ff_data->output, 0, NULL, 1);
  1076. ff_data->initialized = true;
  1077. }
  1078. if (!stream->active)
  1079. return;
  1080. /* encoder failure */
  1081. if (!packet) {
  1082. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  1083. ffmpeg_mpegts_deactivate(stream);
  1084. return;
  1085. }
  1086. if (stopping(stream)) {
  1087. if (packet->sys_dts_usec >= (int64_t)stream->stop_ts) {
  1088. ffmpeg_mpegts_deactivate(stream);
  1089. return;
  1090. }
  1091. }
  1092. mpegts_write_packet(stream, packet);
  1093. return;
  1094. fail:
  1095. obs_output_signal_stop(stream->output, code);
  1096. ffmpeg_mpegts_full_stop(stream);
  1097. }
  1098. static obs_properties_t *ffmpeg_mpegts_properties(void *unused)
  1099. {
  1100. UNUSED_PARAMETER(unused);
  1101. obs_properties_t *props = obs_properties_create();
  1102. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  1103. OBS_TEXT_DEFAULT);
  1104. return props;
  1105. }
  1106. struct obs_output_info ffmpeg_mpegts_muxer = {
  1107. .id = "ffmpeg_mpegts_muxer",
  1108. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  1109. OBS_OUTPUT_SERVICE,
  1110. #ifdef ENABLE_HEVC
  1111. .encoded_video_codecs = "h264;hevc;av1",
  1112. #else
  1113. .encoded_video_codecs = "h264;av1",
  1114. #endif
  1115. .encoded_audio_codecs = "aac",
  1116. .get_name = ffmpeg_mpegts_getname,
  1117. .create = ffmpeg_mpegts_create,
  1118. .destroy = ffmpeg_mpegts_destroy,
  1119. .start = ffmpeg_mpegts_start,
  1120. .stop = ffmpeg_mpegts_stop,
  1121. .encoded_packet = ffmpeg_mpegts_data,
  1122. .get_total_bytes = ffmpeg_mpegts_total_bytes,
  1123. .get_properties = ffmpeg_mpegts_properties,
  1124. };