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