bonjour.m 15.7 KB
Newer Older
1 2 3 4 5 6
/*****************************************************************************
 * bonjour.m: mDNS services discovery module based on Bonjour
 *****************************************************************************
 * Copyright (C) 2016 VLC authors, VideoLAN and VideoLabs
 *
 * Authors: Felix Paul Kühne <fkuehne@videolan.org>
7
 *          Marvin Scholz <epirat07@gmail.com>
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_modules.h>
#include <vlc_services_discovery.h>
32
#include <vlc_renderer_discovery.h>
33 34 35

#import <Foundation/Foundation.h>

36 37 38 39 40 41 42
#pragma mark Function declarations

static int OpenSD( vlc_object_t * );
static void CloseSD( vlc_object_t * );

static int OpenRD( vlc_object_t * );
static void CloseRD( vlc_object_t * );
43

44
VLC_SD_PROBE_HELPER( "Bonjour", N_("Bonjour Network Discovery"), SD_CAT_LAN )
45 46 47 48 49 50 51 52 53 54 55
VLC_RD_PROBE_HELPER( "Bonjour_renderer", "Bonjour Renderer Discovery" )

struct services_discovery_sys_t
{
    CFTypeRef _Nullable discoveryController;
};

struct vlc_renderer_discovery_sys
{
    CFTypeRef _Nullable discoveryController;
};
56 57 58 59 60

/*
 * Module descriptor
 */
vlc_module_begin()
Felix Paul Kühne's avatar
Felix Paul Kühne committed
61 62 63 64 65
    set_shortname( "Bonjour" )
    set_description( N_( "Bonjour Network Discovery" ) )
    set_category( CAT_PLAYLIST )
    set_subcategory( SUBCAT_PLAYLIST_SD )
    set_capability( "services_discovery", 0 )
66
    set_callbacks( OpenSD, CloseSD )
Felix Paul Kühne's avatar
Felix Paul Kühne committed
67 68
    add_shortcut( "mdns", "bonjour" )
    VLC_SD_PROBE_SUBMODULE
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    add_submodule() \
        set_description( N_( "Bonjour Renderer Discovery" ) )
        set_category( CAT_SOUT )
        set_subcategory( SUBCAT_SOUT_RENDERER )
        set_capability( "renderer_discovery", 0 )
        set_callbacks( OpenRD, CloseRD )
        add_shortcut( "mdns_renderer", "bonjour_renderer" )
        VLC_RD_PROBE_SUBMODULE
vlc_module_end()

NSString *const VLCBonjourProtocolName          = @"VLCBonjourProtocolName";
NSString *const VLCBonjourProtocolServiceName   = @"VLCBonjourProtocolServiceName";
NSString *const VLCBonjourIsRenderer            = @"VLCBonjourIsRenderer";
NSString *const VLCBonjourRendererFlags         = @"VLCBonjourRendererFlags";
NSString *const VLCBonjourRendererDemux         = @"VLCBonjourRendererDemux";

#pragma mark -
#pragma mark Interface definition
87 88
@interface VLCNetServiceDiscoveryController : NSObject <NSNetServiceBrowserDelegate, NSNetServiceDelegate>
{
89
    /* Stores all used service browsers, one for each protocol, usually */
90 91
    NSArray *_serviceBrowsers;

92
    /* Holds a required reference to all NSNetServices */
93
    NSMutableArray *_rawNetServices;
94 95

    /* Holds all successfully resolved NSNetServices */
96
    NSMutableArray *_resolvedNetServices;
97 98

    /* Holds the respective pointers to a vlc_object for each resolved and added NSNetService */
99
    NSMutableArray *_inputItemsForNetServices;
100

101
    /* Stores all protocols that are currently discovered */
102 103 104
    NSArray *_activeProtocols;
}

105 106 107 108 109
@property (readonly) BOOL isRendererDiscovery;
@property (readonly, nonatomic) vlc_object_t *p_this;

- (instancetype)initWithRendererDiscoveryObject:(vlc_renderer_discovery_t *)p_rd;
- (instancetype)initWithServicesDiscoveryObject:(services_discovery_t *)p_sd;
110 111 112 113 114 115

- (void)startDiscovery;
- (void)stopDiscovery;

@end

116 117 118
@implementation VLCNetServiceDiscoveryController

- (instancetype)initWithRendererDiscoveryObject:(vlc_renderer_discovery_t *)p_rd
119
{
120 121 122 123 124
    self = [super init];
    if (self) {
        _p_this = VLC_OBJECT( p_rd );
        _isRendererDiscovery = YES;
    }
125

126 127 128 129 130 131 132 133 134 135 136 137 138
    return self;
}

- (instancetype)initWithServicesDiscoveryObject:(services_discovery_t *)p_sd
{
    self = [super init];
    if (self) {
        _p_this = VLC_OBJECT( p_sd );
        _isRendererDiscovery = NO;
    }

    return self;
}
139 140 141

- (void)startDiscovery
{
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
    NSDictionary *VLCFtpProtocol = @{ VLCBonjourProtocolName        : @"ftp",
                                      VLCBonjourProtocolServiceName : @"_ftp._tcp.",
                                      VLCBonjourIsRenderer          : @(NO)
                                      };
    NSDictionary *VLCSmbProtocol = @{ VLCBonjourProtocolName        : @"smb",
                                      VLCBonjourProtocolServiceName : @"_smb._tcp.",
                                      VLCBonjourIsRenderer          : @(NO)
                                      };
    NSDictionary *VLCNfsProtocol = @{ VLCBonjourProtocolName        : @"nfs",
                                      VLCBonjourProtocolServiceName : @"_nfs._tcp.",
                                      VLCBonjourIsRenderer          : @(NO)
                                      };
    NSDictionary *VLCSftpProtocol = @{ VLCBonjourProtocolName       : @"sftp",
                                       VLCBonjourProtocolServiceName: @"_sftp-ssh._tcp.",
                                       VLCBonjourIsRenderer         : @(NO)
                                       };
    NSDictionary *VLCCastProtocol = @{ VLCBonjourProtocolName       : @"chromecast",
                                       VLCBonjourProtocolServiceName: @"_googlecast._tcp.",
                                       VLCBonjourIsRenderer         : @(YES),
                                       VLCBonjourRendererFlags      : @(VLC_RENDERER_CAN_AUDIO),
                                       VLCBonjourRendererDemux      : @"cc_demux"
                                       };

    NSArray *VLCSupportedProtocols = @[VLCFtpProtocol,
                                      VLCSmbProtocol,
                                      VLCNfsProtocol,
                                      VLCSftpProtocol,
                                      VLCCastProtocol];

171 172 173 174 175 176 177
    _rawNetServices = [[NSMutableArray alloc] init];
    _resolvedNetServices = [[NSMutableArray alloc] init];
    _inputItemsForNetServices = [[NSMutableArray alloc] init];

    NSMutableArray *discoverers = [[NSMutableArray alloc] init];
    NSMutableArray *protocols = [[NSMutableArray alloc] init];

178 179
    msg_Info(_p_this, "starting discovery");
    for (NSDictionary *protocol in VLCSupportedProtocols) {
180
        msg_Info(_p_this, "looking up %s", [[protocol objectForKey: VLCBonjourProtocolName] UTF8String]);
181

182
        /* Only discover services if we actually have a module that can handle those */
183 184
        if (!module_exists([[protocol objectForKey: VLCBonjourProtocolName] UTF8String]) && !_isRendererDiscovery) {
            msg_Info(_p_this, "no module for %s, skipping", [[protocol objectForKey: VLCBonjourProtocolName] UTF8String]);
185
            continue;
186 187 188
        }

        /* Only discover hosts it they match the current mode (renderer or service) */
189 190
        if ([[protocol objectForKey: VLCBonjourIsRenderer] boolValue] != _isRendererDiscovery) {
            msg_Info(_p_this, "%s does not match current discovery mode, skipping", [[protocol objectForKey: VLCBonjourProtocolName] UTF8String]);
191 192
            continue;
        }
193 194

        NSNetServiceBrowser *serviceBrowser = [[NSNetServiceBrowser alloc] init];
195
        [serviceBrowser setDelegate:self];
196 197
        msg_Info(_p_this, "starting discovery for type %s", [[protocol objectForKey: VLCBonjourProtocolServiceName] UTF8String]);
        [serviceBrowser searchForServicesOfType:[protocol objectForKey: VLCBonjourProtocolServiceName] inDomain:@"local."];
198 199 200 201 202 203 204 205 206 207 208 209
        [discoverers addObject:serviceBrowser];
        [protocols addObject:protocol];
    }

    _serviceBrowsers = [discoverers copy];
    _activeProtocols = [protocols copy];
}

- (void)stopDiscovery
{
    [_serviceBrowsers makeObjectsPerformSelector:@selector(stop)];

210 211 212 213
    /* Work around a macOS 10.12 bug, see https://openradar.appspot.com/28943305 */
    [_serviceBrowsers makeObjectsPerformSelector:@selector(setDelegate:) withObject:nil];
    [_resolvedNetServices makeObjectsPerformSelector:@selector(setDelegate:) withObject:nil];

214 215 216 217 218
    for (NSValue *item in _inputItemsForNetServices) {
        if (_isRendererDiscovery) {
            [self removeRawRendererItem:item];
        } else {
            [self removeRawInputItem:item];
219 220 221 222 223
        }
    }

    [_inputItemsForNetServices removeAllObjects];
    [_resolvedNetServices removeAllObjects];
224
    msg_Info(_p_this, "stopped discovery");
225 226
}

227 228
#pragma mark - 
#pragma mark Delegate methods
229 230 231

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
232 233
    msg_Info(_p_this, "found something, looking up");
    msg_Dbg(self.p_this, "found bonjour service: %s (%s)", [aNetService.name UTF8String], [aNetService.type UTF8String]);
234 235 236 237 238 239 240
    [_rawNetServices addObject:aNetService];
    aNetService.delegate = self;
    [aNetService resolveWithTimeout:5.];
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
241 242 243
    msg_Dbg(self.p_this, "bonjour service disappeared: %s", [aNetService.name UTF8String]);

    /* If the item was not looked-up yet, just remove it */
244 245 246
    if ([_rawNetServices containsObject:aNetService])
        [_rawNetServices removeObject:aNetService];

247
    /* If the item was already resolved, the associated input or renderer items needs to be removed as well */
248 249
    if ([_resolvedNetServices containsObject:aNetService]) {
        NSInteger index = [_resolvedNetServices indexOfObject:aNetService];
250
        if (index == NSNotFound) {
251
            return;
252
        }
253 254

        [_resolvedNetServices removeObjectAtIndex:index];
255 256

        if (_isRendererDiscovery) {
257
            [self removeRawRendererItem:[_inputItemsForNetServices objectAtIndex:index]];
258
        } else {
259
            [self removeRawInputItem:[_inputItemsForNetServices objectAtIndex:index]];
260
        }
261 262 263

        /* Remove item pointer from our lookup array */
        [_inputItemsForNetServices removeObjectAtIndex:index];
264 265 266 267 268
    }
}

- (void)netServiceDidResolveAddress:(NSNetService *)aNetService
{
269
    msg_Info(_p_this, "resolved something");
270 271 272
    if (![_resolvedNetServices containsObject:aNetService]) {
        NSString *serviceType = aNetService.type;
        NSString *protocol = nil;
273
        for (NSDictionary *protocolDefinition in _activeProtocols) {
274 275
            if ([serviceType isEqualToString:[protocolDefinition objectForKey:VLCBonjourProtocolServiceName]]) {
                protocol = [protocolDefinition objectForKey:VLCBonjourProtocolName];
276 277 278
            }
        }

279 280 281 282
        if (_isRendererDiscovery) {
            [self addResolvedRendererItem:aNetService withProtocol:protocol];
        } else {
            [self addResolvedInputItem:aNetService withProtocol:protocol];
283 284 285 286 287 288 289 290
        }
    }

    [_rawNetServices removeObject:aNetService];
}

- (void)netService:(NSNetService *)aNetService didNotResolve:(NSDictionary *)errorDict
{
291
    msg_Dbg(_p_this, "failed to resolve: %s", [aNetService.name UTF8String]);
292 293 294
    [_rawNetServices removeObject:aNetService];
}

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
#pragma mark -
#pragma mark Helper methods

- (void)addResolvedRendererItem:(NSNetService *)netService withProtocol:(NSString *)protocol
{
    vlc_renderer_discovery_t *p_rd = (vlc_renderer_discovery_t *)_p_this;

    NSString *uri = [NSString stringWithFormat:@"%@://%@:%ld", protocol, netService.hostName, netService.port];
    NSDictionary *txtDict = [NSNetService dictionaryFromTXTRecordData:[netService TXTRecordData]];

    // TODO: Detect rendered capabilities and adapt to work with not just chromecast
    vlc_renderer_item_t *p_renderer_item = vlc_renderer_item_new( "chromecast", [netService.name UTF8String],
                                                                 [uri UTF8String], NULL, "cc_demux",
                                                                 "", VLC_RENDERER_CAN_VIDEO );
    if (p_renderer_item != NULL) {
        vlc_rd_add_item( p_rd, p_renderer_item );
        [_inputItemsForNetServices addObject:[NSValue valueWithPointer:p_renderer_item]];
        [_resolvedNetServices addObject:netService];
    }
}

- (void)removeRawRendererItem:(NSValue *)item
{
    vlc_renderer_discovery_t *p_rd = (vlc_renderer_discovery_t *)_p_this;
    vlc_renderer_item_t *input_item = [item pointerValue];

    if (input_item != NULL) {
        vlc_rd_remove_item( p_rd, input_item );
        vlc_renderer_item_release( input_item );
    }
}

- (void)addResolvedInputItem:(NSNetService *)netService withProtocol:(NSString *)protocol
{
    services_discovery_t *p_sd = (services_discovery_t *)_p_this;

    NSString *uri = [NSString stringWithFormat:@"%@://%@:%ld", protocol, netService.hostName, netService.port];
    input_item_t *p_input_item = input_item_NewDirectory([uri UTF8String], [netService.name UTF8String], ITEM_NET );
    if (p_input_item != NULL) {
        services_discovery_AddItem( p_sd, p_input_item, NULL);
        [_inputItemsForNetServices addObject:[NSValue valueWithPointer:p_input_item]];
        [_resolvedNetServices addObject:netService];
    }
}

- (void)removeRawInputItem:(NSValue *)item
{
    services_discovery_t *p_sd = (services_discovery_t *)_p_this;
    input_item_t *input_item = [item pointerValue];

    if (input_item != NULL) {
        services_discovery_RemoveItem( p_sd, input_item );
        input_item_Release( input_item );
    }
}

351 352
@end

353
static int OpenSD(vlc_object_t *p_this)
354 355 356 357 358 359 360 361 362
{
    services_discovery_t *p_sd = (services_discovery_t *)p_this;
    services_discovery_sys_t *p_sys = NULL;

    p_sd->p_sys = p_sys = calloc(1, sizeof(services_discovery_sys_t));
    if (!p_sys) {
        return VLC_ENOMEM;
    }

363 364
    p_sd->description = _("Bonjour Network Discovery");

365
    VLCNetServiceDiscoveryController *discoveryController = [[VLCNetServiceDiscoveryController alloc] initWithServicesDiscoveryObject:p_sd];
366 367 368 369 370 371 372 373

    p_sys->discoveryController = CFBridgingRetain(discoveryController);

    [discoveryController startDiscovery];

    return VLC_SUCCESS;
}

374
static void CloseSD(vlc_object_t *p_this)
375 376 377 378 379 380 381 382 383 384 385 386
{
    services_discovery_t *p_sd = (services_discovery_t *)p_this;
    services_discovery_sys_t *p_sys = p_sd->p_sys;

    VLCNetServiceDiscoveryController *discoveryController = (__bridge VLCNetServiceDiscoveryController *)(p_sys->discoveryController);
    [discoveryController stopDiscovery];

    CFBridgingRelease(p_sys->discoveryController);
    discoveryController = nil;

    free(p_sys);
}
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

static int OpenRD(vlc_object_t *p_this)
{
    vlc_renderer_discovery_t *p_rd = (vlc_renderer_discovery_t *)p_this;
    vlc_renderer_discovery_sys *p_sys = NULL;

    p_rd->p_sys = p_sys = calloc(1, sizeof(vlc_renderer_discovery_sys));
    if (!p_sys) {
        return VLC_ENOMEM;
    }

    VLCNetServiceDiscoveryController *discoveryController = [[VLCNetServiceDiscoveryController alloc] initWithRendererDiscoveryObject:p_rd];

    p_sys->discoveryController = CFBridgingRetain(discoveryController);

    [discoveryController startDiscovery];

    return VLC_SUCCESS;
}

static void CloseRD(vlc_object_t *p_this)
{
    vlc_renderer_discovery_t *p_rd = (vlc_renderer_discovery_t *)p_this;
    vlc_renderer_discovery_sys *p_sys = p_rd->p_sys;

    VLCNetServiceDiscoveryController *discoveryController = (__bridge VLCNetServiceDiscoveryController *)(p_sys->discoveryController);
    [discoveryController stopDiscovery];

    CFBridgingRelease(p_sys->discoveryController);
    discoveryController = nil;

    free(p_sys);
}