[bbc] Clarify iptv-all mediaset rationale
[youtube-dl] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import xml.etree.ElementTree
6
7 from .common import InfoExtractor
8 from ..utils import (
9     ExtractorError,
10     float_or_none,
11     int_or_none,
12     parse_duration,
13     parse_iso8601,
14 )
15 from ..compat import compat_HTTPError
16
17
18 class BBCCoUkIE(InfoExtractor):
19     IE_NAME = 'bbc.co.uk'
20     IE_DESC = 'BBC iPlayer'
21     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
22
23     _MEDIASELECTOR_URLS = [
24         # Provides HQ HLS streams with even better quality that pc mediaset but fails
25         # with geolocation in some cases when it's even not geo restricted at all (e.g.
26         # http://www.bbc.co.uk/programmes/b06bp7lf)
27         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
28         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
29     ]
30
31     _TESTS = [
32         {
33             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
34             'info_dict': {
35                 'id': 'b039d07m',
36                 'ext': 'flv',
37                 'title': 'Kaleidoscope, Leonard Cohen',
38                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
39                 'duration': 1740,
40             },
41             'params': {
42                 # rtmp download
43                 'skip_download': True,
44             }
45         },
46         {
47             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
48             'info_dict': {
49                 'id': 'b00yng1d',
50                 'ext': 'flv',
51                 'title': 'The Man in Black: Series 3: The Printed Name',
52                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
53                 'duration': 1800,
54             },
55             'params': {
56                 # rtmp download
57                 'skip_download': True,
58             },
59             'skip': 'Episode is no longer available on BBC iPlayer Radio',
60         },
61         {
62             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
63             'info_dict': {
64                 'id': 'b00yng1d',
65                 'ext': 'flv',
66                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
67                 '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.",
68                 'duration': 5100,
69             },
70             'params': {
71                 # rtmp download
72                 'skip_download': True,
73             },
74             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
75         },
76         {
77             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
78             'info_dict': {
79                 'id': 'b03k3pb7',
80                 'ext': 'flv',
81                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
82                 'description': '2. Invasion',
83                 'duration': 3600,
84             },
85             'params': {
86                 # rtmp download
87                 'skip_download': True,
88             },
89             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
90         }, {
91             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
92             'info_dict': {
93                 'id': 'b04v209v',
94                 'ext': 'flv',
95                 'title': 'Pete Tong, The Essential New Tune Special',
96                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
97                 'duration': 10800,
98             },
99             'params': {
100                 # rtmp download
101                 'skip_download': True,
102             }
103         }, {
104             'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
105             'note': 'Audio',
106             'info_dict': {
107                 'id': 'p02frcch',
108                 'ext': 'flv',
109                 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
110                 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
111                 'duration': 3507,
112             },
113             'params': {
114                 # rtmp download
115                 'skip_download': True,
116             }
117         }, {
118             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
119             'note': 'Video',
120             'info_dict': {
121                 'id': 'p025c103',
122                 'ext': 'flv',
123                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
124                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
125                 'duration': 226,
126             },
127             'params': {
128                 # rtmp download
129                 'skip_download': True,
130             }
131         }, {
132             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
133             'info_dict': {
134                 'id': 'p02n76xf',
135                 'ext': 'flv',
136                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
137                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
138                 'duration': 3540,
139             },
140             'params': {
141                 # rtmp download
142                 'skip_download': True,
143             },
144             'skip': 'geolocation',
145         }, {
146             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
147             'info_dict': {
148                 'id': 'b05zmgw1',
149                 'ext': 'flv',
150                 '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.',
151                 'title': 'Royal Academy Summer Exhibition',
152                 'duration': 3540,
153             },
154             'params': {
155                 # rtmp download
156                 'skip_download': True,
157             },
158             'skip': 'geolocation',
159         }, {
160             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
161             'only_matching': True,
162         }, {
163             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
164             'only_matching': True,
165         }, {
166             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
167             'only_matching': True,
168         }
169     ]
170
171     class MediaSelectionError(Exception):
172         def __init__(self, id):
173             self.id = id
174
175     def _extract_asx_playlist(self, connection, programme_id):
176         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
177         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
178
179     def _extract_connection(self, connection, programme_id):
180         formats = []
181         protocol = connection.get('protocol')
182         supplier = connection.get('supplier')
183         if protocol == 'http':
184             href = connection.get('href')
185             transfer_format = connection.get('transferFormat')
186             # ASX playlist
187             if supplier == 'asx':
188                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
189                     formats.append({
190                         'url': ref,
191                         'format_id': 'ref%s_%s' % (i, supplier),
192                     })
193             # Skip DASH until supported
194             elif transfer_format == 'dash':
195                 pass
196             elif transfer_format == 'hls':
197                 m3u8_formats = self._extract_m3u8_formats(
198                     href, programme_id, ext='mp4', entry_protocol='m3u8_native',
199                     m3u8_id=supplier, fatal=False)
200                 if m3u8_formats:
201                     formats.extend(m3u8_formats)
202             # Direct link
203             else:
204                 formats.append({
205                     'url': href,
206                     'format_id': supplier,
207                 })
208         elif protocol == 'rtmp':
209             application = connection.get('application', 'ondemand')
210             auth_string = connection.get('authString')
211             identifier = connection.get('identifier')
212             server = connection.get('server')
213             formats.append({
214                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
215                 'play_path': identifier,
216                 'app': '%s?%s' % (application, auth_string),
217                 'page_url': 'http://www.bbc.co.uk',
218                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
219                 'rtmp_live': False,
220                 'ext': 'flv',
221                 'format_id': supplier,
222             })
223         return formats
224
225     def _extract_items(self, playlist):
226         return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
227
228     def _extract_medias(self, media_selection):
229         error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
230         if error is not None:
231             raise BBCCoUkIE.MediaSelectionError(error.get('id'))
232         return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
233
234     def _extract_connections(self, media):
235         return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
236
237     def _extract_video(self, media, programme_id):
238         formats = []
239         vbr = int_or_none(media.get('bitrate'))
240         vcodec = media.get('encoding')
241         service = media.get('service')
242         width = int_or_none(media.get('width'))
243         height = int_or_none(media.get('height'))
244         file_size = int_or_none(media.get('media_file_size'))
245         for connection in self._extract_connections(media):
246             conn_formats = self._extract_connection(connection, programme_id)
247             for format in conn_formats:
248                 format.update({
249                     'format_id': '%s_%s' % (service, format['format_id']),
250                     'width': width,
251                     'height': height,
252                     'vbr': vbr,
253                     'vcodec': vcodec,
254                     'filesize': file_size,
255                 })
256             formats.extend(conn_formats)
257         return formats
258
259     def _extract_audio(self, media, programme_id):
260         formats = []
261         abr = int_or_none(media.get('bitrate'))
262         acodec = media.get('encoding')
263         service = media.get('service')
264         for connection in self._extract_connections(media):
265             conn_formats = self._extract_connection(connection, programme_id)
266             for format in conn_formats:
267                 format.update({
268                     'format_id': '%s_%s' % (service, format['format_id']),
269                     'abr': abr,
270                     'acodec': acodec,
271                 })
272             formats.extend(conn_formats)
273         return formats
274
275     def _get_subtitles(self, media, programme_id):
276         subtitles = {}
277         for connection in self._extract_connections(media):
278             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
279             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
280             subtitles[lang] = [
281                 {
282                     'url': connection.get('href'),
283                     'ext': 'ttml',
284                 },
285             ]
286         return subtitles
287
288     def _raise_extractor_error(self, media_selection_error):
289         raise ExtractorError(
290             '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
291             expected=True)
292
293     def _download_media_selector(self, programme_id):
294         last_exception = None
295         for mediaselector_url in self._MEDIASELECTOR_URLS:
296             try:
297                 return self._download_media_selector_url(
298                     mediaselector_url % programme_id, programme_id)
299             except BBCCoUkIE.MediaSelectionError as e:
300                 if e.id in ('notukerror', 'geolocation'):
301                     last_exception = e
302                     continue
303                 self._raise_extractor_error(e)
304         self._raise_extractor_error(last_exception)
305
306     def _download_media_selector_url(self, url, programme_id=None):
307         try:
308             media_selection = self._download_xml(
309                 url, programme_id, 'Downloading media selection XML')
310         except ExtractorError as ee:
311             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
312                 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
313             else:
314                 raise
315         return self._process_media_selector(media_selection, programme_id)
316
317     def _process_media_selector(self, media_selection, programme_id):
318         formats = []
319         subtitles = None
320
321         for media in self._extract_medias(media_selection):
322             kind = media.get('kind')
323             if kind == 'audio':
324                 formats.extend(self._extract_audio(media, programme_id))
325             elif kind == 'video':
326                 formats.extend(self._extract_video(media, programme_id))
327             elif kind == 'captions':
328                 subtitles = self.extract_subtitles(media, programme_id)
329         return formats, subtitles
330
331     def _download_playlist(self, playlist_id):
332         try:
333             playlist = self._download_json(
334                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
335                 playlist_id, 'Downloading playlist JSON')
336
337             version = playlist.get('defaultAvailableVersion')
338             if version:
339                 smp_config = version['smpConfig']
340                 title = smp_config['title']
341                 description = smp_config['summary']
342                 for item in smp_config['items']:
343                     kind = item['kind']
344                     if kind != 'programme' and kind != 'radioProgramme':
345                         continue
346                     programme_id = item.get('vpid')
347                     duration = int_or_none(item.get('duration'))
348                     formats, subtitles = self._download_media_selector(programme_id)
349                 return programme_id, title, description, duration, formats, subtitles
350         except ExtractorError as ee:
351             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
352                 raise
353
354         # fallback to legacy playlist
355         return self._process_legacy_playlist(playlist_id)
356
357     def _process_legacy_playlist_url(self, url, display_id):
358         playlist = self._download_legacy_playlist_url(url, display_id)
359         return self._extract_from_legacy_playlist(playlist, display_id)
360
361     def _process_legacy_playlist(self, playlist_id):
362         return self._process_legacy_playlist_url(
363             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
364
365     def _download_legacy_playlist_url(self, url, playlist_id=None):
366         return self._download_xml(
367             url, playlist_id, 'Downloading legacy playlist XML')
368
369     def _extract_from_legacy_playlist(self, playlist, playlist_id):
370         no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
371         if no_items is not None:
372             reason = no_items.get('reason')
373             if reason == 'preAvailability':
374                 msg = 'Episode %s is not yet available' % playlist_id
375             elif reason == 'postAvailability':
376                 msg = 'Episode %s is no longer available' % playlist_id
377             elif reason == 'noMedia':
378                 msg = 'Episode %s is not currently available' % playlist_id
379             else:
380                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
381             raise ExtractorError(msg, expected=True)
382
383         for item in self._extract_items(playlist):
384             kind = item.get('kind')
385             if kind != 'programme' and kind != 'radioProgramme':
386                 continue
387             title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
388             description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
389
390             def get_programme_id(item):
391                 def get_from_attributes(item):
392                     for p in('identifier', 'group'):
393                         value = item.get(p)
394                         if value and re.match(r'^[pb][\da-z]{7}$', value):
395                             return value
396                 get_from_attributes(item)
397                 mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
398                 if mediator is not None:
399                     return get_from_attributes(mediator)
400
401             programme_id = get_programme_id(item)
402             duration = int_or_none(item.get('duration'))
403             # TODO: programme_id can be None and media items can be incorporated right inside
404             # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
405             # as f4m and m3u8
406             formats, subtitles = self._download_media_selector(programme_id)
407
408         return programme_id, title, description, duration, formats, subtitles
409
410     def _real_extract(self, url):
411         group_id = self._match_id(url)
412
413         webpage = self._download_webpage(url, group_id, 'Downloading video page')
414
415         programme_id = None
416
417         tviplayer = self._search_regex(
418             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
419             webpage, 'player', default=None)
420
421         if tviplayer:
422             player = self._parse_json(tviplayer, group_id).get('player', {})
423             duration = int_or_none(player.get('duration'))
424             programme_id = player.get('vpid')
425
426         if not programme_id:
427             programme_id = self._search_regex(
428                 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
429
430         if programme_id:
431             formats, subtitles = self._download_media_selector(programme_id)
432             title = self._og_search_title(webpage)
433             description = self._search_regex(
434                 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
435                 webpage, 'description', fatal=False)
436         else:
437             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
438
439         self._sort_formats(formats)
440
441         return {
442             'id': programme_id,
443             'title': title,
444             'description': description,
445             'thumbnail': self._og_search_thumbnail(webpage, default=None),
446             'duration': duration,
447             'formats': formats,
448             'subtitles': subtitles,
449         }
450
451
452 class BBCIE(BBCCoUkIE):
453     IE_NAME = 'bbc'
454     IE_DESC = 'BBC'
455     _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
456
457     _MEDIASELECTOR_URLS = [
458         # Provides more formats, namely direct mp4 links, but fails on some videos with
459         # notukerror for non UK (?) users (e.g.
460         # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
461         'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
462         # Provides fewer formats, but works everywhere for everybody (hopefully)
463         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
464     ]
465
466     _TESTS = [{
467         # article with multiple videos embedded with data-media-meta containing
468         # playlist.sxml, externalId and no direct video links
469         'url': 'http://www.bbc.com/news/world-europe-32668511',
470         'info_dict': {
471             'id': 'world-europe-32668511',
472             'title': 'Russia stages massive WW2 parade despite Western boycott',
473             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
474         },
475         'playlist_count': 2,
476     }, {
477         # article with multiple videos embedded with data-media-meta (more videos)
478         'url': 'http://www.bbc.com/news/business-28299555',
479         'info_dict': {
480             'id': 'business-28299555',
481             'title': 'Farnborough Airshow: Video highlights',
482             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
483         },
484         'playlist_count': 9,
485         'skip': 'Save time',
486     }, {
487         # article with multiple videos embedded with `new SMP()`
488         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
489         'info_dict': {
490             'id': '3662a707-0af9-3149-963f-47bea720b460',
491             'title': 'BBC Blogs - Adam Curtis - BUGGER',
492         },
493         'playlist_count': 18,
494     }, {
495         # single video embedded with mediaAssetPage.init()
496         'url': 'http://www.bbc.com/news/world-europe-32041533',
497         'info_dict': {
498             'id': 'p02mprgb',
499             'ext': 'mp4',
500             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
501             'duration': 47,
502             'timestamp': 1427219242,
503             'upload_date': '20150324',
504         },
505         'params': {
506             # rtmp download
507             'skip_download': True,
508         }
509     }, {
510         # article with single video embedded with data-media-meta containing
511         # direct video links (for now these are extracted) and playlist.xml (with
512         # media items as f4m and m3u8 - currently unsupported)
513         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
514         'info_dict': {
515             'id': '150615_telabyad_kentin_cogu',
516             'ext': 'mp4',
517             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
518             'duration': 47,
519             'timestamp': 1434397334,
520             'upload_date': '20150615',
521         },
522         'params': {
523             'skip_download': True,
524         }
525     }, {
526         # single video embedded with mediaAssetPage.init() (regional section)
527         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
528         'info_dict': {
529             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
530             'ext': 'mp4',
531             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
532             'duration': 87,
533             'timestamp': 1434713142,
534             'upload_date': '20150619',
535         },
536         'params': {
537             'skip_download': True,
538         }
539     }, {
540         # single video from video playlist embedded with vxp-playlist-data JSON
541         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
542         'info_dict': {
543             'id': 'p02w6qjc',
544             'ext': 'mp4',
545             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
546             'duration': 56,
547         },
548         'params': {
549             'skip_download': True,
550         }
551     }, {
552         # single video story with digitalData
553         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
554         'info_dict': {
555             'id': 'p02q6gc4',
556             'ext': 'flv',
557             'title': 'Sri Lanka’s spicy secret',
558             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
559             'timestamp': 1437674293,
560             'upload_date': '20150723',
561         },
562         'params': {
563             # rtmp download
564             'skip_download': True,
565         }
566     }, {
567         # single video story without digitalData
568         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
569         'info_dict': {
570             'id': 'p018zqqg',
571             'ext': 'mp4',
572             'title': 'Hyundai Santa Fe Sport: Rock star',
573             'description': 'md5:b042a26142c4154a6e472933cf20793d',
574             'timestamp': 1368473503,
575             'upload_date': '20130513',
576         },
577         'params': {
578             # rtmp download
579             'skip_download': True,
580         }
581     }, {
582         # single video with playlist.sxml URL
583         'url': 'http://www.bbc.com/sport/0/football/33653409',
584         'info_dict': {
585             'id': 'p02xycnp',
586             'ext': 'mp4',
587             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
588             'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
589             'duration': 140,
590         },
591         'params': {
592             # rtmp download
593             'skip_download': True,
594         }
595     }, {
596         # single video with playlist URL from weather section
597         'url': 'http://www.bbc.com/weather/features/33601775',
598         'only_matching': True,
599     }, {
600         # custom redirection to www.bbc.com
601         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
602         'only_matching': True,
603     }]
604
605     @classmethod
606     def suitable(cls, url):
607         return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
608
609     def _extract_from_media_meta(self, media_meta, video_id):
610         # Direct links to media in media metadata (e.g.
611         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
612         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
613         source_files = media_meta.get('sourceFiles')
614         if source_files:
615             return [{
616                 'url': f['url'],
617                 'format_id': format_id,
618                 'ext': f.get('encoding'),
619                 'tbr': float_or_none(f.get('bitrate'), 1000),
620                 'filesize': int_or_none(f.get('filesize')),
621             } for format_id, f in source_files.items() if f.get('url')], []
622
623         programme_id = media_meta.get('externalId')
624         if programme_id:
625             return self._download_media_selector(programme_id)
626
627         # Process playlist.sxml as legacy playlist
628         href = media_meta.get('href')
629         if href:
630             playlist = self._download_legacy_playlist_url(href)
631             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
632             return formats, subtitles
633
634         return [], []
635
636     def _real_extract(self, url):
637         playlist_id = self._match_id(url)
638
639         webpage = self._download_webpage(url, playlist_id)
640
641         timestamp = parse_iso8601(self._search_regex(
642             [r'"datePublished":\s*"([^"]+)',
643              r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
644              r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
645             webpage, 'date', default=None))
646
647         # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
648         playlist = self._search_regex(
649             r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
650             webpage, 'playlist', default=None)
651         if playlist:
652             programme_id, title, description, duration, formats, subtitles = \
653                 self._process_legacy_playlist_url(playlist, playlist_id)
654             self._sort_formats(formats)
655             return {
656                 'id': programme_id,
657                 'title': title,
658                 'description': description,
659                 'duration': duration,
660                 'timestamp': timestamp,
661                 'formats': formats,
662                 'subtitles': subtitles,
663             }
664
665         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
666         programme_id = self._search_regex(
667             [r'data-video-player-vpid="([\da-z]{8})"',
668              r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
669             webpage, 'vpid', default=None)
670         if programme_id:
671             formats, subtitles = self._download_media_selector(programme_id)
672             self._sort_formats(formats)
673             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
674             digital_data = self._parse_json(
675                 self._search_regex(
676                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
677                 programme_id, fatal=False)
678             page_info = digital_data.get('page', {}).get('pageInfo', {})
679             title = page_info.get('pageName') or self._og_search_title(webpage)
680             description = page_info.get('description') or self._og_search_description(webpage)
681             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
682             return {
683                 'id': programme_id,
684                 'title': title,
685                 'description': description,
686                 'timestamp': timestamp,
687                 'formats': formats,
688                 'subtitles': subtitles,
689             }
690
691         playlist_title = self._html_search_regex(
692             r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
693         playlist_description = self._og_search_description(webpage, default=None)
694
695         def extract_all(pattern):
696             return list(filter(None, map(
697                 lambda s: self._parse_json(s, playlist_id, fatal=False),
698                 re.findall(pattern, webpage))))
699
700         # Multiple video article (e.g.
701         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
702         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
703         entries = []
704         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
705             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
706             if embed_url and re.match(EMBED_URL, embed_url):
707                 entries.append(embed_url)
708         entries.extend(re.findall(
709             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
710         if entries:
711             return self.playlist_result(
712                 [self.url_result(entry, 'BBCCoUk') for entry in entries],
713                 playlist_id, playlist_title, playlist_description)
714
715         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
716         medias = extract_all(r"data-media-meta='({[^']+})'")
717
718         if not medias:
719             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
720             media_asset = self._search_regex(
721                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
722                 webpage, 'media asset', default=None)
723             if media_asset:
724                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
725                 medias = []
726                 for video in media_asset_page.get('videos', {}).values():
727                     medias.extend(video.values())
728
729         if not medias:
730             # Multiple video playlist with single `now playing` entry (e.g.
731             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
732             vxp_playlist = self._parse_json(
733                 self._search_regex(
734                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
735                     webpage, 'playlist data'),
736                 playlist_id)
737             playlist_medias = []
738             for item in vxp_playlist:
739                 media = item.get('media')
740                 if not media:
741                     continue
742                 playlist_medias.append(media)
743                 # Download single video if found media with asset id matching the video id from URL
744                 if item.get('advert', {}).get('assetId') == playlist_id:
745                     medias = [media]
746                     break
747             # Fallback to the whole playlist
748             if not medias:
749                 medias = playlist_medias
750
751         entries = []
752         for num, media_meta in enumerate(medias, start=1):
753             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
754             if not formats:
755                 continue
756             self._sort_formats(formats)
757
758             video_id = media_meta.get('externalId')
759             if not video_id:
760                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
761
762             title = media_meta.get('caption')
763             if not title:
764                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
765
766             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
767
768             images = []
769             for image in media_meta.get('images', {}).values():
770                 images.extend(image.values())
771             if 'image' in media_meta:
772                 images.append(media_meta['image'])
773
774             thumbnails = [{
775                 'url': image.get('href'),
776                 'width': int_or_none(image.get('width')),
777                 'height': int_or_none(image.get('height')),
778             } for image in images]
779
780             entries.append({
781                 'id': video_id,
782                 'title': title,
783                 'thumbnails': thumbnails,
784                 'duration': duration,
785                 'timestamp': timestamp,
786                 'formats': formats,
787                 'subtitles': subtitles,
788             })
789
790         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)