[bbc] Remove duration
[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-media-meta containing
505         # playlist.sxml, externalId and no direct video links
506         'url': 'http://www.bbc.com/news/world-europe-32668511',
507         'info_dict': {
508             'id': 'world-europe-32668511',
509             'title': 'Russia stages massive WW2 parade despite Western boycott',
510             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
511         },
512         'playlist_count': 2,
513     }, {
514         # article with multiple videos embedded with data-media-meta (more videos)
515         'url': 'http://www.bbc.com/news/business-28299555',
516         'info_dict': {
517             'id': 'business-28299555',
518             'title': 'Farnborough Airshow: Video highlights',
519             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
520         },
521         'playlist_count': 9,
522         'skip': 'Save time',
523     }, {
524         # article with multiple videos embedded with `new SMP()`
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 mediaAssetPage.init()
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-media-meta containing
548         # direct video links (for now these are extracted) and playlist.xml (with
549         # media items as f4m and m3u8 - currently unsupported)
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 playlist.sxml in data-playable
564         'url': 'http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani',
565         'info_dict': {
566             'id': '151010_vid_ankara_patlama_ani',
567             'ext': 'mp4',
568             'title': "Ankara'da patlama anı",
569             'timestamp': 1444480325,
570             'upload_date': '20151010',
571         },
572         'params': {
573             'skip_download': True,
574         }
575     }, {
576         # single video embedded with mediaAssetPage.init() (regional section)
577         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
578         'info_dict': {
579             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
580             'ext': 'mp4',
581             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
582             'duration': 87,
583             'timestamp': 1434713142,
584             'upload_date': '20150619',
585         },
586         'params': {
587             'skip_download': True,
588         }
589     }, {
590         # single video from video playlist embedded with vxp-playlist-data JSON
591         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
592         'info_dict': {
593             'id': 'p02w6qjc',
594             'ext': 'mp4',
595             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
596             'duration': 56,
597         },
598         'params': {
599             'skip_download': True,
600         }
601     }, {
602         # single video story with digitalData
603         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
604         'info_dict': {
605             'id': 'p02q6gc4',
606             'ext': 'flv',
607             'title': 'Sri Lanka’s spicy secret',
608             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
609             'timestamp': 1437674293,
610             'upload_date': '20150723',
611         },
612         'params': {
613             # rtmp download
614             'skip_download': True,
615         }
616     }, {
617         # single video story without digitalData
618         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
619         'info_dict': {
620             'id': 'p018zqqg',
621             'ext': 'mp4',
622             'title': 'Hyundai Santa Fe Sport: Rock star',
623             'description': 'md5:b042a26142c4154a6e472933cf20793d',
624             'timestamp': 1368473503,
625             'upload_date': '20130513',
626         },
627         'params': {
628             # rtmp download
629             'skip_download': True,
630         }
631     }, {
632         # single video with playlist.sxml URL
633         'url': 'http://www.bbc.com/sport/0/football/33653409',
634         'info_dict': {
635             'id': 'p02xycnp',
636             'ext': 'mp4',
637             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
638             'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
639             'duration': 140,
640         },
641         'params': {
642             # rtmp download
643             'skip_download': True,
644         }
645     }, {
646         # article with multiple videos embedded with playlist.sxml
647         'url': 'http://www.bbc.com/sport/0/football/34475836',
648         'info_dict': {
649             'id': '34475836',
650             'title': 'What Liverpool can expect from Klopp',
651         },
652         'playlist_count': 3,
653     }, {
654         # single video with playlist URL from weather section
655         'url': 'http://www.bbc.com/weather/features/33601775',
656         'only_matching': True,
657     }, {
658         # custom redirection to www.bbc.com
659         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
660         'only_matching': True,
661     }]
662
663     @classmethod
664     def suitable(cls, url):
665         return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
666
667     def _extract_from_media_meta(self, media_meta, video_id):
668         # Direct links to media in media metadata (e.g.
669         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
670         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
671         source_files = media_meta.get('sourceFiles')
672         if source_files:
673             return [{
674                 'url': f['url'],
675                 'format_id': format_id,
676                 'ext': f.get('encoding'),
677                 'tbr': float_or_none(f.get('bitrate'), 1000),
678                 'filesize': int_or_none(f.get('filesize')),
679             } for format_id, f in source_files.items() if f.get('url')], []
680
681         programme_id = media_meta.get('externalId')
682         if programme_id:
683             return self._download_media_selector(programme_id)
684
685         # Process playlist.sxml as legacy playlist
686         href = media_meta.get('href')
687         if href:
688             playlist = self._download_legacy_playlist_url(href)
689             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
690             return formats, subtitles
691
692         return [], []
693
694     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
695         programme_id, title, description, duration, formats, subtitles = \
696             self._process_legacy_playlist_url(url, playlist_id)
697         self._sort_formats(formats)
698         return {
699             'id': programme_id,
700             'title': title,
701             'description': description,
702             'duration': duration,
703             'timestamp': timestamp,
704             'formats': formats,
705             'subtitles': subtitles,
706         }
707
708     def _real_extract(self, url):
709         playlist_id = self._match_id(url)
710
711         webpage = self._download_webpage(url, playlist_id)
712
713         timestamp = parse_iso8601(self._search_regex(
714             [r'"datePublished":\s*"([^"]+)',
715              r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
716              r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
717             webpage, 'date', default=None))
718
719         entries = []
720
721         # article with multiple videos embedded with playlist.sxml (e.g.
722         # http://www.bbc.com/sport/0/football/34475836)
723         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
724         if playlists:
725             entries = [
726                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
727                 for playlist_url in playlists]
728
729         # news article with multiple videos embedded with data-playable
730         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
731         if data_playables:
732             for _, data_playable_json in data_playables:
733                 data_playable = self._parse_json(
734                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
735                 if not data_playable:
736                     continue
737                 settings = data_playable.get('settings', {})
738                 if settings:
739                     # data-playable with video vpid in settings.playlistObject.items (e.g.
740                     # http://www.bbc.com/news/world-us-canada-34473351)
741                     playlist_object = settings.get('playlistObject', {})
742                     if playlist_object:
743                         items = playlist_object.get('items')
744                         if items and isinstance(items, list):
745                             title = playlist_object['title']
746                             description = playlist_object.get('summary')
747                             duration = int_or_none(items[0].get('duration'))
748                             programme_id = items[0].get('vpid')
749                             formats, subtitles = self._download_media_selector(programme_id)
750                             self._sort_formats(formats)
751                             entries.append({
752                                 'id': programme_id,
753                                 'title': title,
754                                 'description': description,
755                                 'timestamp': timestamp,
756                                 'duration': duration,
757                                 'formats': formats,
758                                 'subtitles': subtitles,
759                             })
760                     else:
761                         # data-playable without vpid but with a playlist.sxml URLs
762                         # in otherSettings.playlist (e.g.
763                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
764                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
765                         if playlist:
766                             entries.append(self._extract_from_playlist_sxml(
767                                 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
768
769         if entries:
770             playlist_title = self._og_search_title(webpage)
771             playlist_description = self._og_search_description(webpage, default=None)
772             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
773
774         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
775         programme_id = self._search_regex(
776             [r'data-video-player-vpid="([\da-z]{8})"',
777              r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
778             webpage, 'vpid', default=None)
779
780         if programme_id:
781             formats, subtitles = self._download_media_selector(programme_id)
782             self._sort_formats(formats)
783             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
784             digital_data = self._parse_json(
785                 self._search_regex(
786                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
787                 programme_id, fatal=False)
788             page_info = digital_data.get('page', {}).get('pageInfo', {})
789             title = page_info.get('pageName') or self._og_search_title(webpage)
790             description = page_info.get('description') or self._og_search_description(webpage)
791             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
792             return {
793                 'id': programme_id,
794                 'title': title,
795                 'description': description,
796                 'timestamp': timestamp,
797                 'formats': formats,
798                 'subtitles': subtitles,
799             }
800
801         playlist_title = self._html_search_regex(
802             r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
803         playlist_description = self._og_search_description(webpage, default=None)
804
805         def extract_all(pattern):
806             return list(filter(None, map(
807                 lambda s: self._parse_json(s, playlist_id, fatal=False),
808                 re.findall(pattern, webpage))))
809
810         # Multiple video article (e.g.
811         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
812         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
813         entries = []
814         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
815             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
816             if embed_url and re.match(EMBED_URL, embed_url):
817                 entries.append(embed_url)
818         entries.extend(re.findall(
819             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
820         if entries:
821             return self.playlist_result(
822                 [self.url_result(entry, 'BBCCoUk') for entry in entries],
823                 playlist_id, playlist_title, playlist_description)
824
825         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
826         medias = extract_all(r"data-media-meta='({[^']+})'")
827
828         if not medias:
829             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
830             media_asset = self._search_regex(
831                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
832                 webpage, 'media asset', default=None)
833             if media_asset:
834                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
835                 medias = []
836                 for video in media_asset_page.get('videos', {}).values():
837                     medias.extend(video.values())
838
839         if not medias:
840             # Multiple video playlist with single `now playing` entry (e.g.
841             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
842             vxp_playlist = self._parse_json(
843                 self._search_regex(
844                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
845                     webpage, 'playlist data'),
846                 playlist_id)
847             playlist_medias = []
848             for item in vxp_playlist:
849                 media = item.get('media')
850                 if not media:
851                     continue
852                 playlist_medias.append(media)
853                 # Download single video if found media with asset id matching the video id from URL
854                 if item.get('advert', {}).get('assetId') == playlist_id:
855                     medias = [media]
856                     break
857             # Fallback to the whole playlist
858             if not medias:
859                 medias = playlist_medias
860
861         entries = []
862         for num, media_meta in enumerate(medias, start=1):
863             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
864             if not formats:
865                 continue
866             self._sort_formats(formats)
867
868             video_id = media_meta.get('externalId')
869             if not video_id:
870                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
871
872             title = media_meta.get('caption')
873             if not title:
874                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
875
876             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
877
878             images = []
879             for image in media_meta.get('images', {}).values():
880                 images.extend(image.values())
881             if 'image' in media_meta:
882                 images.append(media_meta['image'])
883
884             thumbnails = [{
885                 'url': image.get('href'),
886                 'width': int_or_none(image.get('width')),
887                 'height': int_or_none(image.get('height')),
888             } for image in images]
889
890             entries.append({
891                 'id': video_id,
892                 'title': title,
893                 'thumbnails': thumbnails,
894                 'duration': duration,
895                 'timestamp': timestamp,
896                 'formats': formats,
897                 'subtitles': subtitles,
898             })
899
900         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)