/
AntMediaApplicationAdapter.java
1527 lines (1261 loc) · 53.7 KB
/
AntMediaApplicationAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.antmedia;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.red5.server.api.scope.IBroadcastScope;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.api.stream.IClientBroadcastStream;
import org.red5.server.api.stream.IPlayItem;
import org.red5.server.api.stream.IStreamCapableConnection;
import org.red5.server.api.stream.IStreamPublishSecurity;
import org.red5.server.api.stream.IStreamService;
import org.red5.server.api.stream.ISubscriberStream;
import org.red5.server.stream.ClientBroadcastStream;
import org.red5.server.stream.StreamService;
import org.red5.server.util.ScopeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import io.antmedia.cluster.IClusterNotifier;
import io.antmedia.datastore.db.DataStore;
import io.antmedia.datastore.db.DataStoreFactory;
import io.antmedia.datastore.db.IDataStoreFactory;
import io.antmedia.datastore.db.types.Broadcast;
import io.antmedia.datastore.db.types.Endpoint;
import io.antmedia.datastore.db.types.SocialEndpointCredentials;
import io.antmedia.datastore.db.types.VoD;
import io.antmedia.datastore.preference.PreferenceStore;
import io.antmedia.filter.StreamAcceptFilter;
import io.antmedia.ipcamera.OnvifCamera;
import io.antmedia.muxer.IAntMediaStreamHandler;
import io.antmedia.muxer.MuxAdaptor;
import io.antmedia.rest.RestServiceBase;
import io.antmedia.rest.model.Result;
import io.antmedia.security.AcceptOnlyStreamsInDataStore;
import io.antmedia.settings.ServerSettings;
import io.antmedia.shutdown.AMSShutdownManager;
import io.antmedia.shutdown.IShutdownListener;
import io.antmedia.social.endpoint.PeriscopeEndpoint;
import io.antmedia.social.endpoint.VideoServiceEndpoint;
import io.antmedia.social.endpoint.VideoServiceEndpoint.DeviceAuthParameters;
import io.antmedia.statistic.HlsViewerStats;
import io.antmedia.statistic.type.RTMPToWebRTCStats;
import io.antmedia.statistic.type.WebRTCAudioReceiveStats;
import io.antmedia.statistic.type.WebRTCAudioSendStats;
import io.antmedia.statistic.type.WebRTCVideoReceiveStats;
import io.antmedia.statistic.type.WebRTCVideoSendStats;
import io.antmedia.streamsource.StreamFetcher;
import io.antmedia.streamsource.StreamFetcherManager;
import io.antmedia.webrtc.api.IWebRTCAdaptor;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.dropwizard.MetricsService;
public class AntMediaApplicationAdapter implements IAntMediaStreamHandler, IShutdownListener {
public static final String BEAN_NAME = "web.handler";
public static final int BROADCAST_STATS_RESET = 0;
public static final String HOOK_ACTION_END_LIVE_STREAM = "liveStreamEnded";
public static final String HOOK_ACTION_START_LIVE_STREAM = "liveStreamStarted";
public static final String HOOK_ACTION_VOD_READY = "vodReady";
public static final String DEFAULT_LOCALHOST = "127.0.0.1";
protected static Logger logger = LoggerFactory.getLogger(AntMediaApplicationAdapter.class);
private ServerSettings serverSettings;
public static final String VOD = "VoD";
public static final String LIVE_STREAM = "liveStream";
public static final String IP_CAMERA = "ipCamera";
public static final String STREAM_SOURCE = "streamSource";
public static final String PLAY_LIST = "playlist";
protected static final int END_POINT_LIMIT = 20;
public static final String FACEBOOK = "facebook";
public static final String PERISCOPE = "periscope";
public static final String YOUTUBE = "youtube";
public static final String FACEBOOK_ENDPOINT_CLASS = "io.antmedia.enterprise.social.endpoint.FacebookEndpoint";
public static final String YOUTUBE_ENDPOINT_CLASS = "io.antmedia.enterprise.social.endpoint.YoutubeEndpoint";
public static final String WEBAPPS_PATH = "webapps/";
private Map<String, VideoServiceEndpoint> videoServiceEndpoints = new HashMap<>();
private List<VideoServiceEndpoint> videoServiceEndpointsHavingError = new ArrayList<>();
private List<IStreamPublishSecurity> streamPublishSecurityList;
private HashMap<String, OnvifCamera> onvifCameraList = new HashMap<>();
protected StreamFetcherManager streamFetcherManager;
protected List<MuxAdaptor> muxAdaptors;
private DataStore dataStore;
private DataStoreFactory dataStoreFactory;
private StreamAcceptFilter streamAcceptFilter;
private AppSettings appSettings;
private Vertx vertx;
private IScope scope;
protected List<String> encoderBlockedStreams = new ArrayList<>();
private int numberOfEncoderNotOpenedErrors = 0;
protected int publishTimeoutStreams = 0;
private List<String> publishTimeoutStreamsList = new ArrayList<>();
private boolean shutdownProperly = true;
protected WebRTCVideoReceiveStats webRTCVideoReceiveStats = new WebRTCVideoReceiveStats();
protected WebRTCAudioReceiveStats webRTCAudioReceiveStats = new WebRTCAudioReceiveStats();
protected WebRTCVideoSendStats webRTCVideoSendStats = new WebRTCVideoSendStats();
protected WebRTCAudioSendStats webRTCAudioSendStats = new WebRTCAudioSendStats();
private IClusterNotifier clusterNotifier;
protected boolean serverShuttingDown = false;
public boolean appStart(IScope app) {
setScope(app);
vertx = (Vertx) app.getContext().getBean(VERTX_BEAN_NAME);
//initalize to access the data store directly in the code
getDataStore();
// Create initialized file in application
Result result = createInitializationProcess(app.getName());
if (!result.isSuccess()) {
//Save App Setting
this.shutdownProperly = false;
// Reset Broadcast Stats
resetBroadcasts();
}
if (app.getContext().hasBean(IClusterNotifier.BEAN_NAME)) {
//which means it's in cluster mode
clusterNotifier = (IClusterNotifier) app.getContext().getBean(IClusterNotifier.BEAN_NAME);
logger.info("Registering settings listener to the cluster notifier for app: {}", app.getName());
clusterNotifier.registerSettingUpdateListener(getAppSettings().getAppName(), settings -> {
updateSettings(settings, false);
});
AppSettings storedSettings = clusterNotifier.getClusterStore().getSettings(app.getName());
boolean updateClusterSettings = false;
if(storedSettings == null)
{
storedSettings = appSettings;
updateClusterSettings = true;
}
else if (storedSettings.isToBeDeleted())
{
logger.warn("There is a stored settings for the app:{} and it's status to be deleted. Probably, application with the same name is deleted/created again", app.getName());
//this update make the app not to be deleted
updateClusterSettings = true;
}
logger.info("Updating settings while app({}) is being started. Update cluster db for appsettings -> {}", app.getName(), updateClusterSettings);
updateSettings(storedSettings, updateClusterSettings);
}
vertx.setTimer(10, l -> {
getStreamFetcherManager();
if(appSettings.isStartStreamFetcherAutomatically()) {
List<Broadcast> streams = getDataStore().getExternalStreamsList();
logger.info("Stream source size: {}", streams.size());
streamFetcherManager.startStreams(streams);
}
List<SocialEndpointCredentials> socialEndpoints = getDataStore().getSocialEndpoints(0, END_POINT_LIMIT);
logger.info("socialEndpoints size: {}", socialEndpoints.size());
for (SocialEndpointCredentials socialEndpointCredentials : socialEndpoints)
{
VideoServiceEndpoint endPointService = null;
if (socialEndpointCredentials.getServiceName().equals(FACEBOOK))
{
endPointService = getEndpointService(FACEBOOK_ENDPOINT_CLASS, socialEndpointCredentials, appSettings.getFacebookClientId(), appSettings.getFacebookClientSecret());
}
else if (socialEndpointCredentials.getServiceName().equals(PERISCOPE))
{
endPointService = getEndpointService(PeriscopeEndpoint.class.getName(), socialEndpointCredentials, appSettings.getPeriscopeClientId(), appSettings.getPeriscopeClientSecret());
}
else if (socialEndpointCredentials.getServiceName().equals(YOUTUBE))
{
endPointService = getEndpointService(YOUTUBE_ENDPOINT_CLASS, socialEndpointCredentials, appSettings.getYoutubeClientId(), appSettings.getYoutubeClientSecret());
}
if (endPointService != null) {
endPointService.setCollectInteractivity(appSettings.isCollectSocialMediaActivity());
videoServiceEndpoints.put(endPointService.getCredentials().getId(), endPointService);
}
}
synchUserVoDFolder(null, appSettings.getVodFolder());
});
AMSShutdownManager.getInstance().subscribe(this);
//With the common app structure, we won't need to null check for WebRTCAdaptor
if (app.getContext().hasBean(IWebRTCAdaptor.BEAN_NAME))
{
IWebRTCAdaptor webRTCAdaptor = (IWebRTCAdaptor) app.getContext().getBean(IWebRTCAdaptor.BEAN_NAME);
webRTCAdaptor.setExcessiveBandwidthValue(appSettings.getExcessiveBandwidthValue());
webRTCAdaptor.setExcessiveBandwidthCallThreshold(appSettings.getExcessiveBandwidthCallThreshold());
webRTCAdaptor.setTryCountBeforeSwitchback(appSettings.getExcessiveBandwithTryCountBeforeSwitchback());
webRTCAdaptor.setExcessiveBandwidthAlgorithmEnabled(appSettings.isExcessiveBandwidthAlgorithmEnabled());
webRTCAdaptor.setPacketLossDiffThresholdForSwitchback(appSettings.getPacketLossDiffThresholdForSwitchback());
webRTCAdaptor.setRttMeasurementDiffThresholdForSwitchback(appSettings.getRttMeasurementDiffThresholdForSwitchback());
}
logger.info("{} started", app.getName());
return true;
}
public void appStop(IScope app)
{
//not used
}
/**
* This method is called after ungraceful shutdown
* @return
*/
public Result resetBroadcasts(){
logger.info("Resetting streams viewer numbers because there is an unexpected stop happened in app: {}", getScope() != null? getScope().getName() : "[scope is null]");
int operationCount = getDataStore().resetBroadcasts(getServerSettings().getHostAddress());
logger.info("Resetting subscriber connection status" );
getDataStore().resetSubscribersConnectedStatus();
Result result = new Result(true);
result.setMessage("Successfull operations: "+ operationCount);
return result;
}
public boolean synchUserVoDFolder(String oldFolderPath, String vodFolderPath)
{
boolean result = false;
File streamsFolder = new File(WEBAPPS_PATH + getScope().getName() + "/streams");
try {
deleteOldFolderPath(oldFolderPath, streamsFolder);
//even if an exception occurs, catch it in here and do not prevent the below operations
} catch (IOException e) {
logger.error(e.getMessage());
}
File f = new File(vodFolderPath == null ? "" : vodFolderPath);
try {
if (!streamsFolder.exists()) {
streamsFolder.mkdir();
}
if (f.exists() && f.isDirectory()) {
String newLinkPath = streamsFolder.getAbsolutePath() + "/" + f.getName();
File newLinkFile = new File(newLinkPath);
if (!newLinkFile.exists()) {
Path target = f.toPath();
Files.createSymbolicLink(newLinkFile.toPath(), target);
}
}
//if file does not exists, it means reset the vod
getDataStore().fetchUserVodList(f);
result = true;
} catch (IOException e) {
logger.error(e.getMessage());
}
return result;
}
public boolean deleteOldFolderPath(String oldFolderPath, File streamsFolder) throws IOException {
boolean result = false;
if (oldFolderPath != null && !oldFolderPath.isEmpty() && streamsFolder != null)
{
File f = new File(oldFolderPath);
File linkFile = new File(streamsFolder.getAbsolutePath(), f.getName());
if (linkFile.exists() && linkFile.isDirectory()) {
Files.delete(linkFile.toPath());
result = true;
}
}
return result;
}
public void streamBroadcastClose(IBroadcastStream stream) {
String streamName = stream.getPublishedName();
vertx.executeBlocking(future -> closeBroadcast(streamName), null);
}
public void closeBroadcast(String streamName) {
try {
logger.info("Closing broadcast stream id: {}", streamName);
getDataStore().updateStatus(streamName, BROADCAST_STATUS_FINISHED);
Broadcast broadcast = getDataStore().get(streamName);
if (broadcast != null) {
final String listenerHookURL = broadcast.getListenerHookURL();
final String streamId = broadcast.getStreamId();
if (listenerHookURL != null && listenerHookURL.length() > 0) {
final String name = broadcast.getName();
final String category = broadcast.getCategory();
logger.info("Setting timer to call live stream ended hook for stream:{}",streamId );
vertx.setTimer(10, e -> notifyHook(listenerHookURL, streamId, HOOK_ACTION_END_LIVE_STREAM, name, category, null, null));
}
stopPublishingSocialEndpoints(broadcast);
if (broadcast.isZombi()) {
getDataStore().delete(streamName);
}
else {
// This is resets Viewer map in HLS Viewer Stats
resetHLSStats(streamId);
}
}
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
public void resetHLSStats(String streamId) {
if (scope.getContext().getApplicationContext().containsBean(HlsViewerStats.BEAN_NAME)) {
HlsViewerStats hlsViewerStats = (HlsViewerStats) scope.getContext().getApplicationContext().getBean(HlsViewerStats.BEAN_NAME);
if (hlsViewerStats != null) {
hlsViewerStats.resetHLSViewerMap(streamId);
}
}
}
public void stopPublishingSocialEndpoints(Broadcast broadcast)
{
List<Endpoint> endPointList = broadcast.getEndPointList();
if (endPointList != null) {
for (Endpoint endpoint : endPointList) {
VideoServiceEndpoint videoServiceEndPoint = getVideoServiceEndPoint(endpoint.getEndpointServiceId());
if (videoServiceEndPoint != null) {
try {
videoServiceEndPoint.stopBroadcast(endpoint);
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
}
// recreate endpoints for social media
recreateEndpointsForSocialMedia(broadcast, endPointList);
}
}
public void recreateEndpointsForSocialMedia(Broadcast broadcast, List<Endpoint> endPointList) {
//below removeList and addList is due to avoid concurrent exception
List<Endpoint> removeList = new ArrayList<>();
List<Endpoint> addList = new ArrayList<>();
for (Endpoint endpoint : endPointList) {
if (!"".equals(endpoint.getType()))
{
VideoServiceEndpoint videoServiceEndPoint = getVideoServiceEndPoint(endpoint.getEndpointServiceId());
if (videoServiceEndPoint != null)
{
Endpoint newEndpoint;
try {
newEndpoint = videoServiceEndPoint.createBroadcast(broadcast.getName(),
broadcast.getDescription(), broadcast.getStreamId(), broadcast.isIs360(), broadcast.isPublicStream(), 2160, true);
removeList.add(endpoint);
addList.add(newEndpoint);
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
}
}
for (Endpoint endpoint : removeList) {
getDataStore().removeEndpoint(broadcast.getStreamId(), endpoint, true);
}
for (Endpoint endpoint : addList) {
getDataStore().addEndpoint(broadcast.getStreamId(), endpoint);
}
}
public VideoServiceEndpoint getEndpointService(String className,
SocialEndpointCredentials socialEndpointCredentials, String clientId, String clientSecret)
{
try {
VideoServiceEndpoint endPointService;
Class endpointClass = Class.forName(className);
endPointService = (VideoServiceEndpoint) endpointClass.getConstructor(String.class, String.class, DataStore.class, SocialEndpointCredentials.class, Vertx.class)
.newInstance(clientId, clientSecret, getDataStore(), socialEndpointCredentials, vertx);
endPointService.setCollectInteractivity(appSettings.isCollectSocialMediaActivity());
return endPointService;
}
catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
return null;
}
public void streamPlayItemPlay(IPlayItem item, boolean isLive) {
vertx.setTimer(1, l -> getDataStore().updateRtmpViewerCount(item.getName(), true));
}
public void streamPlayItemStop(IPlayItem item) {
vertx.setTimer(1, l -> getDataStore().updateRtmpViewerCount(item.getName(), false));
}
public void streamSubscriberClose(ISubscriberStream stream) {
vertx.setTimer(1, l -> getDataStore().updateRtmpViewerCount(stream.getBroadcastStreamPublishName(), false));
}
public void streamPublishStart(final IBroadcastStream stream) {
String streamName = stream.getPublishedName();
logger.info("stream name in streamPublishStart: {}", streamName );
long absoluteStartTimeMs = 0;
if (stream instanceof ClientBroadcastStream) {
absoluteStartTimeMs = ((ClientBroadcastStream) stream).getAbsoluteStartTimeMs();
}
startPublish(streamName, absoluteStartTimeMs);
}
public void startPublish(String streamName, long absoluteStartTimeMs) {
vertx.executeBlocking( handler -> {
try {
DataStore dataStoreLocal = getDataStore();
Broadcast broadcast = dataStoreLocal.get(streamName);
if (broadcast == null) {
broadcast = saveUndefinedBroadcast(streamName, getScope().getName(), dataStoreLocal, appSettings, IAntMediaStreamHandler.BROADCAST_STATUS_BROADCASTING, getServerSettings(), absoluteStartTimeMs);
}
else {
broadcast.setStatus(BROADCAST_STATUS_BROADCASTING);
broadcast.setStartTime(System.currentTimeMillis());
broadcast.setOriginAdress(getServerSettings().getHostAddress());
broadcast.setWebRTCViewerCount(0);
broadcast.setHlsViewerCount(0);
boolean result = dataStoreLocal.updateBroadcastFields(broadcast.getStreamId(), broadcast);
logger.info(" Status of stream {} is set to Broadcasting with result: {}", broadcast.getStreamId(), result);
}
final String listenerHookURL = broadcast.getListenerHookURL();
final String streamId = broadcast.getStreamId();
if (listenerHookURL != null && !listenerHookURL.isEmpty())
{
final String name = broadcast.getName();
final String category = broadcast.getCategory();
logger.info("Setting timer to call live stream started hook for stream:{}",streamId );
vertx.setTimer(10, e -> notifyHook(listenerHookURL, streamId, HOOK_ACTION_START_LIVE_STREAM, name, category,
null, null));
}
int ingestingStreamLimit = appSettings.getIngestingStreamLimit();
long activeBroadcastNumber = dataStore.getActiveBroadcastCount();
if (ingestingStreamLimit != -1 && activeBroadcastNumber > ingestingStreamLimit)
{
logger.info("Active broadcast count({}) is more than ingesting stream limit:{} so stopping broadcast:{}", activeBroadcastNumber, ingestingStreamLimit, broadcast.getStreamId());
stopStreaming(broadcast);
}
else
{
publishSocialEndpoints(broadcast.getEndPointList());
}
handler.complete();
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
handler.fail(ExceptionUtils.getStackTrace(e));
}
}, null);
if (absoluteStartTimeMs == 0)
{
vertx.setTimer(2000, h ->
{
IBroadcastStream broadcastStream = getBroadcastStream(getScope(), streamName);
if (broadcastStream instanceof ClientBroadcastStream)
{
long absoluteStarTime = ((ClientBroadcastStream)broadcastStream).getAbsoluteStartTimeMs();
if (absoluteStarTime != 0)
{
Broadcast broadcast = getDataStore().get(streamName);
if (broadcast != null)
{
broadcast.setAbsoluteStartTimeMs(absoluteStarTime);
getDataStore().save(broadcast);
logger.info("Updating broadcast absolute time {} ms for stream:{}", absoluteStarTime, streamName);
}
else {
logger.info("Broadcast is not available in the database to update the absolute start time for stream:{}", streamName);
}
}
else {
logger.info("Broadcast absolute time is not available for stream:{}", streamName);
}
}
});
}
logger.info("start publish leaved for stream:{}", streamName);
}
private ServerSettings getServerSettings()
{
if (serverSettings == null) {
serverSettings = (ServerSettings)scope.getContext().getApplicationContext().getBean(ServerSettings.BEAN_NAME);
}
return serverSettings;
}
public void publishSocialEndpoints(List<Endpoint> endPointList)
{
if (endPointList != null)
{
for (Endpoint endpoint : endPointList) {
VideoServiceEndpoint videoServiceEndPoint = getVideoServiceEndPoint(endpoint.getEndpointServiceId());
if (videoServiceEndPoint != null) {
try {
videoServiceEndPoint.publishBroadcast(endpoint);
logger.info("publish broadcast called for {}" , videoServiceEndPoint.getName());
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
}
}
}
public static Broadcast saveUndefinedBroadcast(String streamId, String scopeName, DataStore dataStore, AppSettings appSettings, String streamStatus, ServerSettings serverSettings, long absoluteStartTimeMs) {
Broadcast newBroadcast = new Broadcast();
long now = System.currentTimeMillis();
newBroadcast.setDate(now);
newBroadcast.setStartTime(now);
newBroadcast.setZombi(true);
try {
newBroadcast.setStreamId(streamId);
String settingsListenerHookURL = null;
if (appSettings != null) {
settingsListenerHookURL = appSettings.getListenerHookURL();
}
return RestServiceBase.saveBroadcast(newBroadcast,
streamStatus, scopeName, dataStore,
settingsListenerHookURL, serverSettings, absoluteStartTimeMs);
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
return null;
}
public VideoServiceEndpoint getVideoServiceEndPoint(String id) {
if (videoServiceEndpoints != null) {
return videoServiceEndpoints.get(id);
}
return null;
}
@Override
public void muxingFinished(final String streamId, File file, long duration, int resolution) {
String vodName = file.getName();
String filePath = file.getPath();
long fileSize = file.length();
long systemTime = System.currentTimeMillis();
String[] subDirs = filePath.split(Pattern.quote(File.separator));
Integer pathLength=Integer.valueOf(subDirs.length);
String relativePath= subDirs[pathLength-2]+'/'+subDirs[pathLength-1];
String listenerHookURL = null;
String streamName = file.getName();
Broadcast broadcast = getDataStore().get(streamId);
if (broadcast != null && broadcast.getName() != null) {
streamName = broadcast.getName();
listenerHookURL = broadcast.getListenerHookURL();
if (resolution != 0) {
streamName = streamName + " (" + resolution + "p)";
}
}
if (listenerHookURL == null || listenerHookURL.isEmpty()) {
// if hook URL is not defined for stream specific, then try to get common one from app
listenerHookURL = appSettings.getListenerHookURL();
}
String vodId = RandomStringUtils.randomNumeric(24);
VoD newVod = new VoD(streamName, streamId, relativePath, vodName, systemTime, duration, fileSize, VoD.STREAM_VOD, vodId);
if (getDataStore().addVod(newVod) == null) {
logger.warn("Stream vod with stream id {} cannot be added to data store", streamId);
}
int index;
//HOOK_ACTION_VOD_READY is called only the listenerHookURL is defined either for stream or in AppSettings
if (listenerHookURL != null && !listenerHookURL.isEmpty() &&
((index = vodName.lastIndexOf(".mp4")) != -1)
|| ((index = vodName.lastIndexOf(".webm")) != -1) )
{
final String baseName = vodName.substring(0, index);
String finalListenerHookURL = listenerHookURL;
logger.info("Setting timer for calling vod ready hook for stream:{}", streamId);
vertx.setTimer(10, e -> notifyHook(finalListenerHookURL, streamId, HOOK_ACTION_VOD_READY, null, null, baseName, vodId));
}
String muxerFinishScript = appSettings.getMuxerFinishScript();
if (muxerFinishScript != null && !muxerFinishScript.isEmpty()) {
runScript(muxerFinishScript + " " + file.getAbsolutePath());
}
}
public void runScript(String scriptFile) {
vertx.executeBlocking(future -> {
try {
logger.info("running muxer finish script: {}", scriptFile);
Process exec = Runtime.getRuntime().exec(scriptFile);
int result = exec.waitFor();
future.complete();
logger.info("completing script: {} with return value {}", scriptFile, result);
} catch (IOException e) {
logger.error(ExceptionUtils.getStackTrace(e));
} catch (InterruptedException e) {
logger.error(ExceptionUtils.getStackTrace(e));
Thread.currentThread().interrupt();
}
}, res -> {
});
}
private static class AuthCheckJob {
private int count;
private VideoServiceEndpoint videoServiceEndpoint;
private int interval;
private AntMediaApplicationAdapter appAdapter;
public AuthCheckJob(int count, int interval, VideoServiceEndpoint videoServiceEndpoint, AntMediaApplicationAdapter adapter) {
this.count = count;
this.videoServiceEndpoint = videoServiceEndpoint;
this.interval = interval;
this.appAdapter = adapter;
}
public void execute() {
try {
if (!videoServiceEndpoint.askIfDeviceAuthenticated()) {
count++;
if (count < 10) {
if (videoServiceEndpoint.getError() == null) {
appAdapter.getVertx().setTimer(interval, l->{
new AuthCheckJob(count, interval, videoServiceEndpoint, appAdapter).execute();
});
logger.info("Asking authetnication for {}", videoServiceEndpoint.getName());
}
else {
//there is an error so do not ask again
this.appAdapter.getVideoServiceEndpointsHavingError().add(videoServiceEndpoint);
}
}
else {
videoServiceEndpoint.setError(VideoServiceEndpoint.AUTHENTICATION_TIMEOUT);
this.appAdapter.getVideoServiceEndpointsHavingError().add(videoServiceEndpoint);
logger.info("Not authenticated for {} and will not try again", videoServiceEndpoint.getName());
}
}
else {
logger.info("Authenticated, adding video service endpoint type: {} with id: {} to the app", videoServiceEndpoint.getName(), videoServiceEndpoint.getCredentials().getId());
this.appAdapter.getVideoServiceEndpoints().put(videoServiceEndpoint.getCredentials().getId(), videoServiceEndpoint);
}
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
}
public void startDeviceAuthStatusPolling(VideoServiceEndpoint videoServiceEndpoint,
DeviceAuthParameters askDeviceAuthParameters) {
int timeDelta = askDeviceAuthParameters.interval * 1000;
getVertx().setTimer(timeDelta, l->{
new AuthCheckJob(0, timeDelta, videoServiceEndpoint, this).execute();
});
}
public Map<String, VideoServiceEndpoint> getVideoServiceEndpoints() {
return videoServiceEndpoints;
}
public List<VideoServiceEndpoint> getVideoServiceEndpointsHavingError(){
return videoServiceEndpointsHavingError ;
}
public void setVideoServiceEndpoints(Map<String, VideoServiceEndpoint> videoServiceEndpoints) {
this.videoServiceEndpoints = videoServiceEndpoints;
}
/**
* Notify hook with parameters below
*
* @param url
* is the url of the service to be called
*
* @param id
* is the stream id that is unique for each stream
*
* @param action
* is the name of the action to be notified, it has values such
* as {@link #HOOK_ACTION_END_LIVE_STREAM}
* {@link #HOOK_ACTION_START_LIVE_STREAM}
*
* @param streamName,
* name of the stream. It is not the name of the file. It is just
* a user friendly name
*
* @param category,
* category of the stream
*
* @param vodName name of the vod
*
* @param vodId id of the vod in the datastore
*
* @return
*/
public StringBuilder notifyHook(String url, String id, String action, String streamName, String category,
String vodName, String vodId) {
StringBuilder response = null;
logger.info("Running notify hook url:{} stream id: {} action:{} vod name:{} vod id:{}", url, id, action, vodName, vodId);
if (url != null && url.length() > 0) {
Map<String, String> variables = new HashMap<>();
variables.put("id", id);
variables.put("action", action);
if (streamName != null) {
variables.put("streamName", streamName);
}
if (category != null) {
variables.put("category", category);
}
if (vodName != null) {
variables.put("vodName", vodName);
}
if (vodId != null) {
variables.put("vodId", vodId);
}
try {
response = sendPOST(url, variables);
} catch (Exception e) {
//Make Exception generi
logger.error(ExceptionUtils.getStackTrace(e));
}
}
return response;
}
public StringBuilder sendPOST(String url, Map<String, String> variables) throws IOException {
StringBuilder response = null;
try (CloseableHttpClient httpClient = getHttpClient())
{
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig =RequestConfig.custom()
.setConnectTimeout(2000)
.setConnectionRequestTimeout(2000)
.setSocketTimeout(2000).build();
httpPost.setConfig(requestConfig);
List<NameValuePair> urlParameters = new ArrayList<>();
Set<Entry<String, String>> entrySet = variables.entrySet();
for (Entry<String, String> entry : entrySet) {
urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
httpPost.setEntity(postParams);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
logger.info("POST Response Status:: {}" , httpResponse.getStatusLine().getStatusCode());
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
//read entity if it's available
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String inputLine;
response = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
}
}
}
return response;
}
public CloseableHttpClient getHttpClient() {
return HttpClients.createDefault();
}
public List<IStreamPublishSecurity> getStreamPublishSecurityList() {
return streamPublishSecurityList;
}
public void setStreamPublishSecurityList(List<IStreamPublishSecurity> streamPublishSecurityList) {
this.streamPublishSecurityList = streamPublishSecurityList;
}
public AppSettings getAppSettings() {
return appSettings;
}
public void setAppSettings(AppSettings appSettings) {
this.appSettings = appSettings;
}
public StreamAcceptFilter getStreamAcceptFilter() {
return streamAcceptFilter;
}
public void setStreamAcceptFilter(StreamAcceptFilter streamAcceptFilter) {
this.streamAcceptFilter = streamAcceptFilter;
}
@Override
public boolean isValidStreamParameters(int width, int height, int fps, int bitrate, String streamId) {
return streamAcceptFilter.isValidStreamParameters(width, height, fps, bitrate, streamId);
}
public Result startStreaming(Broadcast broadcast)
{
Result result = new Result(false);
if(broadcast.getType().equals(AntMediaApplicationAdapter.IP_CAMERA) ||
broadcast.getType().equals(AntMediaApplicationAdapter.STREAM_SOURCE)) {
result = getStreamFetcherManager().startStreaming(broadcast);
}
else if (broadcast.getType().equals(AntMediaApplicationAdapter.PLAY_LIST)) {
result = getStreamFetcherManager().startPlaylist(broadcast);
}
return result;
}
public Result stopStreaming(Broadcast broadcast)
{
Result result = new Result(false);
if (broadcast.getType().equals(AntMediaApplicationAdapter.IP_CAMERA) ||
broadcast.getType().equals(AntMediaApplicationAdapter.STREAM_SOURCE) ||
broadcast.getType().equals(AntMediaApplicationAdapter.VOD))
{
result = getStreamFetcherManager().stopStreaming(broadcast.getStreamId());
}
else if (broadcast.getType().equals(AntMediaApplicationAdapter.PLAY_LIST))
{
result = getStreamFetcherManager().stopPlayList(broadcast.getStreamId());
}
else if (broadcast.getType().equals(AntMediaApplicationAdapter.LIVE_STREAM))
{
IBroadcastStream broadcastStream = getBroadcastStream(getScope(), broadcast.getStreamId());
if (broadcastStream != null)
{
IStreamCapableConnection connection = ((IClientBroadcastStream) broadcastStream).getConnection();
if (connection != null) {
connection.close();
}
else {
logger.warn("Connection is null. It should not happen for stream: {}. Analyze the logs", broadcast.getStreamId());
}
result.setSuccess(true);
}
}
return result;
}
public IBroadcastStream getBroadcastStream(IScope scope, String name) {
IStreamService service = (IStreamService) ScopeUtils.getScopeService(scope, IStreamService.class,
StreamService.class);
if (service instanceof StreamService) {
IBroadcastScope bs = ((StreamService) service).getBroadcastScope(scope, name);
if (bs != null) {
return bs.getClientBroadcastStream();
}
}
return null;
}
public OnvifCamera getOnvifCamera(String id) {
OnvifCamera onvifCamera = onvifCameraList.get(id);
if (onvifCamera == null) {
Broadcast camera = getDataStore().get(id);
if (camera != null) {
onvifCamera = new OnvifCamera();
onvifCamera.connect(camera.getIpAddr(), camera.getUsername(), camera.getPassword());
onvifCameraList.put(id, onvifCamera);
}
}
return onvifCamera;
}
public StreamFetcherManager getStreamFetcherManager() {
if(streamFetcherManager == null) {
streamFetcherManager = new StreamFetcherManager(vertx, getDataStore(), getScope());
}
return streamFetcherManager;
}
public void setStreamFetcherManager(StreamFetcherManager streamFetcherManager) {
this.streamFetcherManager = streamFetcherManager;
}
@Override
public void setQualityParameters(String id, String quality, double speed, int pendingPacketSize) {
vertx.setTimer(500, h -> {
logger.info("update source quality for stream: {} quality:{} speed:{}", id, quality, speed);
getDataStore().updateSourceQualityParameters(id, quality, speed, pendingPacketSize);
});
}
public DataStore getDataStore() {
if(dataStore == null)
{
dataStore = dataStoreFactory.getDataStore();
}
return dataStore;
}
public void setDataStore(DataStore dataStore) {
this.dataStore = dataStore;
}