1 /* 2 * libjingle 3 * Copyright 2004 Google Inc. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, 9 * this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright notice, 11 * this list of conditions and the following disclaimer in the documentation 12 * and/or other materials provided with the distribution. 13 * 3. The name of the author may not be used to endorse or promote products 14 * derived from this software without specific prior written permission. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28 #include "talk/media/devices/linuxdevicemanager.h" 29 30 #include <unistd.h> 31 #include "talk/base/fileutils.h" 32 #include "talk/base/linux.h" 33 #include "talk/base/logging.h" 34 #include "talk/base/pathutils.h" 35 #include "talk/base/physicalsocketserver.h" 36 #include "talk/base/stream.h" 37 #include "talk/base/stringutils.h" 38 #include "talk/base/thread.h" 39 #include "talk/media/base/mediacommon.h" 40 #include "talk/media/devices/libudevsymboltable.h" 41 #include "talk/media/devices/v4llookup.h" 42 #include "talk/sound/platformsoundsystem.h" 43 #include "talk/sound/platformsoundsystemfactory.h" 44 #include "talk/sound/sounddevicelocator.h" 45 #include "talk/sound/soundsysteminterface.h" 46 47 namespace cricket { 48 49 DeviceManagerInterface* DeviceManagerFactory::Create() { 50 return new LinuxDeviceManager(); 51 } 52 53 class LinuxDeviceWatcher 54 : public DeviceWatcher, 55 private talk_base::Dispatcher { 56 public: 57 explicit LinuxDeviceWatcher(DeviceManagerInterface* dm); 58 virtual ~LinuxDeviceWatcher(); 59 virtual bool Start(); 60 virtual void Stop(); 61 62 private: 63 virtual uint32 GetRequestedEvents(); 64 virtual void OnPreEvent(uint32 ff); 65 virtual void OnEvent(uint32 ff, int err); 66 virtual int GetDescriptor(); 67 virtual bool IsDescriptorClosed(); 68 69 DeviceManagerInterface* manager_; 70 LibUDevSymbolTable libudev_; 71 struct udev* udev_; 72 struct udev_monitor* udev_monitor_; 73 bool registered_; 74 }; 75 76 static const char* const kFilteredAudioDevicesName[] = { 77 #if defined(CHROMEOS) 78 "surround40:", 79 "surround41:", 80 "surround50:", 81 "surround51:", 82 "surround71:", 83 "iec958:", // S/PDIF 84 #endif 85 NULL, 86 }; 87 static const char* kFilteredVideoDevicesName[] = { 88 NULL, 89 }; 90 91 LinuxDeviceManager::LinuxDeviceManager() 92 : sound_system_(new PlatformSoundSystemFactory()) { 93 set_watcher(new LinuxDeviceWatcher(this)); 94 } 95 96 LinuxDeviceManager::~LinuxDeviceManager() { 97 } 98 99 bool LinuxDeviceManager::GetAudioDevices(bool input, 100 std::vector<Device>* devs) { 101 devs->clear(); 102 if (!sound_system_.get()) { 103 return false; 104 } 105 SoundSystemInterface::SoundDeviceLocatorList list; 106 bool success; 107 if (input) { 108 success = sound_system_->EnumerateCaptureDevices(&list); 109 } else { 110 success = sound_system_->EnumeratePlaybackDevices(&list); 111 } 112 if (!success) { 113 LOG(LS_ERROR) << "Can't enumerate devices"; 114 sound_system_.release(); 115 return false; 116 } 117 // We have to start the index at 1 because webrtc VoiceEngine puts the default 118 // device at index 0, but Enumerate(Capture|Playback)Devices does not include 119 // a locator for the default device. 120 int index = 1; 121 for (SoundSystemInterface::SoundDeviceLocatorList::iterator i = list.begin(); 122 i != list.end(); 123 ++i, ++index) { 124 devs->push_back(Device((*i)->name(), index)); 125 } 126 SoundSystemInterface::ClearSoundDeviceLocatorList(&list); 127 sound_system_.release(); 128 return FilterDevices(devs, kFilteredAudioDevicesName); 129 } 130 131 static const std::string kVideoMetaPathK2_4("/proc/video/dev/"); 132 static const std::string kVideoMetaPathK2_6("/sys/class/video4linux/"); 133 134 enum MetaType { M2_4, M2_6, NONE }; 135 136 static void ScanDeviceDirectory(const std::string& devdir, 137 std::vector<Device>* devices) { 138 talk_base::scoped_ptr<talk_base::DirectoryIterator> directoryIterator( 139 talk_base::Filesystem::IterateDirectory()); 140 141 if (directoryIterator->Iterate(talk_base::Pathname(devdir))) { 142 do { 143 std::string filename = directoryIterator->Name(); 144 std::string device_name = devdir + filename; 145 if (!directoryIterator->IsDots()) { 146 if (filename.find("video") == 0 && 147 V4LLookup::IsV4L2Device(device_name)) { 148 devices->push_back(Device(device_name, device_name)); 149 } 150 } 151 } while (directoryIterator->Next()); 152 } 153 } 154 155 static std::string GetVideoDeviceNameK2_6(const std::string& device_meta_path) { 156 std::string device_name; 157 158 talk_base::scoped_ptr<talk_base::FileStream> device_meta_stream( 159 talk_base::Filesystem::OpenFile(device_meta_path, "r")); 160 161 if (device_meta_stream) { 162 if (device_meta_stream->ReadLine(&device_name) != talk_base::SR_SUCCESS) { 163 LOG(LS_ERROR) << "Failed to read V4L2 device meta " << device_meta_path; 164 } 165 device_meta_stream->Close(); 166 } 167 168 return device_name; 169 } 170 171 static std::string Trim(const std::string& s, const std::string& drop = " \t") { 172 std::string::size_type first = s.find_first_not_of(drop); 173 std::string::size_type last = s.find_last_not_of(drop); 174 175 if (first == std::string::npos || last == std::string::npos) 176 return std::string(""); 177 178 return s.substr(first, last - first + 1); 179 } 180 181 static std::string GetVideoDeviceNameK2_4(const std::string& device_meta_path) { 182 talk_base::ConfigParser::MapVector all_values; 183 184 talk_base::ConfigParser config_parser; 185 talk_base::FileStream* file_stream = 186 talk_base::Filesystem::OpenFile(device_meta_path, "r"); 187 188 if (file_stream == NULL) return ""; 189 190 config_parser.Attach(file_stream); 191 config_parser.Parse(&all_values); 192 193 for (talk_base::ConfigParser::MapVector::iterator i = all_values.begin(); 194 i != all_values.end(); ++i) { 195 talk_base::ConfigParser::SimpleMap::iterator device_name_i = 196 i->find("name"); 197 198 if (device_name_i != i->end()) { 199 return device_name_i->second; 200 } 201 } 202 203 return ""; 204 } 205 206 static std::string GetVideoDeviceName(MetaType meta, 207 const std::string& device_file_name) { 208 std::string device_meta_path; 209 std::string device_name; 210 std::string meta_file_path; 211 212 if (meta == M2_6) { 213 meta_file_path = kVideoMetaPathK2_6 + device_file_name + "/name"; 214 215 LOG(LS_INFO) << "Trying " + meta_file_path; 216 device_name = GetVideoDeviceNameK2_6(meta_file_path); 217 218 if (device_name.empty()) { 219 meta_file_path = kVideoMetaPathK2_6 + device_file_name + "/model"; 220 221 LOG(LS_INFO) << "Trying " << meta_file_path; 222 device_name = GetVideoDeviceNameK2_6(meta_file_path); 223 } 224 } else { 225 meta_file_path = kVideoMetaPathK2_4 + device_file_name; 226 LOG(LS_INFO) << "Trying " << meta_file_path; 227 device_name = GetVideoDeviceNameK2_4(meta_file_path); 228 } 229 230 if (device_name.empty()) { 231 device_name = "/dev/" + device_file_name; 232 LOG(LS_ERROR) 233 << "Device name not found, defaulting to device path " << device_name; 234 } 235 236 LOG(LS_INFO) << "Name for " << device_file_name << " is " << device_name; 237 238 return Trim(device_name); 239 } 240 241 static void ScanV4L2Devices(std::vector<Device>* devices) { 242 LOG(LS_INFO) << ("Enumerating V4L2 devices"); 243 244 MetaType meta; 245 std::string metadata_dir; 246 247 talk_base::scoped_ptr<talk_base::DirectoryIterator> directoryIterator( 248 talk_base::Filesystem::IterateDirectory()); 249 250 // Try and guess kernel version 251 if (directoryIterator->Iterate(kVideoMetaPathK2_6)) { 252 meta = M2_6; 253 metadata_dir = kVideoMetaPathK2_6; 254 } else if (directoryIterator->Iterate(kVideoMetaPathK2_4)) { 255 meta = M2_4; 256 metadata_dir = kVideoMetaPathK2_4; 257 } else { 258 meta = NONE; 259 } 260 261 if (meta != NONE) { 262 LOG(LS_INFO) << "V4L2 device metadata found at " << metadata_dir; 263 264 do { 265 std::string filename = directoryIterator->Name(); 266 267 if (filename.find("video") == 0) { 268 std::string device_path = "/dev/" + filename; 269 270 if (V4LLookup::IsV4L2Device(device_path)) { 271 devices->push_back( 272 Device(GetVideoDeviceName(meta, filename), device_path)); 273 } 274 } 275 } while (directoryIterator->Next()); 276 } else { 277 LOG(LS_ERROR) << "Unable to detect v4l2 metadata directory"; 278 } 279 280 if (devices->size() == 0) { 281 LOG(LS_INFO) << "Plan B. Scanning all video devices in /dev directory"; 282 ScanDeviceDirectory("/dev/", devices); 283 } 284 285 LOG(LS_INFO) << "Total V4L2 devices found : " << devices->size(); 286 } 287 288 bool LinuxDeviceManager::GetVideoCaptureDevices(std::vector<Device>* devices) { 289 devices->clear(); 290 ScanV4L2Devices(devices); 291 return FilterDevices(devices, kFilteredVideoDevicesName); 292 } 293 294 LinuxDeviceWatcher::LinuxDeviceWatcher(DeviceManagerInterface* dm) 295 : DeviceWatcher(dm), 296 manager_(dm), 297 udev_(NULL), 298 udev_monitor_(NULL), 299 registered_(false) { 300 } 301 302 LinuxDeviceWatcher::~LinuxDeviceWatcher() { 303 } 304 305 bool LinuxDeviceWatcher::Start() { 306 // We deliberately return true in the failure paths here because libudev is 307 // not a critical component of a Linux system so it may not be present/usable, 308 // and we don't want to halt LinuxDeviceManager initialization in such a case. 309 if (!libudev_.Load()) { 310 LOG(LS_WARNING) << "libudev not present/usable; LinuxDeviceWatcher disabled"; 311 return true; 312 } 313 udev_ = libudev_.udev_new()(); 314 if (!udev_) { 315 LOG_ERR(LS_ERROR) << "udev_new()"; 316 return true; 317 } 318 // The second argument here is the event source. It can be either "kernel" or 319 // "udev", but "udev" is the only correct choice. Apps listen on udev and the 320 // udev daemon in turn listens on the kernel. 321 udev_monitor_ = libudev_.udev_monitor_new_from_netlink()(udev_, "udev"); 322 if (!udev_monitor_) { 323 LOG_ERR(LS_ERROR) << "udev_monitor_new_from_netlink()"; 324 return true; 325 } 326 // We only listen for changes in the video devices. Audio devices are more or 327 // less unimportant because receiving device change notifications really only 328 // matters for broadcasting updated send/recv capabilities based on whether 329 // there is at least one device available, and almost all computers have at 330 // least one audio device. Also, PulseAudio device notifications don't come 331 // from the udev daemon, they come from the PulseAudio daemon, so we'd only 332 // want to listen for audio device changes from udev if using ALSA. For 333 // simplicity, we don't bother with any audio stuff at all. 334 if (libudev_.udev_monitor_filter_add_match_subsystem_devtype()( 335 udev_monitor_, "video4linux", NULL) < 0) { 336 LOG_ERR(LS_ERROR) << "udev_monitor_filter_add_match_subsystem_devtype()"; 337 return true; 338 } 339 if (libudev_.udev_monitor_enable_receiving()(udev_monitor_) < 0) { 340 LOG_ERR(LS_ERROR) << "udev_monitor_enable_receiving()"; 341 return true; 342 } 343 static_cast<talk_base::PhysicalSocketServer*>( 344 talk_base::Thread::Current()->socketserver())->Add(this); 345 registered_ = true; 346 return true; 347 } 348 349 void LinuxDeviceWatcher::Stop() { 350 if (registered_) { 351 static_cast<talk_base::PhysicalSocketServer*>( 352 talk_base::Thread::Current()->socketserver())->Remove(this); 353 registered_ = false; 354 } 355 if (udev_monitor_) { 356 libudev_.udev_monitor_unref()(udev_monitor_); 357 udev_monitor_ = NULL; 358 } 359 if (udev_) { 360 libudev_.udev_unref()(udev_); 361 udev_ = NULL; 362 } 363 libudev_.Unload(); 364 } 365 366 uint32 LinuxDeviceWatcher::GetRequestedEvents() { 367 return talk_base::DE_READ; 368 } 369 370 void LinuxDeviceWatcher::OnPreEvent(uint32 ff) { 371 // Nothing to do. 372 } 373 374 void LinuxDeviceWatcher::OnEvent(uint32 ff, int err) { 375 udev_device* device = libudev_.udev_monitor_receive_device()(udev_monitor_); 376 if (!device) { 377 // Probably the socket connection to the udev daemon was terminated (perhaps 378 // the daemon crashed or is being restarted?). 379 LOG_ERR(LS_WARNING) << "udev_monitor_receive_device()"; 380 // Stop listening to avoid potential livelock (an fd with EOF in it is 381 // always considered readable). 382 static_cast<talk_base::PhysicalSocketServer*>( 383 talk_base::Thread::Current()->socketserver())->Remove(this); 384 registered_ = false; 385 return; 386 } 387 // Else we read the device successfully. 388 389 // Since we already have our own filesystem-based device enumeration code, we 390 // simply re-enumerate rather than inspecting the device event. 391 libudev_.udev_device_unref()(device); 392 manager_->SignalDevicesChange(); 393 } 394 395 int LinuxDeviceWatcher::GetDescriptor() { 396 return libudev_.udev_monitor_get_fd()(udev_monitor_); 397 } 398 399 bool LinuxDeviceWatcher::IsDescriptorClosed() { 400 // If it is closed then we will just get an error in 401 // udev_monitor_receive_device and unregister, so we don't need to check for 402 // it separately. 403 return false; 404 } 405 406 }; // namespace cricket 407