symba (779893), страница 47

Файл №779893 symba (Symbian Books) 47 страницаsymba (779893) страница 472018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 47)

Whenadding new features that require additional API methods, Symbian preserves the previous calls for use by existing applications. There is littlereason to refactor existing applications just to use the latest API, but fornew applications the general advice is clear: instead of passing the filename to open, pass an open RFile handle. Especially if the RFile objectis passed down by the application, this makes it easier for the applicationto deal with files passed by other subsystems – passing RFile handlesaround has replaced filenames as the standard Symbian OS method ofpassing a file from one application to another.In addition to this, it is worth considering using TMMSource objectsto pass the RFile handle to the multimedia subsystem.

The mainreason for using TMMSource is because it is useful for supporting DRMscenarios – it allows DRM-specific information to be supplied. Again,222BEST PRACTICEeven if your application does not currently require this, using TMMSourceconsistently makes things easier for future adaptation (see Section 2.3 formore on DRM and TMMSource).There are equivalent calls in each of the multimedia player and decoderAPIs, and they should be used for the same reasons.8.13Consider the Volume ControlThe settings for MaxVolume() and MaxGain() vary from one deviceto another, although they are constant for a given device. Applicationsmust not assume specific MaxVolume() or MaxGain() values across arange of devices.So how does this affect your applications? Be very careful about volumesliders and other choice UI features. You have a choice: enquire aboutthe MaxVolume() (or MaxGain(), as appropriate) setting and changethe slider values; or hardwire a range (say 0 to 10) and then scale to thereal MMF range.

In general, people seem to prefer the former, but it is anapplication choice.A second point concerns the default volume or gain. It is recommendedthat you use (MaxVolume()+1)/2 for the default volume, and theequivalent for gain.As a side point, it is probably always a good idea to set the volume orgain.

For some versions of Symbian OS, you need to or nothing can beheard.Another feature you may find useful is volume ramping (using one ofthe SetVolumeRamp() methods), which provides a fade-in feature. Thevolume increases from zero to the current setting at the start of playbackover a time period you specify. It’s a good idea to use this for a shortfade-in (say, half a second), even if you don’t need a fade-in effect.

Withthe audio stream APIs, or DevSound, it can help avoid any poppingor clicking noises when starting playback. In addition, it can prevent aphenomenon known as audio shock, where a very loud sound is startedsuddenly and the end user’s ear doesn’t have time to adjust – potentiallydamaging hearing.

There is no fade-out API in standard Symbian OS,although it may be supported as an extension on some devices – look atthe appropriate SDK.8.14Know When to Use Threaded Requests on ICLBy default, ICL decoder and encoder plug-ins run in the same threadas the calling code, but the client can request that they run in a separate thread (see Chapter 6 for examples). It is perhaps tempting to doDON’T HAVE TOO MANY CLIENTS223this for performance reasons but, because of the extra overheads ofthread support, using threads is not always much faster and is occasionally slower.You should,almost certainly not do this – just accept the default setting.The only time you may want to use the option is when your program isdoing something else that is time critical.Normal ICL processing takes place in the same thread using CActivebased objects – a standard way of doing background-processing onSymbian OS.

The disadvantage of this approach is that it takes a little longer for the program to respond to other events, such as key presses,pen taps and redraw requests. In such a case, the CActive::RunL()call doing the background processing must first finish before the higherpriority event is handled.

This is not as bad as it might seem – imageprocessing is split into many reasonably short RunL() calls, instead of asingle large one, so in normal processing this delay should be no morethan 100 ms and not generally observable. However, in some scenarios itis important, e.g. if your application is streaming data and, more importantly, is streaming it in the main thread. In such situations, and only insuch situations, you should perhaps use this option.Why not always use it? Well apart from higher resource utilization, itturns out that creating, deleting and stopping the encoder and decoderobjects takes a noticeable amount of time – so by using this option, yourapplication might go slightly slower.

OK, your end users probably won’tsee it but this option does not come without disadvantages.There are other scenarios where the ICL codec runs in its ownthread – where the codec itself requests to do so. Some codecs can’teasily be written using the multiple RunL() approach and using a threadallows the codec to be supported without having to be completelyrewritten.To summarize: don’t do this by default, but it can be useful in somecircumstances if used with care.8.15 Don’t Have too many ClientsAt one level, Symbian OS is a sophisticated, multi-tasking system thatcan have many applications open and executing concurrently; at anotherlevel, the target devices are still relatively small and have limited memoryand processing power – especially compared with desktop computers.It is comparatively easy to ask the device to perform operations thatare beyond it, trying to have too many active clients, decoding images,playing sounds, and playing video at the same time.On a very simplistic level, the more clients you create, the morememory and other resources are used.

However, the reality is more224BEST PRACTICEcomplex: an ‘active client’ consumes significantly more resources thenan idle one. By ‘active’ we mean, for example, an MMF client that isplaying or recording, or an ICL client that is decoding or encoding.The effects vary, but the basic rules are fairly straightforward: withinreason, you can have several clips or images open, but if they are active,it is more likely there will be a problem.The lowest memory usage comes from doing only one thing at atime.

For example, if you have several images to decode to bitmaps, itis generally better to do one at a time. For standard decoding you onlyneed to have a decoder object for the conversion operation and can thendelete it, keeping the generated bitmap output to display.

Similarly if youare transcoding several audio files, you should convert each file seriallywithout trying to overlap.Things get more tricky where the use case actually calls for youto do more than one thing. For example, where you are downloadingseveral images concurrently and wish to display partially downloadedresults, or wish to play more than one audio stream. For the latter case youshould perhaps consider the reasonableness of the use case – playing fourseparate channels may work on some devices but it won’t on others – andperhaps have some option for ‘simple’ as opposed to ‘rich’ audio.

For thepartial download case, having a limit on the number of active decoders isprobably a good idea, for example, in the region of two to four is a goodrule of thumb.We suggest you avoid the approach of hardwiring what works ona particular device since variations between firmware versions, othersoftware being installed, and so on, can all make a difference.

Twodevices that end users believe to be identical may in fact have differentperformance characteristics. Don’t over-complicate things but do allowsome options.As a final point, too much going on may be a sign of a confusingapplication (apart from, perhaps, in games) – so take care!8.16Understand the Multi-heap ProblemThis is a specific issue of trying to do too much at the same time, andwith a bit of luck you will never run into it! However, it is worth knowingabout, just in case.The issue is to do with chunks – see RChunk in the Symbian Developer Library documentation. These chunks are used to support sectionsof memory.

From an application perspective, they usually representsections of real memory accessible by the process – they are used forvarious things including heaps, some DLLs, shared memory betweenUNDERSTAND THE MULTI-HEAP PROBLEM225processes, device data buffers, etc. At the kernel level, these relate tomemory management – how the virtual addresses are mapped to physicaladdresses, etc.Although chunks do not normally concern application writers, theyare quite a useful tool that many of the Symbian OS user-side librariesdepend on.

Each heap is a separate chunk, and that is a fundamentalfeature of C++. However, depending on the underlying hardware, thenumber of chunks that can be mapped into a process can be limited. AtSymbian, we usually work to a rule-of-thumb where there is a limit of16 chunks per user process – regardless of whether it is an application, aserver or something else. This restriction only applies on some platforms,but it is a good idea to assume it if you want the code to be portable.What this means is that having too many heaps is an issue.So how does this affect us? Well from Symbian’s perspective, we’vehad to try to design the subsystems to not create too many heaps.

Froman application programmer’s perspective, you have to be careful in somescenarios. In general, it should not affect you – unless you are trying to dotoo much at the same time. ICL instances normally share the user heap,apart from a few plug-ins that use temporary chunks or heaps to avoidfragmentation.

Характеристики

Тип файла
PDF-файл
Размер
1,13 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее