[bbc] extract more and better qulities from Unified Streaming Platform m3u8 manifests
[youtube-dl] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     float_or_none,
10     int_or_none,
11     parse_duration,
12     parse_iso8601,
13     unescapeHTML,
14 )
15 from ..compat import (
16     compat_etree_fromstring,
17     compat_HTTPError,
18 )
19
20
21 class BBCCoUkIE(InfoExtractor):
22     IE_NAME = 'bbc.co.uk'
23     IE_DESC = 'BBC iPlayer'
24     _ID_REGEX = r'[pb][\da-z]{7}'
25     _VALID_URL = r'''(?x)
26                     https?://
27                         (?:www\.)?bbc\.co\.uk/
28                         (?:
29                             programmes/(?!articles/)|
30                             iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
31                             music/clips[/#]|
32                             radio/player/
33                         )
34                         (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
35                     ''' % _ID_REGEX
36
37     _MEDIASELECTOR_URLS = [
38         # Provides HQ HLS streams with even better quality that pc mediaset but fails
39         # with geolocation in some cases when it's even not geo restricted at all (e.g.
40         # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
41         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
42         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
43     ]
44
45     _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
46     _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
47     # Unified Streaming Platform
48     _USP_RE = r'/([^/]+)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
49
50     _NAMESPACES = (
51         _MEDIASELECTION_NS,
52         _EMP_PLAYLIST_NS,
53     )
54
55     _TESTS = [
56         {
57             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
58             'info_dict': {
59                 'id': 'b039d07m',
60                 'ext': 'mp4',
61                 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
62                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
63             },
64             'params': {
65                 'skip_download': True,
66             }
67         },
68         {
69             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
70             'info_dict': {
71                 'id': 'b00yng1d',
72                 'ext': 'flv',
73                 'title': 'The Man in Black: Series 3: The Printed Name',
74                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
75                 'duration': 1800,
76             },
77             'params': {
78                 # rtmp download
79                 'skip_download': True,
80             },
81             'skip': 'Episode is no longer available on BBC iPlayer Radio',
82         },
83         {
84             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
85             'info_dict': {
86                 'id': 'b00yng1d',
87                 'ext': 'flv',
88                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
89                 'description': 'Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.',
90                 'duration': 5100,
91             },
92             'params': {
93                 # rtmp download
94                 'skip_download': True,
95             },
96             'skip': 'this episode is not currently available',
97         },
98         {
99             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
100             'info_dict': {
101                 'id': 'b03k3pb7',
102                 'ext': 'flv',
103                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
104                 'description': '2. Invasion',
105                 'duration': 3600,
106             },
107             'params': {
108                 # rtmp download
109                 'skip_download': True,
110             },
111             'skip': 'this episode is not currently available',
112         }, {
113             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
114             'info_dict': {
115                 'id': 'b04v209v',
116                 'ext': 'flv',
117                 'title': 'Pete Tong, The Essential New Tune Special',
118                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
119                 'duration': 10800,
120             },
121             'params': {
122                 # rtmp download
123                 'skip_download': True,
124             },
125             'skip': 'Episode is no longer available on BBC iPlayer Radio',
126         }, {
127             'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
128             'note': 'Audio',
129             'info_dict': {
130                 'id': 'p022h44j',
131                 'ext': 'mp4',
132                 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
133                 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
134                 'duration': 227,
135             },
136             'params': {
137                 'skip_download': True,
138             }
139         }, {
140             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
141             'note': 'Video',
142             'info_dict': {
143                 'id': 'p025c103',
144                 'ext': 'mp4',
145                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
146                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
147                 'duration': 226,
148             },
149             'params': {
150                 'skip_download': True,
151             }
152         }, {
153             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
154             'info_dict': {
155                 'id': 'p02n76xf',
156                 'ext': 'flv',
157                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
158                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
159                 'duration': 3540,
160             },
161             'params': {
162                 # rtmp download
163                 'skip_download': True,
164             },
165             'skip': 'this episode is not currently available',
166         }, {
167             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
168             'info_dict': {
169                 'id': 'b05zmgw1',
170                 'ext': 'flv',
171                 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
172                 'title': 'Royal Academy Summer Exhibition',
173                 'duration': 3540,
174             },
175             'params': {
176                 # rtmp download
177                 'skip_download': True,
178             },
179             'skip': 'this episode is not currently available',
180         }, {
181             # iptv-all mediaset fails with geolocation however there is no geo restriction
182             # for this programme at all
183             'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
184             'info_dict': {
185                 'id': 'b06rkms3',
186                 'ext': 'flv',
187                 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
188                 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
189             },
190             'params': {
191                 # rtmp download
192                 'skip_download': True,
193             },
194             'skip': 'this episode is not currently available on BBC iPlayer Radio',
195         }, {
196             # compact player (https://github.com/rg3/youtube-dl/issues/8147)
197             'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
198             'info_dict': {
199                 'id': 'p028bfkj',
200                 'ext': 'mp4',
201                 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
202                 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
203             },
204             'params': {
205                 'skip_download': True,
206             },
207         }, {
208             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
209             'only_matching': True,
210         }, {
211             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
212             'only_matching': True,
213         }, {
214             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
215             'only_matching': True,
216         }, {
217             'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
218             'only_matching': True,
219         }
220     ]
221
222     class MediaSelectionError(Exception):
223         def __init__(self, id):
224             self.id = id
225
226     def _extract_asx_playlist(self, connection, programme_id):
227         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
228         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
229
230     def _extract_connection(self, connection, programme_id):
231         formats = []
232         kind = connection.get('kind')
233         protocol = connection.get('protocol')
234         supplier = connection.get('supplier')
235         if protocol == 'http':
236             href = connection.get('href')
237             transfer_format = connection.get('transferFormat')
238             # ASX playlist
239             if supplier == 'asx':
240                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
241                     formats.append({
242                         'url': ref,
243                         'format_id': 'ref%s_%s' % (i, supplier),
244                     })
245             # Skip DASH until supported
246             elif transfer_format == 'dash':
247                 pass
248             elif transfer_format == 'hls':
249                 is_unified_streaming = re.search(self._USP_RE, href)
250                 if is_unified_streaming:
251                     href = re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href)
252                 m3u8_formats = self._extract_m3u8_formats(
253                     href, programme_id, ext='mp4', entry_protocol='m3u8_native',
254                     m3u8_id=supplier, fatal=False)
255                 if is_unified_streaming:
256                     self._check_formats(m3u8_formats, programme_id)
257                 formats.extend(m3u8_formats)
258             # Direct link
259             else:
260                 formats.append({
261                     'url': href,
262                     'format_id': supplier or kind or protocol,
263                 })
264         elif protocol == 'rtmp':
265             application = connection.get('application', 'ondemand')
266             auth_string = connection.get('authString')
267             identifier = connection.get('identifier')
268             server = connection.get('server')
269             formats.append({
270                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
271                 'play_path': identifier,
272                 'app': '%s?%s' % (application, auth_string),
273                 'page_url': 'http://www.bbc.co.uk',
274                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
275                 'rtmp_live': False,
276                 'ext': 'flv',
277                 'format_id': supplier,
278             })
279         return formats
280
281     def _extract_items(self, playlist):
282         return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
283
284     def _findall_ns(self, element, xpath):
285         elements = []
286         for ns in self._NAMESPACES:
287             elements.extend(element.findall(xpath % ns))
288         return elements
289
290     def _extract_medias(self, media_selection):
291         error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
292         if error is None:
293             media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
294         if error is not None:
295             raise BBCCoUkIE.MediaSelectionError(error.get('id'))
296         return self._findall_ns(media_selection, './{%s}media')
297
298     def _extract_connections(self, media):
299         return self._findall_ns(media, './{%s}connection')
300
301     def _extract_video(self, media, programme_id):
302         formats = []
303         vbr = int_or_none(media.get('bitrate'))
304         vcodec = media.get('encoding')
305         service = media.get('service')
306         width = int_or_none(media.get('width'))
307         height = int_or_none(media.get('height'))
308         file_size = int_or_none(media.get('media_file_size'))
309         for connection in self._extract_connections(media):
310             conn_formats = self._extract_connection(connection, programme_id)
311             for format in conn_formats:
312                 if format.get('protocol') != 'm3u8_native':
313                     format.update({
314                         'width': width,
315                         'height': height,
316                         'vbr': vbr,
317                         'vcodec': vcodec,
318                         'filesize': file_size,
319                     })
320                 if service:
321                     format['format_id'] = '%s_%s' % (service, format['format_id'])
322             formats.extend(conn_formats)
323         return formats
324
325     def _extract_audio(self, media, programme_id):
326         formats = []
327         abr = int_or_none(media.get('bitrate'))
328         acodec = media.get('encoding')
329         service = media.get('service')
330         for connection in self._extract_connections(media):
331             conn_formats = self._extract_connection(connection, programme_id)
332             for format in conn_formats:
333                 format.update({
334                     'format_id': '%s_%s' % (service, format['format_id']),
335                     'abr': abr,
336                     'acodec': acodec,
337                     'vcodec': 'none',
338                 })
339             formats.extend(conn_formats)
340         return formats
341
342     def _get_subtitles(self, media, programme_id):
343         subtitles = {}
344         for connection in self._extract_connections(media):
345             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
346             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
347             subtitles[lang] = [
348                 {
349                     'url': connection.get('href'),
350                     'ext': 'ttml',
351                 },
352             ]
353         return subtitles
354
355     def _raise_extractor_error(self, media_selection_error):
356         raise ExtractorError(
357             '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
358             expected=True)
359
360     def _download_media_selector(self, programme_id):
361         last_exception = None
362         for mediaselector_url in self._MEDIASELECTOR_URLS:
363             try:
364                 return self._download_media_selector_url(
365                     mediaselector_url % programme_id, programme_id)
366             except BBCCoUkIE.MediaSelectionError as e:
367                 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
368                     last_exception = e
369                     continue
370                 self._raise_extractor_error(e)
371         self._raise_extractor_error(last_exception)
372
373     def _download_media_selector_url(self, url, programme_id=None):
374         try:
375             media_selection = self._download_xml(
376                 url, programme_id, 'Downloading media selection XML')
377         except ExtractorError as ee:
378             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
379                 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
380             else:
381                 raise
382         return self._process_media_selector(media_selection, programme_id)
383
384     def _process_media_selector(self, media_selection, programme_id):
385         formats = []
386         subtitles = None
387
388         for media in self._extract_medias(media_selection):
389             kind = media.get('kind')
390             if kind == 'audio':
391                 formats.extend(self._extract_audio(media, programme_id))
392             elif kind == 'video':
393                 formats.extend(self._extract_video(media, programme_id))
394             elif kind == 'captions':
395                 subtitles = self.extract_subtitles(media, programme_id)
396         return formats, subtitles
397
398     def _download_playlist(self, playlist_id):
399         try:
400             playlist = self._download_json(
401                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
402                 playlist_id, 'Downloading playlist JSON')
403
404             version = playlist.get('defaultAvailableVersion')
405             if version:
406                 smp_config = version['smpConfig']
407                 title = smp_config['title']
408                 description = smp_config['summary']
409                 for item in smp_config['items']:
410                     kind = item['kind']
411                     if kind != 'programme' and kind != 'radioProgramme':
412                         continue
413                     programme_id = item.get('vpid')
414                     duration = int_or_none(item.get('duration'))
415                     formats, subtitles = self._download_media_selector(programme_id)
416                 return programme_id, title, description, duration, formats, subtitles
417         except ExtractorError as ee:
418             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
419                 raise
420
421         # fallback to legacy playlist
422         return self._process_legacy_playlist(playlist_id)
423
424     def _process_legacy_playlist_url(self, url, display_id):
425         playlist = self._download_legacy_playlist_url(url, display_id)
426         return self._extract_from_legacy_playlist(playlist, display_id)
427
428     def _process_legacy_playlist(self, playlist_id):
429         return self._process_legacy_playlist_url(
430             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
431
432     def _download_legacy_playlist_url(self, url, playlist_id=None):
433         return self._download_xml(
434             url, playlist_id, 'Downloading legacy playlist XML')
435
436     def _extract_from_legacy_playlist(self, playlist, playlist_id):
437         no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
438         if no_items is not None:
439             reason = no_items.get('reason')
440             if reason == 'preAvailability':
441                 msg = 'Episode %s is not yet available' % playlist_id
442             elif reason == 'postAvailability':
443                 msg = 'Episode %s is no longer available' % playlist_id
444             elif reason == 'noMedia':
445                 msg = 'Episode %s is not currently available' % playlist_id
446             else:
447                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
448             raise ExtractorError(msg, expected=True)
449
450         for item in self._extract_items(playlist):
451             kind = item.get('kind')
452             if kind != 'programme' and kind != 'radioProgramme':
453                 continue
454             title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
455             description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
456             description = description_el.text if description_el is not None else None
457
458             def get_programme_id(item):
459                 def get_from_attributes(item):
460                     for p in('identifier', 'group'):
461                         value = item.get(p)
462                         if value and re.match(r'^[pb][\da-z]{7}$', value):
463                             return value
464                 get_from_attributes(item)
465                 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
466                 if mediator is not None:
467                     return get_from_attributes(mediator)
468
469             programme_id = get_programme_id(item)
470             duration = int_or_none(item.get('duration'))
471
472             if programme_id:
473                 formats, subtitles = self._download_media_selector(programme_id)
474             else:
475                 formats, subtitles = self._process_media_selector(item, playlist_id)
476                 programme_id = playlist_id
477
478         return programme_id, title, description, duration, formats, subtitles
479
480     def _real_extract(self, url):
481         group_id = self._match_id(url)
482
483         webpage = self._download_webpage(url, group_id, 'Downloading video page')
484
485         programme_id = None
486         duration = None
487
488         tviplayer = self._search_regex(
489             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
490             webpage, 'player', default=None)
491
492         if tviplayer:
493             player = self._parse_json(tviplayer, group_id).get('player', {})
494             duration = int_or_none(player.get('duration'))
495             programme_id = player.get('vpid')
496
497         if not programme_id:
498             programme_id = self._search_regex(
499                 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
500
501         if programme_id:
502             formats, subtitles = self._download_media_selector(programme_id)
503             title = self._og_search_title(webpage, default=None) or self._html_search_regex(
504                 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
505                  r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
506             description = self._search_regex(
507                 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
508                  r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
509                 webpage, 'description', default=None)
510             if not description:
511                 description = self._html_search_meta('description', webpage)
512         else:
513             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
514
515         self._sort_formats(formats)
516
517         return {
518             'id': programme_id,
519             'title': title,
520             'description': description,
521             'thumbnail': self._og_search_thumbnail(webpage, default=None),
522             'duration': duration,
523             'formats': formats,
524             'subtitles': subtitles,
525         }
526
527
528 class BBCIE(BBCCoUkIE):
529     IE_NAME = 'bbc'
530     IE_DESC = 'BBC'
531     _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
532
533     _MEDIASELECTOR_URLS = [
534         # Provides HQ HLS streams but fails with geolocation in some cases when it's
535         # even not geo restricted at all
536         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
537         # Provides more formats, namely direct mp4 links, but fails on some videos with
538         # notukerror for non UK (?) users (e.g.
539         # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
540         'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
541         # Provides fewer formats, but works everywhere for everybody (hopefully)
542         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
543     ]
544
545     _TESTS = [{
546         # article with multiple videos embedded with data-playable containing vpids
547         'url': 'http://www.bbc.com/news/world-europe-32668511',
548         'info_dict': {
549             'id': 'world-europe-32668511',
550             'title': 'Russia stages massive WW2 parade despite Western boycott',
551             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
552         },
553         'playlist_count': 2,
554     }, {
555         # article with multiple videos embedded with data-playable (more videos)
556         'url': 'http://www.bbc.com/news/business-28299555',
557         'info_dict': {
558             'id': 'business-28299555',
559             'title': 'Farnborough Airshow: Video highlights',
560             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
561         },
562         'playlist_count': 9,
563         'skip': 'Save time',
564     }, {
565         # article with multiple videos embedded with `new SMP()`
566         # broken
567         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
568         'info_dict': {
569             'id': '3662a707-0af9-3149-963f-47bea720b460',
570             'title': 'BUGGER',
571         },
572         'playlist_count': 18,
573     }, {
574         # single video embedded with data-playable containing vpid
575         'url': 'http://www.bbc.com/news/world-europe-32041533',
576         'info_dict': {
577             'id': 'p02mprgb',
578             'ext': 'mp4',
579             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
580             'description': 'md5:2868290467291b37feda7863f7a83f54',
581             'duration': 47,
582             'timestamp': 1427219242,
583             'upload_date': '20150324',
584         },
585         'params': {
586             # rtmp download
587             'skip_download': True,
588         }
589     }, {
590         # article with single video embedded with data-playable containing XML playlist
591         # with direct video links as progressiveDownloadUrl (for now these are extracted)
592         # and playlist with f4m and m3u8 as streamingUrl
593         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
594         'info_dict': {
595             'id': '150615_telabyad_kentin_cogu',
596             'ext': 'mp4',
597             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
598             'timestamp': 1434397334,
599             'upload_date': '20150615',
600         },
601         'params': {
602             'skip_download': True,
603         }
604     }, {
605         # single video embedded with data-playable containing XML playlists (regional section)
606         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
607         'info_dict': {
608             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
609             'ext': 'mp4',
610             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
611             'timestamp': 1434713142,
612             'upload_date': '20150619',
613         },
614         'params': {
615             'skip_download': True,
616         }
617     }, {
618         # single video from video playlist embedded with vxp-playlist-data JSON
619         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
620         'info_dict': {
621             'id': 'p02w6qjc',
622             'ext': 'mp4',
623             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
624             'duration': 56,
625             'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
626         },
627         'params': {
628             'skip_download': True,
629         }
630     }, {
631         # single video story with digitalData
632         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
633         'info_dict': {
634             'id': 'p02q6gc4',
635             'ext': 'flv',
636             'title': 'Sri Lanka’s spicy secret',
637             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
638             'timestamp': 1437674293,
639             'upload_date': '20150723',
640         },
641         'params': {
642             # rtmp download
643             'skip_download': True,
644         }
645     }, {
646         # single video story without digitalData
647         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
648         'info_dict': {
649             'id': 'p018zqqg',
650             'ext': 'mp4',
651             'title': 'Hyundai Santa Fe Sport: Rock star',
652             'description': 'md5:b042a26142c4154a6e472933cf20793d',
653             'timestamp': 1415867444,
654             'upload_date': '20141113',
655         },
656         'params': {
657             # rtmp download
658             'skip_download': True,
659         }
660     }, {
661         # single video with playlist.sxml URL in playlist param
662         'url': 'http://www.bbc.com/sport/0/football/33653409',
663         'info_dict': {
664             'id': 'p02xycnp',
665             'ext': 'mp4',
666             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
667             'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
668             'duration': 140,
669         },
670         'params': {
671             # rtmp download
672             'skip_download': True,
673         }
674     }, {
675         # article with multiple videos embedded with playlist.sxml in playlist param
676         'url': 'http://www.bbc.com/sport/0/football/34475836',
677         'info_dict': {
678             'id': '34475836',
679             'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
680             'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
681         },
682         'playlist_count': 3,
683     }, {
684         # school report article with single video
685         'url': 'http://www.bbc.co.uk/schoolreport/35744779',
686         'info_dict': {
687             'id': '35744779',
688             'title': 'School which breaks down barriers in Jerusalem',
689         },
690         'playlist_count': 1,
691     }, {
692         # single video with playlist URL from weather section
693         'url': 'http://www.bbc.com/weather/features/33601775',
694         'only_matching': True,
695     }, {
696         # custom redirection to www.bbc.com
697         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
698         'only_matching': True,
699     }, {
700         # single video article embedded with data-media-vpid
701         'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
702         'only_matching': True,
703     }]
704
705     @classmethod
706     def suitable(cls, url):
707         EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
708         return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
709                 else super(BBCIE, cls).suitable(url))
710
711     def _extract_from_media_meta(self, media_meta, video_id):
712         # Direct links to media in media metadata (e.g.
713         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
714         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
715         source_files = media_meta.get('sourceFiles')
716         if source_files:
717             return [{
718                 'url': f['url'],
719                 'format_id': format_id,
720                 'ext': f.get('encoding'),
721                 'tbr': float_or_none(f.get('bitrate'), 1000),
722                 'filesize': int_or_none(f.get('filesize')),
723             } for format_id, f in source_files.items() if f.get('url')], []
724
725         programme_id = media_meta.get('externalId')
726         if programme_id:
727             return self._download_media_selector(programme_id)
728
729         # Process playlist.sxml as legacy playlist
730         href = media_meta.get('href')
731         if href:
732             playlist = self._download_legacy_playlist_url(href)
733             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
734             return formats, subtitles
735
736         return [], []
737
738     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
739         programme_id, title, description, duration, formats, subtitles = \
740             self._process_legacy_playlist_url(url, playlist_id)
741         self._sort_formats(formats)
742         return {
743             'id': programme_id,
744             'title': title,
745             'description': description,
746             'duration': duration,
747             'timestamp': timestamp,
748             'formats': formats,
749             'subtitles': subtitles,
750         }
751
752     def _real_extract(self, url):
753         playlist_id = self._match_id(url)
754
755         webpage = self._download_webpage(url, playlist_id)
756
757         json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
758         timestamp = json_ld_info.get('timestamp')
759
760         playlist_title = json_ld_info.get('title')
761         if not playlist_title:
762             playlist_title = self._og_search_title(
763                 webpage, default=None) or self._html_search_regex(
764                 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
765             if playlist_title:
766                 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
767
768         playlist_description = json_ld_info.get(
769             'description') or self._og_search_description(webpage, default=None)
770
771         if not timestamp:
772             timestamp = parse_iso8601(self._search_regex(
773                 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
774                  r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
775                  r'"datePublished":\s*"([^"]+)'],
776                 webpage, 'date', default=None))
777
778         entries = []
779
780         # article with multiple videos embedded with playlist.sxml (e.g.
781         # http://www.bbc.com/sport/0/football/34475836)
782         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
783         playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
784         if playlists:
785             entries = [
786                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
787                 for playlist_url in playlists]
788
789         # news article with multiple videos embedded with data-playable
790         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
791         if data_playables:
792             for _, data_playable_json in data_playables:
793                 data_playable = self._parse_json(
794                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
795                 if not data_playable:
796                     continue
797                 settings = data_playable.get('settings', {})
798                 if settings:
799                     # data-playable with video vpid in settings.playlistObject.items (e.g.
800                     # http://www.bbc.com/news/world-us-canada-34473351)
801                     playlist_object = settings.get('playlistObject', {})
802                     if playlist_object:
803                         items = playlist_object.get('items')
804                         if items and isinstance(items, list):
805                             title = playlist_object['title']
806                             description = playlist_object.get('summary')
807                             duration = int_or_none(items[0].get('duration'))
808                             programme_id = items[0].get('vpid')
809                             formats, subtitles = self._download_media_selector(programme_id)
810                             self._sort_formats(formats)
811                             entries.append({
812                                 'id': programme_id,
813                                 'title': title,
814                                 'description': description,
815                                 'timestamp': timestamp,
816                                 'duration': duration,
817                                 'formats': formats,
818                                 'subtitles': subtitles,
819                             })
820                     else:
821                         # data-playable without vpid but with a playlist.sxml URLs
822                         # in otherSettings.playlist (e.g.
823                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
824                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
825                         if playlist:
826                             entries.append(self._extract_from_playlist_sxml(
827                                 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
828
829         if entries:
830             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
831
832         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
833         programme_id = self._search_regex(
834             [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
835              r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
836              r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
837             webpage, 'vpid', default=None)
838
839         if programme_id:
840             formats, subtitles = self._download_media_selector(programme_id)
841             self._sort_formats(formats)
842             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
843             digital_data = self._parse_json(
844                 self._search_regex(
845                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
846                 programme_id, fatal=False)
847             page_info = digital_data.get('page', {}).get('pageInfo', {})
848             title = page_info.get('pageName') or self._og_search_title(webpage)
849             description = page_info.get('description') or self._og_search_description(webpage)
850             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
851             return {
852                 'id': programme_id,
853                 'title': title,
854                 'description': description,
855                 'timestamp': timestamp,
856                 'formats': formats,
857                 'subtitles': subtitles,
858             }
859
860         def extract_all(pattern):
861             return list(filter(None, map(
862                 lambda s: self._parse_json(s, playlist_id, fatal=False),
863                 re.findall(pattern, webpage))))
864
865         # Multiple video article (e.g.
866         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
867         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
868         entries = []
869         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
870             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
871             if embed_url and re.match(EMBED_URL, embed_url):
872                 entries.append(embed_url)
873         entries.extend(re.findall(
874             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
875         if entries:
876             return self.playlist_result(
877                 [self.url_result(entry, 'BBCCoUk') for entry in entries],
878                 playlist_id, playlist_title, playlist_description)
879
880         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
881         medias = extract_all(r"data-media-meta='({[^']+})'")
882
883         if not medias:
884             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
885             media_asset = self._search_regex(
886                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
887                 webpage, 'media asset', default=None)
888             if media_asset:
889                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
890                 medias = []
891                 for video in media_asset_page.get('videos', {}).values():
892                     medias.extend(video.values())
893
894         if not medias:
895             # Multiple video playlist with single `now playing` entry (e.g.
896             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
897             vxp_playlist = self._parse_json(
898                 self._search_regex(
899                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
900                     webpage, 'playlist data'),
901                 playlist_id)
902             playlist_medias = []
903             for item in vxp_playlist:
904                 media = item.get('media')
905                 if not media:
906                     continue
907                 playlist_medias.append(media)
908                 # Download single video if found media with asset id matching the video id from URL
909                 if item.get('advert', {}).get('assetId') == playlist_id:
910                     medias = [media]
911                     break
912             # Fallback to the whole playlist
913             if not medias:
914                 medias = playlist_medias
915
916         entries = []
917         for num, media_meta in enumerate(medias, start=1):
918             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
919             if not formats:
920                 continue
921             self._sort_formats(formats)
922
923             video_id = media_meta.get('externalId')
924             if not video_id:
925                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
926
927             title = media_meta.get('caption')
928             if not title:
929                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
930
931             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
932
933             images = []
934             for image in media_meta.get('images', {}).values():
935                 images.extend(image.values())
936             if 'image' in media_meta:
937                 images.append(media_meta['image'])
938
939             thumbnails = [{
940                 'url': image.get('href'),
941                 'width': int_or_none(image.get('width')),
942                 'height': int_or_none(image.get('height')),
943             } for image in images]
944
945             entries.append({
946                 'id': video_id,
947                 'title': title,
948                 'thumbnails': thumbnails,
949                 'duration': duration,
950                 'timestamp': timestamp,
951                 'formats': formats,
952                 'subtitles': subtitles,
953             })
954
955         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
956
957
958 class BBCCoUkArticleIE(InfoExtractor):
959     _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
960     IE_NAME = 'bbc.co.uk:article'
961     IE_DESC = 'BBC articles'
962
963     _TEST = {
964         'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
965         'info_dict': {
966             'id': '3jNQLTMrPlYGTBn0WV6M2MS',
967             'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
968             'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
969         },
970         'playlist_count': 4,
971         'add_ie': ['BBCCoUk'],
972     }
973
974     def _real_extract(self, url):
975         playlist_id = self._match_id(url)
976
977         webpage = self._download_webpage(url, playlist_id)
978
979         title = self._og_search_title(webpage)
980         description = self._og_search_description(webpage).strip()
981
982         entries = [self.url_result(programme_url) for programme_url in re.findall(
983             r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
984
985         return self.playlist_result(entries, playlist_id, title, description)
986
987
988 class BBCCoUkPlaylistBaseIE(InfoExtractor):
989     def _real_extract(self, url):
990         playlist_id = self._match_id(url)
991
992         webpage = self._download_webpage(url, playlist_id)
993
994         entries = [
995             self.url_result(self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
996             for video_id in re.findall(
997                 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage)]
998
999         title, description = self._extract_title_and_description(webpage)
1000
1001         return self.playlist_result(entries, playlist_id, title, description)
1002
1003
1004 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1005     IE_NAME = 'bbc.co.uk:iplayer:playlist'
1006     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/episodes/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1007     _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1008     _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1009     _TEST = {
1010         'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1011         'info_dict': {
1012             'id': 'b05rcz9v',
1013             'title': 'The Disappearance',
1014             'description': 'French thriller serial about a missing teenager.',
1015         },
1016         'playlist_mincount': 6,
1017     }
1018
1019     def _extract_title_and_description(self, webpage):
1020         title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1021         description = self._search_regex(
1022             r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1023             webpage, 'description', fatal=False, group='value')
1024         return title, description
1025
1026
1027 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1028     IE_NAME = 'bbc.co.uk:playlist'
1029     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1030     _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1031     _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1032     _TESTS = [{
1033         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1034         'info_dict': {
1035             'id': 'b05rcz9v',
1036             'title': 'The Disappearance - Clips - BBC Four',
1037             'description': 'French thriller serial about a missing teenager.',
1038         },
1039         'playlist_mincount': 7,
1040     }, {
1041         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1042         'only_matching': True,
1043     }, {
1044         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1045         'only_matching': True,
1046     }, {
1047         'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1048         'only_matching': True,
1049     }]
1050
1051     def _extract_title_and_description(self, webpage):
1052         title = self._og_search_title(webpage, fatal=False)
1053         description = self._og_search_description(webpage)
1054         return title, description