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