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