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