ftl-stream.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /******************************************************************************
  2. Copyright (C) 2017 by Quinn Damerell <[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 <obs-avc.h>
  16. #include <util/platform.h>
  17. #include <util/circlebuf.h>
  18. #include <util/dstr.h>
  19. #include <util/threading.h>
  20. #include <inttypes.h>
  21. #include "ftl.h"
  22. #include "flv-mux.h"
  23. #include "net-if.h"
  24. #ifdef _WIN32
  25. #include <Iphlpapi.h>
  26. #else
  27. #include <sys/ioctl.h>
  28. #define INFINITE 0xFFFFFFFF
  29. #endif
  30. #define do_log(level, format, ...) \
  31. blog(level, "[ftl stream: '%s'] " format, \
  32. obs_output_get_name(stream->output), ##__VA_ARGS__)
  33. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  34. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  35. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  36. #define OPT_DROP_THRESHOLD "drop_threshold_ms"
  37. #define OPT_MAX_SHUTDOWN_TIME_SEC "max_shutdown_time_sec"
  38. #define OPT_BIND_IP "bind_ip"
  39. #define FTL_URL_PROTOCOL "ftl://"
  40. typedef struct _nalu_t {
  41. int len;
  42. int dts_usec;
  43. int send_marker_bit;
  44. uint8_t *data;
  45. } nalu_t;
  46. typedef struct _frame_of_nalus_t {
  47. nalu_t nalus[100];
  48. int total;
  49. int complete_frame;
  50. } frame_of_nalus_t;
  51. struct ftl_stream {
  52. obs_output_t *output;
  53. pthread_mutex_t packets_mutex;
  54. struct circlebuf packets;
  55. bool sent_headers;
  56. int64_t frames_sent;
  57. volatile bool connecting;
  58. pthread_t connect_thread;
  59. pthread_t status_thread;
  60. volatile bool active;
  61. volatile bool disconnected;
  62. volatile bool encode_error;
  63. pthread_t send_thread;
  64. int max_shutdown_time_sec;
  65. os_sem_t *send_sem;
  66. os_event_t *stop_event;
  67. uint64_t stop_ts;
  68. uint64_t shutdown_timeout_ts;
  69. struct dstr path;
  70. uint32_t channel_id;
  71. struct dstr username, password;
  72. struct dstr encoder_name;
  73. struct dstr bind_ip;
  74. /* frame drop variables */
  75. int64_t drop_threshold_usec;
  76. int64_t pframe_drop_threshold_usec;
  77. int min_priority;
  78. float congestion;
  79. int64_t last_dts_usec;
  80. uint64_t total_bytes_sent;
  81. uint64_t dropped_frames;
  82. uint64_t last_nack_count;
  83. ftl_handle_t ftl_handle;
  84. ftl_ingest_params_t params;
  85. int peak_kbps;
  86. uint32_t scale_width, scale_height, width, height;
  87. frame_of_nalus_t coded_pic_buffer;
  88. };
  89. static void log_libftl_messages(ftl_log_severity_t log_level,
  90. const char *message);
  91. static int init_connect(struct ftl_stream *stream);
  92. static void *connect_thread(void *data);
  93. static void *status_thread(void *data);
  94. static int _ftl_error_to_obs_error(int status);
  95. static const char *ftl_stream_getname(void *unused)
  96. {
  97. UNUSED_PARAMETER(unused);
  98. return obs_module_text("FTLStream");
  99. }
  100. static void log_ftl(int level, const char *format, va_list args)
  101. {
  102. blogva(LOG_INFO, format, args);
  103. UNUSED_PARAMETER(level);
  104. }
  105. static inline size_t num_buffered_packets(struct ftl_stream *stream);
  106. static inline void free_packets(struct ftl_stream *stream)
  107. {
  108. size_t num_packets;
  109. pthread_mutex_lock(&stream->packets_mutex);
  110. num_packets = num_buffered_packets(stream);
  111. if (num_packets)
  112. info("Freeing %d remaining packets", (int)num_packets);
  113. while (stream->packets.size) {
  114. struct encoder_packet packet;
  115. circlebuf_pop_front(&stream->packets, &packet, sizeof(packet));
  116. obs_encoder_packet_release(&packet);
  117. }
  118. pthread_mutex_unlock(&stream->packets_mutex);
  119. }
  120. static inline bool stopping(struct ftl_stream *stream)
  121. {
  122. return os_event_try(stream->stop_event) != EAGAIN;
  123. }
  124. static inline bool connecting(struct ftl_stream *stream)
  125. {
  126. return os_atomic_load_bool(&stream->connecting);
  127. }
  128. static inline bool active(struct ftl_stream *stream)
  129. {
  130. return os_atomic_load_bool(&stream->active);
  131. }
  132. static inline bool disconnected(struct ftl_stream *stream)
  133. {
  134. return os_atomic_load_bool(&stream->disconnected);
  135. }
  136. static void ftl_stream_destroy(void *data)
  137. {
  138. struct ftl_stream *stream = data;
  139. ftl_status_t status_code;
  140. info("ftl_stream_destroy");
  141. if (stopping(stream) && !connecting(stream)) {
  142. pthread_join(stream->send_thread, NULL);
  143. } else if (connecting(stream) || active(stream)) {
  144. if (stream->connecting) {
  145. info("wait for connect_thread to terminate");
  146. pthread_join(stream->status_thread, NULL);
  147. pthread_join(stream->connect_thread, NULL);
  148. info("wait for connect_thread to terminate: done");
  149. }
  150. stream->stop_ts = 0;
  151. os_event_signal(stream->stop_event);
  152. if (active(stream)) {
  153. os_sem_post(stream->send_sem);
  154. obs_output_end_data_capture(stream->output);
  155. pthread_join(stream->send_thread, NULL);
  156. }
  157. }
  158. info("ingest destroy");
  159. status_code = ftl_ingest_destroy(&stream->ftl_handle);
  160. if (status_code != FTL_SUCCESS) {
  161. info("Failed to destroy from ingest %d", status_code);
  162. }
  163. if (stream) {
  164. free_packets(stream);
  165. dstr_free(&stream->path);
  166. dstr_free(&stream->username);
  167. dstr_free(&stream->password);
  168. dstr_free(&stream->encoder_name);
  169. dstr_free(&stream->bind_ip);
  170. os_event_destroy(stream->stop_event);
  171. os_sem_destroy(stream->send_sem);
  172. pthread_mutex_destroy(&stream->packets_mutex);
  173. circlebuf_free(&stream->packets);
  174. bfree(stream);
  175. }
  176. }
  177. static void *ftl_stream_create(obs_data_t *settings, obs_output_t *output)
  178. {
  179. struct ftl_stream *stream = bzalloc(sizeof(struct ftl_stream));
  180. info("ftl_stream_create");
  181. stream->output = output;
  182. pthread_mutex_init_value(&stream->packets_mutex);
  183. stream->peak_kbps = -1;
  184. ftl_init();
  185. if (pthread_mutex_init(&stream->packets_mutex, NULL) != 0) {
  186. goto fail;
  187. }
  188. if (os_event_init(&stream->stop_event, OS_EVENT_TYPE_MANUAL) != 0) {
  189. goto fail;
  190. }
  191. stream->coded_pic_buffer.total = 0;
  192. stream->coded_pic_buffer.complete_frame = 0;
  193. UNUSED_PARAMETER(settings);
  194. return stream;
  195. fail:
  196. return NULL;
  197. }
  198. static void ftl_stream_stop(void *data, uint64_t ts)
  199. {
  200. struct ftl_stream *stream = data;
  201. info("ftl_stream_stop");
  202. if (stopping(stream) && ts != 0) {
  203. return;
  204. }
  205. if (connecting(stream)) {
  206. pthread_join(stream->status_thread, NULL);
  207. pthread_join(stream->connect_thread, NULL);
  208. }
  209. stream->stop_ts = ts / 1000ULL;
  210. if (ts) {
  211. stream->shutdown_timeout_ts =
  212. ts +
  213. (uint64_t)stream->max_shutdown_time_sec * 1000000000ULL;
  214. }
  215. if (active(stream)) {
  216. os_event_signal(stream->stop_event);
  217. if (stream->stop_ts == 0)
  218. os_sem_post(stream->send_sem);
  219. } else {
  220. obs_output_signal_stop(stream->output, OBS_OUTPUT_SUCCESS);
  221. }
  222. }
  223. static inline bool get_next_packet(struct ftl_stream *stream,
  224. struct encoder_packet *packet)
  225. {
  226. bool new_packet = false;
  227. pthread_mutex_lock(&stream->packets_mutex);
  228. if (stream->packets.size) {
  229. circlebuf_pop_front(&stream->packets, packet,
  230. sizeof(struct encoder_packet));
  231. new_packet = true;
  232. }
  233. pthread_mutex_unlock(&stream->packets_mutex);
  234. return new_packet;
  235. }
  236. static int avc_get_video_frame(struct ftl_stream *stream,
  237. struct encoder_packet *packet, bool is_header)
  238. {
  239. int consumed = 0;
  240. int len = (int)packet->size;
  241. nalu_t *nalu;
  242. unsigned char *video_stream = packet->data;
  243. while ((size_t)consumed < packet->size) {
  244. size_t total_max = sizeof(stream->coded_pic_buffer.nalus) /
  245. sizeof(stream->coded_pic_buffer.nalus[0]);
  246. if ((size_t)stream->coded_pic_buffer.total >= total_max) {
  247. warn("ERROR: cannot continue, nalu buffers are full");
  248. return -1;
  249. }
  250. nalu = &stream->coded_pic_buffer
  251. .nalus[stream->coded_pic_buffer.total];
  252. if (is_header) {
  253. if (consumed == 0) {
  254. //first 6 bytes are some obs header with part
  255. //of the sps
  256. video_stream += 6;
  257. consumed += 6;
  258. } else {
  259. //another spacer byte of 0x1
  260. video_stream += 1;
  261. consumed += 1;
  262. }
  263. len = video_stream[0] << 8 | video_stream[1];
  264. video_stream += 2;
  265. consumed += 2;
  266. } else {
  267. len = video_stream[0] << 24 | video_stream[1] << 16 |
  268. video_stream[2] << 8 | video_stream[3];
  269. if ((size_t)len > (packet->size - (size_t)consumed)) {
  270. warn("ERROR: got len of %d but packet only "
  271. "has %d left",
  272. len, (int)(packet->size - consumed));
  273. }
  274. consumed += 4;
  275. video_stream += 4;
  276. }
  277. consumed += len;
  278. uint8_t nalu_type = video_stream[0] & 0x1F;
  279. uint8_t nri = (video_stream[0] >> 5) & 0x3;
  280. if ((nalu_type != 12 && nalu_type != 6 && nalu_type != 9) ||
  281. nri) {
  282. nalu->data = video_stream;
  283. nalu->len = len;
  284. nalu->send_marker_bit = 0;
  285. stream->coded_pic_buffer.total++;
  286. }
  287. video_stream += len;
  288. }
  289. if (!is_header) {
  290. size_t idx = stream->coded_pic_buffer.total - 1;
  291. stream->coded_pic_buffer.nalus[idx].send_marker_bit = 1;
  292. }
  293. return 0;
  294. }
  295. static int send_packet(struct ftl_stream *stream, struct encoder_packet *packet,
  296. bool is_header)
  297. {
  298. int bytes_sent = 0;
  299. int ret = 0;
  300. if (packet->type == OBS_ENCODER_VIDEO) {
  301. stream->coded_pic_buffer.total = 0;
  302. avc_get_video_frame(stream, packet, is_header);
  303. int i;
  304. for (i = 0; i < stream->coded_pic_buffer.total; i++) {
  305. nalu_t *nalu = &stream->coded_pic_buffer.nalus[i];
  306. bytes_sent += ftl_ingest_send_media_dts(
  307. &stream->ftl_handle, FTL_VIDEO_DATA,
  308. packet->dts_usec, nalu->data, nalu->len,
  309. nalu->send_marker_bit);
  310. if (nalu->send_marker_bit) {
  311. stream->frames_sent++;
  312. }
  313. }
  314. } else if (packet->type == OBS_ENCODER_AUDIO) {
  315. bytes_sent += ftl_ingest_send_media_dts(
  316. &stream->ftl_handle, FTL_AUDIO_DATA, packet->dts_usec,
  317. packet->data, (int)packet->size, 0);
  318. } else {
  319. warn("Got packet type %d", packet->type);
  320. }
  321. if (is_header) {
  322. bfree(packet->data);
  323. } else {
  324. obs_encoder_packet_release(packet);
  325. }
  326. stream->total_bytes_sent += bytes_sent;
  327. return ret;
  328. }
  329. static void set_peak_bitrate(struct ftl_stream *stream)
  330. {
  331. int speedtest_kbps = 15000;
  332. int speedtest_duration = 1000;
  333. speed_test_t results;
  334. ftl_status_t status_code;
  335. status_code = ftl_ingest_speed_test_ex(&stream->ftl_handle,
  336. speedtest_kbps,
  337. speedtest_duration, &results);
  338. float percent_lost = 0;
  339. if (status_code == FTL_SUCCESS) {
  340. percent_lost = (float)results.lost_pkts * 100.f /
  341. (float)results.pkts_sent;
  342. } else {
  343. warn("Speed test failed with: %s",
  344. ftl_status_code_to_string(status_code));
  345. }
  346. // Get what the user set the encoding bitrate to.
  347. obs_encoder_t *video_encoder =
  348. obs_output_get_video_encoder(stream->output);
  349. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  350. int user_desired_bitrate =
  351. (int)obs_data_get_int(video_settings, "bitrate");
  352. obs_data_release(video_settings);
  353. // Report the results.
  354. info("Speed test completed: User desired bitrate %d, Peak kbps %d, "
  355. "initial rtt %d, "
  356. "final rtt %d, %3.2f lost packets",
  357. user_desired_bitrate, results.peak_kbps, results.starting_rtt,
  358. results.ending_rtt, percent_lost);
  359. // We still want to set the peak to about 1.2x what the target bitrate is,
  360. // even if the speed test reported it should be lower. If we don't, FTL
  361. // will queue data on the client and start adding latency. If the internet
  362. // connection really can't handle the bitrate the user will see either lost frame
  363. // and recovered frame counts go up, which is reflect in the dropped_frames count.
  364. stream->peak_kbps = stream->params.peak_kbps =
  365. user_desired_bitrate * 12 / 10;
  366. ftl_ingest_update_params(&stream->ftl_handle, &stream->params);
  367. }
  368. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec);
  369. static inline bool can_shutdown_stream(struct ftl_stream *stream,
  370. struct encoder_packet *packet)
  371. {
  372. uint64_t cur_time = os_gettime_ns();
  373. bool timeout = cur_time >= stream->shutdown_timeout_ts;
  374. if (timeout)
  375. info("Stream shutdown timeout reached (%d second(s))",
  376. stream->max_shutdown_time_sec);
  377. return timeout || packet->sys_dts_usec >= (int64_t)stream->stop_ts;
  378. }
  379. static void *send_thread(void *data)
  380. {
  381. struct ftl_stream *stream = data;
  382. ftl_status_t status_code;
  383. os_set_thread_name("ftl-stream: send_thread");
  384. while (os_sem_wait(stream->send_sem) == 0) {
  385. struct encoder_packet packet;
  386. if (stopping(stream) && stream->stop_ts == 0) {
  387. break;
  388. }
  389. if (!get_next_packet(stream, &packet))
  390. continue;
  391. if (stopping(stream)) {
  392. if (can_shutdown_stream(stream, &packet)) {
  393. obs_encoder_packet_release(&packet);
  394. break;
  395. }
  396. }
  397. /* sends sps/pps on every key frame as this is typically
  398. * required for webrtc */
  399. if (packet.keyframe) {
  400. if (!send_headers(stream, packet.dts_usec)) {
  401. os_atomic_set_bool(&stream->disconnected, true);
  402. break;
  403. }
  404. }
  405. if (send_packet(stream, &packet, false) < 0) {
  406. os_atomic_set_bool(&stream->disconnected, true);
  407. break;
  408. }
  409. }
  410. bool encode_error = os_atomic_load_bool(&stream->encode_error);
  411. if (disconnected(stream)) {
  412. info("Disconnected from %s", stream->path.array);
  413. } else if (encode_error) {
  414. info("Encoder error, disconnecting");
  415. } else {
  416. info("User stopped the stream");
  417. }
  418. if (!stopping(stream)) {
  419. pthread_detach(stream->send_thread);
  420. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  421. } else if (encode_error) {
  422. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  423. } else {
  424. obs_output_end_data_capture(stream->output);
  425. }
  426. info("ingest disconnect");
  427. status_code = ftl_ingest_disconnect(&stream->ftl_handle);
  428. if (status_code != FTL_SUCCESS) {
  429. printf("Failed to disconnect from ingest %d", status_code);
  430. }
  431. free_packets(stream);
  432. os_event_reset(stream->stop_event);
  433. os_atomic_set_bool(&stream->active, false);
  434. stream->sent_headers = false;
  435. return NULL;
  436. }
  437. static bool send_video_header(struct ftl_stream *stream, int64_t dts_usec)
  438. {
  439. obs_output_t *context = stream->output;
  440. obs_encoder_t *vencoder = obs_output_get_video_encoder(context);
  441. uint8_t *header;
  442. size_t size;
  443. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  444. .timebase_den = 1,
  445. .keyframe = true,
  446. .dts_usec = dts_usec};
  447. if (!obs_encoder_get_extra_data(vencoder, &header, &size))
  448. return false;
  449. packet.size = obs_parse_avc_header(&packet.data, header, size);
  450. return send_packet(stream, &packet, true) >= 0;
  451. }
  452. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec)
  453. {
  454. stream->sent_headers = true;
  455. if (!send_video_header(stream, dts_usec))
  456. return false;
  457. return true;
  458. }
  459. static inline bool reset_semaphore(struct ftl_stream *stream)
  460. {
  461. os_sem_destroy(stream->send_sem);
  462. return os_sem_init(&stream->send_sem, 0) == 0;
  463. }
  464. #ifdef _WIN32
  465. #define socklen_t int
  466. #endif
  467. static int init_send(struct ftl_stream *stream)
  468. {
  469. int ret;
  470. reset_semaphore(stream);
  471. ret = pthread_create(&stream->send_thread, NULL, send_thread, stream);
  472. if (ret != 0) {
  473. warn("Failed to create send thread");
  474. return OBS_OUTPUT_ERROR;
  475. }
  476. os_atomic_set_bool(&stream->active, true);
  477. obs_output_begin_data_capture2(stream->output);
  478. return OBS_OUTPUT_SUCCESS;
  479. }
  480. static int try_connect(struct ftl_stream *stream)
  481. {
  482. ftl_status_t status_code;
  483. if (dstr_is_empty(&stream->path)) {
  484. warn("URL is empty");
  485. return OBS_OUTPUT_BAD_PATH;
  486. }
  487. info("Connecting to FTL Ingest URL %s...", stream->path.array);
  488. stream->width = (int)obs_output_get_width(stream->output);
  489. stream->height = (int)obs_output_get_height(stream->output);
  490. status_code = ftl_ingest_connect(&stream->ftl_handle);
  491. if (status_code != FTL_SUCCESS) {
  492. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  493. blog(LOG_ERROR, "Invalid Key (%s)",
  494. ftl_status_code_to_string(status_code));
  495. return OBS_OUTPUT_INVALID_STREAM;
  496. } else {
  497. warn("Ingest connect failed with: %s (%d)",
  498. ftl_status_code_to_string(status_code),
  499. status_code);
  500. return _ftl_error_to_obs_error(status_code);
  501. }
  502. }
  503. info("Connection to %s successful", stream->path.array);
  504. // Always get the peak bitrate when we are starting.
  505. set_peak_bitrate(stream);
  506. pthread_create(&stream->status_thread, NULL, status_thread, stream);
  507. return init_send(stream);
  508. }
  509. static bool ftl_stream_start(void *data)
  510. {
  511. struct ftl_stream *stream = data;
  512. info("ftl_stream_start");
  513. // Mixer doesn't support bframes. So force them off.
  514. obs_encoder_t *video_encoder =
  515. obs_output_get_video_encoder(stream->output);
  516. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  517. obs_data_set_int(video_settings, "bf", 0);
  518. obs_data_release(video_settings);
  519. if (!obs_output_can_begin_data_capture2(stream->output)) {
  520. return false;
  521. }
  522. if (!obs_output_initialize_encoders2(stream->output)) {
  523. return false;
  524. }
  525. stream->frames_sent = 0;
  526. os_atomic_set_bool(&stream->connecting, true);
  527. return pthread_create(&stream->connect_thread, NULL, connect_thread,
  528. stream) == 0;
  529. }
  530. static inline bool add_packet(struct ftl_stream *stream,
  531. struct encoder_packet *packet)
  532. {
  533. circlebuf_push_back(&stream->packets, packet,
  534. sizeof(struct encoder_packet));
  535. return true;
  536. }
  537. static inline size_t num_buffered_packets(struct ftl_stream *stream)
  538. {
  539. return stream->packets.size / sizeof(struct encoder_packet);
  540. }
  541. static void drop_frames(struct ftl_stream *stream, const char *name,
  542. int highest_priority, bool pframes)
  543. {
  544. UNUSED_PARAMETER(pframes);
  545. struct circlebuf new_buf = {0};
  546. int num_frames_dropped = 0;
  547. #ifdef _DEBUG
  548. int start_packets = (int)num_buffered_packets(stream);
  549. #else
  550. UNUSED_PARAMETER(name);
  551. #endif
  552. circlebuf_reserve(&new_buf, sizeof(struct encoder_packet) * 8);
  553. while (stream->packets.size) {
  554. struct encoder_packet packet;
  555. circlebuf_pop_front(&stream->packets, &packet, sizeof(packet));
  556. /* do not drop audio data or video keyframes */
  557. if (packet.type == OBS_ENCODER_AUDIO ||
  558. packet.drop_priority >= highest_priority) {
  559. circlebuf_push_back(&new_buf, &packet, sizeof(packet));
  560. } else {
  561. num_frames_dropped++;
  562. obs_encoder_packet_release(&packet);
  563. }
  564. }
  565. circlebuf_free(&stream->packets);
  566. stream->packets = new_buf;
  567. if (stream->min_priority < highest_priority)
  568. stream->min_priority = highest_priority;
  569. if (!num_frames_dropped)
  570. return;
  571. stream->dropped_frames += num_frames_dropped;
  572. #ifdef _DEBUG
  573. debug("Dropped %s, prev packet count: %d, new packet count: %d", name,
  574. start_packets, (int)num_buffered_packets(stream));
  575. #endif
  576. }
  577. static bool find_first_video_packet(struct ftl_stream *stream,
  578. struct encoder_packet *first)
  579. {
  580. size_t count = stream->packets.size / sizeof(*first);
  581. for (size_t i = 0; i < count; i++) {
  582. struct encoder_packet *cur =
  583. circlebuf_data(&stream->packets, i * sizeof(*first));
  584. if (cur->type == OBS_ENCODER_VIDEO && !cur->keyframe) {
  585. *first = *cur;
  586. return true;
  587. }
  588. }
  589. return false;
  590. }
  591. static void check_to_drop_frames(struct ftl_stream *stream, bool pframes)
  592. {
  593. struct encoder_packet first;
  594. int64_t buffer_duration_usec;
  595. size_t num_packets = num_buffered_packets(stream);
  596. const char *name = pframes ? "p-frames" : "b-frames";
  597. int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST
  598. : OBS_NAL_PRIORITY_HIGH;
  599. int64_t drop_threshold = pframes ? stream->pframe_drop_threshold_usec
  600. : stream->drop_threshold_usec;
  601. if (num_packets < 5) {
  602. if (!pframes)
  603. stream->congestion = 0.0f;
  604. return;
  605. }
  606. if (!find_first_video_packet(stream, &first))
  607. return;
  608. /* if the amount of time stored in the buffered packets waiting to be
  609. * sent is higher than threshold, drop frames */
  610. buffer_duration_usec = stream->last_dts_usec - first.dts_usec;
  611. if (!pframes) {
  612. stream->congestion =
  613. (float)buffer_duration_usec / (float)drop_threshold;
  614. }
  615. if (buffer_duration_usec > drop_threshold) {
  616. debug("buffer_duration_usec: %" PRId64, buffer_duration_usec);
  617. drop_frames(stream, name, priority, pframes);
  618. }
  619. }
  620. static bool add_video_packet(struct ftl_stream *stream,
  621. struct encoder_packet *packet)
  622. {
  623. check_to_drop_frames(stream, false);
  624. check_to_drop_frames(stream, true);
  625. /* if currently dropping frames, drop packets until it reaches the
  626. * desired priority */
  627. if (packet->priority < stream->min_priority) {
  628. stream->dropped_frames++;
  629. return false;
  630. } else {
  631. stream->min_priority = 0;
  632. }
  633. stream->last_dts_usec = packet->dts_usec;
  634. return add_packet(stream, packet);
  635. }
  636. static void ftl_stream_data(void *data, struct encoder_packet *packet)
  637. {
  638. struct ftl_stream *stream = data;
  639. struct encoder_packet new_packet;
  640. bool added_packet = false;
  641. if (disconnected(stream) || !active(stream))
  642. return;
  643. /* encoder failure */
  644. if (!packet) {
  645. os_atomic_set_bool(&stream->encode_error, true);
  646. os_sem_post(stream->send_sem);
  647. return;
  648. }
  649. if (packet->type == OBS_ENCODER_VIDEO)
  650. obs_parse_avc_packet(&new_packet, packet);
  651. else
  652. obs_encoder_packet_ref(&new_packet, packet);
  653. pthread_mutex_lock(&stream->packets_mutex);
  654. if (!disconnected(stream)) {
  655. added_packet = (packet->type == OBS_ENCODER_VIDEO)
  656. ? add_video_packet(stream, &new_packet)
  657. : add_packet(stream, &new_packet);
  658. }
  659. pthread_mutex_unlock(&stream->packets_mutex);
  660. if (added_packet)
  661. os_sem_post(stream->send_sem);
  662. else
  663. obs_encoder_packet_release(&new_packet);
  664. }
  665. static void ftl_stream_defaults(obs_data_t *defaults)
  666. {
  667. UNUSED_PARAMETER(defaults);
  668. }
  669. static obs_properties_t *ftl_stream_properties(void *unused)
  670. {
  671. UNUSED_PARAMETER(unused);
  672. obs_properties_t *props = obs_properties_create();
  673. obs_properties_add_int(props, "peak_bitrate_kbps",
  674. obs_module_text("FTLStream.PeakBitrate"), 1000,
  675. 10000, 500);
  676. return props;
  677. }
  678. static uint64_t ftl_stream_total_bytes_sent(void *data)
  679. {
  680. struct ftl_stream *stream = data;
  681. return stream->total_bytes_sent;
  682. }
  683. static int ftl_stream_dropped_frames(void *data)
  684. {
  685. struct ftl_stream *stream = data;
  686. return (int)stream->dropped_frames;
  687. }
  688. static float ftl_stream_congestion(void *data)
  689. {
  690. struct ftl_stream *stream = data;
  691. return stream->min_priority > 0 ? 1.0f : stream->congestion;
  692. }
  693. enum ret_type {
  694. RET_CONTINUE,
  695. RET_BREAK,
  696. RET_EXIT,
  697. };
  698. static enum ret_type ftl_event(struct ftl_stream *stream,
  699. ftl_status_msg_t status)
  700. {
  701. if (status.msg.event.type != FTL_STATUS_EVENT_TYPE_DISCONNECTED)
  702. return RET_CONTINUE;
  703. info("Disconnected from ingest with reason: %s",
  704. ftl_status_code_to_string(status.msg.event.error_code));
  705. if (status.msg.event.reason == FTL_STATUS_EVENT_REASON_API_REQUEST) {
  706. return RET_BREAK;
  707. }
  708. //tell OBS and it will trigger a reconnection
  709. blog(LOG_WARNING, "Reconnecting to Ingest");
  710. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  711. reset_semaphore(stream);
  712. return RET_EXIT;
  713. }
  714. static void *status_thread(void *data)
  715. {
  716. struct ftl_stream *stream = data;
  717. ftl_status_msg_t status;
  718. ftl_status_t status_code;
  719. while (!disconnected(stream)) {
  720. status_code = ftl_ingest_get_status(&stream->ftl_handle,
  721. &status, 1000);
  722. if (status_code == FTL_STATUS_TIMEOUT ||
  723. status_code == FTL_QUEUE_EMPTY) {
  724. continue;
  725. } else if (status_code == FTL_NOT_INITIALIZED) {
  726. break;
  727. }
  728. if (status.type == FTL_STATUS_EVENT) {
  729. enum ret_type ret_type = ftl_event(stream, status);
  730. if (ret_type == RET_EXIT)
  731. return NULL;
  732. else if (ret_type == RET_BREAK)
  733. break;
  734. } else if (status.type == FTL_STATUS_LOG) {
  735. blog(LOG_INFO, "[%d] %s", status.msg.log.log_level,
  736. status.msg.log.string);
  737. } else if (status.type == FTL_STATUS_VIDEO_PACKETS) {
  738. ftl_packet_stats_msg_t *p = &status.msg.pkt_stats;
  739. // Report nack requests as dropped frames
  740. stream->dropped_frames +=
  741. p->nack_reqs - stream->last_nack_count;
  742. stream->last_nack_count = p->nack_reqs;
  743. int log_level = p->nack_reqs > 0 ? LOG_INFO : LOG_DEBUG;
  744. blog(log_level,
  745. "Avg packet send per second %3.1f, "
  746. "total nack requests %d",
  747. (float)p->sent * 1000.f / p->period,
  748. (int)p->nack_reqs);
  749. } else if (status.type == FTL_STATUS_VIDEO_PACKETS_INSTANT) {
  750. ftl_packet_stats_instant_msg_t *p =
  751. &status.msg.ipkt_stats;
  752. int log_level = p->avg_rtt > 20 ? LOG_INFO : LOG_DEBUG;
  753. blog(log_level,
  754. "avg transmit delay %dms "
  755. "(min: %d, max: %d), "
  756. "avg rtt %dms (min: %d, max: %d)",
  757. p->avg_xmit_delay, p->min_xmit_delay,
  758. p->max_xmit_delay, p->avg_rtt, p->min_rtt,
  759. p->max_rtt);
  760. } else if (status.type == FTL_STATUS_VIDEO) {
  761. ftl_video_frame_stats_msg_t *v =
  762. &status.msg.video_stats;
  763. int log_level = v->queue_fullness > 0 ? LOG_INFO
  764. : LOG_DEBUG;
  765. blog(log_level,
  766. "Queue an average of %3.2f fps "
  767. "(%3.1f kbps), "
  768. "sent an average of %3.2f fps "
  769. "(%3.1f kbps), "
  770. "queue fullness %d, "
  771. "max frame size %d",
  772. (float)v->frames_queued * 1000.f / v->period,
  773. (float)v->bytes_queued / v->period * 8,
  774. (float)v->frames_sent * 1000.f / v->period,
  775. (float)v->bytes_sent / v->period * 8,
  776. v->queue_fullness, v->max_frame_size);
  777. } else {
  778. blog(LOG_DEBUG,
  779. "Status: Got Status message of type "
  780. "%d",
  781. status.type);
  782. }
  783. }
  784. blog(LOG_DEBUG, "status_thread: Exited");
  785. pthread_detach(stream->status_thread);
  786. return NULL;
  787. }
  788. static void *connect_thread(void *data)
  789. {
  790. struct ftl_stream *stream = data;
  791. int ret;
  792. os_set_thread_name("ftl-stream: connect_thread");
  793. blog(LOG_WARNING, "ftl-stream: connect thread");
  794. ret = init_connect(stream);
  795. if (ret != OBS_OUTPUT_SUCCESS) {
  796. obs_output_signal_stop(stream->output, ret);
  797. return NULL;
  798. }
  799. ret = try_connect(stream);
  800. if (ret != OBS_OUTPUT_SUCCESS) {
  801. obs_output_signal_stop(stream->output, ret);
  802. info("Connection to %s failed: %d", stream->path.array, ret);
  803. }
  804. if (!stopping(stream))
  805. pthread_detach(stream->connect_thread);
  806. os_atomic_set_bool(&stream->connecting, false);
  807. return NULL;
  808. }
  809. static void log_libftl_messages(ftl_log_severity_t log_level,
  810. const char *message)
  811. {
  812. UNUSED_PARAMETER(log_level);
  813. blog(LOG_WARNING, "[libftl] %s", message);
  814. }
  815. static int init_connect(struct ftl_stream *stream)
  816. {
  817. obs_service_t *service;
  818. obs_data_t *settings;
  819. const char *bind_ip, *key, *ingest_url;
  820. ftl_status_t status_code;
  821. info("init_connect");
  822. if (stopping(stream))
  823. pthread_join(stream->send_thread, NULL);
  824. free_packets(stream);
  825. service = obs_output_get_service(stream->output);
  826. if (!service) {
  827. return OBS_OUTPUT_ERROR;
  828. }
  829. os_atomic_set_bool(&stream->disconnected, false);
  830. os_atomic_set_bool(&stream->encode_error, false);
  831. stream->total_bytes_sent = 0;
  832. stream->dropped_frames = 0;
  833. stream->min_priority = 0;
  834. settings = obs_output_get_settings(stream->output);
  835. obs_encoder_t *video_encoder =
  836. obs_output_get_video_encoder(stream->output);
  837. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  838. ingest_url = obs_service_get_connect_info(
  839. service, OBS_SERVICE_CONNECT_INFO_SERVER_URL);
  840. if (strncmp(ingest_url, FTL_URL_PROTOCOL, strlen(FTL_URL_PROTOCOL)) ==
  841. 0) {
  842. dstr_copy(&stream->path, ingest_url + strlen(FTL_URL_PROTOCOL));
  843. } else {
  844. dstr_copy(&stream->path, ingest_url);
  845. }
  846. key = obs_service_get_connect_info(service,
  847. OBS_SERVICE_CONNECT_INFO_STREAM_KEY);
  848. int target_bitrate = (int)obs_data_get_int(video_settings, "bitrate");
  849. int peak_bitrate = (int)((float)target_bitrate * 1.1f);
  850. //minimum overshoot tolerance of 10%
  851. if (peak_bitrate < target_bitrate) {
  852. peak_bitrate = target_bitrate;
  853. }
  854. stream->params.stream_key = (char *)key;
  855. stream->params.video_codec = FTL_VIDEO_H264;
  856. stream->params.audio_codec = FTL_AUDIO_OPUS;
  857. stream->params.ingest_hostname = stream->path.array;
  858. stream->params.vendor_name = "OBS Studio";
  859. stream->params.vendor_version = OBS_VERSION;
  860. stream->params.peak_kbps = stream->peak_kbps < 0 ? 0
  861. : stream->peak_kbps;
  862. //not required when using ftl_ingest_send_media_dts
  863. stream->params.fps_num = 0;
  864. stream->params.fps_den = 0;
  865. status_code = ftl_ingest_create(&stream->ftl_handle, &stream->params);
  866. if (status_code != FTL_SUCCESS) {
  867. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  868. blog(LOG_ERROR, "Invalid Key (%s)",
  869. ftl_status_code_to_string(status_code));
  870. return OBS_OUTPUT_INVALID_STREAM;
  871. } else {
  872. blog(LOG_ERROR, "Failed to create ingest handle (%s)",
  873. ftl_status_code_to_string(status_code));
  874. return OBS_OUTPUT_ERROR;
  875. }
  876. }
  877. dstr_copy(&stream->username,
  878. obs_service_get_connect_info(
  879. service, OBS_SERVICE_CONNECT_INFO_USERNAME));
  880. dstr_copy(&stream->password,
  881. obs_service_get_connect_info(
  882. service, OBS_SERVICE_CONNECT_INFO_PASSWORD));
  883. dstr_depad(&stream->path);
  884. stream->drop_threshold_usec =
  885. (int64_t)obs_data_get_int(settings, OPT_DROP_THRESHOLD) * 1000;
  886. stream->max_shutdown_time_sec =
  887. (int)obs_data_get_int(settings, OPT_MAX_SHUTDOWN_TIME_SEC);
  888. bind_ip = obs_data_get_string(settings, OPT_BIND_IP);
  889. dstr_copy(&stream->bind_ip, bind_ip);
  890. obs_data_release(settings);
  891. obs_data_release(video_settings);
  892. return OBS_OUTPUT_SUCCESS;
  893. }
  894. // Returns 0 on success
  895. static int _ftl_error_to_obs_error(int status)
  896. {
  897. /* Map FTL errors to OBS errors */
  898. switch (status) {
  899. case FTL_SUCCESS:
  900. return OBS_OUTPUT_SUCCESS;
  901. case FTL_SOCKET_NOT_CONNECTED:
  902. case FTL_MALLOC_FAILURE:
  903. case FTL_INTERNAL_ERROR:
  904. case FTL_CONFIG_ERROR:
  905. case FTL_NOT_ACTIVE_STREAM:
  906. case FTL_NOT_CONNECTED:
  907. case FTL_ALREADY_CONNECTED:
  908. case FTL_STATUS_TIMEOUT:
  909. case FTL_QUEUE_FULL:
  910. case FTL_STATUS_WAITING_FOR_KEY_FRAME:
  911. case FTL_QUEUE_EMPTY:
  912. case FTL_NOT_INITIALIZED:
  913. return OBS_OUTPUT_ERROR;
  914. case FTL_BAD_REQUEST:
  915. case FTL_DNS_FAILURE:
  916. case FTL_CONNECT_ERROR:
  917. case FTL_UNSUPPORTED_MEDIA_TYPE:
  918. case FTL_OLD_VERSION:
  919. case FTL_UNAUTHORIZED:
  920. case FTL_AUDIO_SSRC_COLLISION:
  921. case FTL_VIDEO_SSRC_COLLISION:
  922. case FTL_STREAM_REJECTED:
  923. case FTL_BAD_OR_INVALID_STREAM_KEY:
  924. case FTL_CHANNEL_IN_USE:
  925. case FTL_REGION_UNSUPPORTED:
  926. case FTL_GAME_BLOCKED:
  927. return OBS_OUTPUT_CONNECT_FAILED;
  928. case FTL_NO_MEDIA_TIMEOUT:
  929. return OBS_OUTPUT_DISCONNECTED;
  930. case FTL_USER_DISCONNECT:
  931. return OBS_OUTPUT_SUCCESS;
  932. case FTL_UNKNOWN_ERROR_CODE:
  933. default:
  934. /* Unknown FTL error */
  935. return OBS_OUTPUT_ERROR;
  936. }
  937. }
  938. struct obs_output_info ftl_output_info = {
  939. .id = "ftl_output",
  940. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_SERVICE,
  941. .protocols = "FTL",
  942. .encoded_video_codecs = "h264",
  943. .encoded_audio_codecs = "opus",
  944. .get_name = ftl_stream_getname,
  945. .create = ftl_stream_create,
  946. .destroy = ftl_stream_destroy,
  947. .start = ftl_stream_start,
  948. .stop = ftl_stream_stop,
  949. .encoded_packet = ftl_stream_data,
  950. .get_defaults = ftl_stream_defaults,
  951. .get_properties = ftl_stream_properties,
  952. .get_total_bytes = ftl_stream_total_bytes_sent,
  953. .get_congestion = ftl_stream_congestion,
  954. .get_dropped_frames = ftl_stream_dropped_frames,
  955. };