ffserver.c 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018
  1. /*
  2. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multiple format streaming server based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #if !HAVE_CLOSESOCKET
  26. #define closesocket close
  27. #endif
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include "libavformat/avformat.h"
  32. /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
  33. #include "libavformat/rtpproto.h"
  34. #include "libavformat/rtsp.h"
  35. #include "libavformat/avio_internal.h"
  36. #include "libavformat/internal.h"
  37. #include "libavutil/avassert.h"
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/lfg.h"
  40. #include "libavutil/dict.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/mathematics.h"
  43. #include "libavutil/random_seed.h"
  44. #include "libavutil/rational.h"
  45. #include "libavutil/parseutils.h"
  46. #include "libavutil/opt.h"
  47. #include "libavutil/time.h"
  48. #include <stdarg.h>
  49. #if HAVE_UNISTD_H
  50. #include <unistd.h>
  51. #endif
  52. #include <fcntl.h>
  53. #include <sys/ioctl.h>
  54. #if HAVE_POLL_H
  55. #include <poll.h>
  56. #endif
  57. #include <errno.h>
  58. #include <time.h>
  59. #include <sys/wait.h>
  60. #include <signal.h>
  61. #include "cmdutils.h"
  62. #include "ffserver_config.h"
  63. #define PATH_LENGTH 1024
  64. const char program_name[] = "ffserver";
  65. const int program_birth_year = 2000;
  66. static const OptionDef options[];
  67. enum HTTPState {
  68. HTTPSTATE_WAIT_REQUEST,
  69. HTTPSTATE_SEND_HEADER,
  70. HTTPSTATE_SEND_DATA_HEADER,
  71. HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
  72. HTTPSTATE_SEND_DATA_TRAILER,
  73. HTTPSTATE_RECEIVE_DATA,
  74. HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
  75. HTTPSTATE_READY,
  76. RTSPSTATE_WAIT_REQUEST,
  77. RTSPSTATE_SEND_REPLY,
  78. RTSPSTATE_SEND_PACKET,
  79. };
  80. static const char * const http_state[] = {
  81. "HTTP_WAIT_REQUEST",
  82. "HTTP_SEND_HEADER",
  83. "SEND_DATA_HEADER",
  84. "SEND_DATA",
  85. "SEND_DATA_TRAILER",
  86. "RECEIVE_DATA",
  87. "WAIT_FEED",
  88. "READY",
  89. "RTSP_WAIT_REQUEST",
  90. "RTSP_SEND_REPLY",
  91. "RTSP_SEND_PACKET",
  92. };
  93. #define IOBUFFER_INIT_SIZE 8192
  94. /* timeouts are in ms */
  95. #define HTTP_REQUEST_TIMEOUT (15 * 1000)
  96. #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
  97. #define SYNC_TIMEOUT (10 * 1000)
  98. typedef struct RTSPActionServerSetup {
  99. uint32_t ipaddr;
  100. char transport_option[512];
  101. } RTSPActionServerSetup;
  102. typedef struct {
  103. int64_t count1, count2;
  104. int64_t time1, time2;
  105. } DataRateData;
  106. /* context associated with one connection */
  107. typedef struct HTTPContext {
  108. enum HTTPState state;
  109. int fd; /* socket file descriptor */
  110. struct sockaddr_in from_addr; /* origin */
  111. struct pollfd *poll_entry; /* used when polling */
  112. int64_t timeout;
  113. uint8_t *buffer_ptr, *buffer_end;
  114. int http_error;
  115. int post;
  116. int chunked_encoding;
  117. int chunk_size; /* 0 if it needs to be read */
  118. struct HTTPContext *next;
  119. int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
  120. int64_t data_count;
  121. /* feed input */
  122. int feed_fd;
  123. /* input format handling */
  124. AVFormatContext *fmt_in;
  125. int64_t start_time; /* In milliseconds - this wraps fairly often */
  126. int64_t first_pts; /* initial pts value */
  127. int64_t cur_pts; /* current pts value from the stream in us */
  128. int64_t cur_frame_duration; /* duration of the current frame in us */
  129. int cur_frame_bytes; /* output frame size, needed to compute
  130. the time at which we send each
  131. packet */
  132. int pts_stream_index; /* stream we choose as clock reference */
  133. int64_t cur_clock; /* current clock reference value in us */
  134. /* output format handling */
  135. struct FFServerStream *stream;
  136. /* -1 is invalid stream */
  137. int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  138. int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  139. int switch_pending;
  140. AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */
  141. int last_packet_sent; /* true if last data packet was sent */
  142. int suppress_log;
  143. DataRateData datarate;
  144. int wmp_client_id;
  145. char protocol[16];
  146. char method[16];
  147. char url[128];
  148. char clean_url[128*7];
  149. int buffer_size;
  150. uint8_t *buffer;
  151. int is_packetized; /* if true, the stream is packetized */
  152. int packet_stream_index; /* current stream for output in state machine */
  153. /* RTSP state specific */
  154. uint8_t *pb_buffer; /* XXX: use that in all the code */
  155. AVIOContext *pb;
  156. int seq; /* RTSP sequence number */
  157. /* RTP state specific */
  158. enum RTSPLowerTransport rtp_protocol;
  159. char session_id[32]; /* session id */
  160. AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
  161. /* RTP/UDP specific */
  162. URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
  163. /* RTP/TCP specific */
  164. struct HTTPContext *rtsp_c;
  165. uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
  166. } HTTPContext;
  167. static HTTPContext *first_http_ctx;
  168. static FFServerConfig config = {
  169. .nb_max_http_connections = 2000,
  170. .nb_max_connections = 5,
  171. .max_bandwidth = 1000,
  172. .use_defaults = 1,
  173. };
  174. static void new_connection(int server_fd, int is_rtsp);
  175. static void close_connection(HTTPContext *c);
  176. /* HTTP handling */
  177. static int handle_connection(HTTPContext *c);
  178. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
  179. static void compute_status(HTTPContext *c);
  180. static int open_input_stream(HTTPContext *c, const char *info);
  181. static int http_parse_request(HTTPContext *c);
  182. static int http_send_data(HTTPContext *c);
  183. static int http_start_receive_data(HTTPContext *c);
  184. static int http_receive_data(HTTPContext *c);
  185. /* RTSP handling */
  186. static int rtsp_parse_request(HTTPContext *c);
  187. static void rtsp_cmd_describe(HTTPContext *c, const char *url);
  188. static void rtsp_cmd_options(HTTPContext *c, const char *url);
  189. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  190. RTSPMessageHeader *h);
  191. static void rtsp_cmd_play(HTTPContext *c, const char *url,
  192. RTSPMessageHeader *h);
  193. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  194. RTSPMessageHeader *h, int pause_only);
  195. /* SDP handling */
  196. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  197. struct in_addr my_ip);
  198. /* RTP handling */
  199. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  200. FFServerStream *stream,
  201. const char *session_id,
  202. enum RTSPLowerTransport rtp_protocol);
  203. static int rtp_new_av_stream(HTTPContext *c,
  204. int stream_index, struct sockaddr_in *dest_addr,
  205. HTTPContext *rtsp_c);
  206. /* utils */
  207. static size_t htmlencode (const char *src, char **dest);
  208. static inline void cp_html_entity (char *buffer, const char *entity);
  209. static inline int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream);
  210. static const char *my_program_name;
  211. static int no_launch;
  212. static int need_to_start_children;
  213. /* maximum number of simultaneous HTTP connections */
  214. static unsigned int nb_connections;
  215. static uint64_t current_bandwidth;
  216. /* Making this global saves on passing it around everywhere */
  217. static int64_t cur_time;
  218. static AVLFG random_state;
  219. static FILE *logfile = NULL;
  220. static void unlayer_stream(AVStream *st, LayeredAVStream *lst)
  221. {
  222. avcodec_free_context(&st->codec);
  223. avcodec_parameters_free(&st->codecpar);
  224. #define COPY(a) st->a = lst->a;
  225. COPY(index)
  226. COPY(id)
  227. COPY(codec)
  228. COPY(codecpar)
  229. COPY(time_base)
  230. COPY(pts_wrap_bits)
  231. COPY(sample_aspect_ratio)
  232. COPY(recommended_encoder_configuration)
  233. }
  234. static inline void cp_html_entity (char *buffer, const char *entity) {
  235. if (!buffer || !entity)
  236. return;
  237. while (*entity)
  238. *buffer++ = *entity++;
  239. }
  240. /**
  241. * Substitutes known conflicting chars on a text string with
  242. * their corresponding HTML entities.
  243. *
  244. * Returns the number of bytes in the 'encoded' representation
  245. * not including the terminating NUL.
  246. */
  247. static size_t htmlencode (const char *src, char **dest) {
  248. const char *amp = "&amp;";
  249. const char *lt = "&lt;";
  250. const char *gt = "&gt;";
  251. const char *start;
  252. char *tmp;
  253. size_t final_size = 0;
  254. if (!src)
  255. return 0;
  256. start = src;
  257. /* Compute needed dest size */
  258. while (*src != '\0') {
  259. switch(*src) {
  260. case 38: /* & */
  261. final_size += 5;
  262. break;
  263. case 60: /* < */
  264. case 62: /* > */
  265. final_size += 4;
  266. break;
  267. default:
  268. final_size++;
  269. }
  270. src++;
  271. }
  272. src = start;
  273. *dest = av_mallocz(final_size + 1);
  274. if (!*dest)
  275. return 0;
  276. /* Build dest */
  277. tmp = *dest;
  278. while (*src != '\0') {
  279. switch(*src) {
  280. case 38: /* & */
  281. cp_html_entity (tmp, amp);
  282. tmp += 5;
  283. break;
  284. case 60: /* < */
  285. cp_html_entity (tmp, lt);
  286. tmp += 4;
  287. break;
  288. case 62: /* > */
  289. cp_html_entity (tmp, gt);
  290. tmp += 4;
  291. break;
  292. default:
  293. *tmp = *src;
  294. tmp += 1;
  295. }
  296. src++;
  297. }
  298. *tmp = '\0';
  299. return final_size;
  300. }
  301. static int64_t ffm_read_write_index(int fd)
  302. {
  303. uint8_t buf[8];
  304. if (lseek(fd, 8, SEEK_SET) < 0)
  305. return AVERROR(EIO);
  306. if (read(fd, buf, 8) != 8)
  307. return AVERROR(EIO);
  308. return AV_RB64(buf);
  309. }
  310. static int ffm_write_write_index(int fd, int64_t pos)
  311. {
  312. uint8_t buf[8];
  313. int i;
  314. for(i=0;i<8;i++)
  315. buf[i] = (pos >> (56 - i * 8)) & 0xff;
  316. if (lseek(fd, 8, SEEK_SET) < 0)
  317. goto bail_eio;
  318. if (write(fd, buf, 8) != 8)
  319. goto bail_eio;
  320. return 8;
  321. bail_eio:
  322. return AVERROR(EIO);
  323. }
  324. static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
  325. int64_t file_size)
  326. {
  327. av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
  328. av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
  329. av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
  330. }
  331. static char *ctime1(char *buf2, size_t buf_size)
  332. {
  333. time_t ti;
  334. char *p;
  335. ti = time(NULL);
  336. p = ctime(&ti);
  337. if (!p || !*p) {
  338. *buf2 = '\0';
  339. return buf2;
  340. }
  341. av_strlcpy(buf2, p, buf_size);
  342. p = buf2 + strlen(buf2) - 1;
  343. if (*p == '\n')
  344. *p = '\0';
  345. return buf2;
  346. }
  347. static void http_vlog(const char *fmt, va_list vargs)
  348. {
  349. static int print_prefix = 1;
  350. char buf[32];
  351. if (!logfile)
  352. return;
  353. if (print_prefix) {
  354. ctime1(buf, sizeof(buf));
  355. fprintf(logfile, "%s ", buf);
  356. }
  357. print_prefix = strstr(fmt, "\n") != NULL;
  358. vfprintf(logfile, fmt, vargs);
  359. fflush(logfile);
  360. }
  361. #ifdef __GNUC__
  362. __attribute__ ((format (printf, 1, 2)))
  363. #endif
  364. static void http_log(const char *fmt, ...)
  365. {
  366. va_list vargs;
  367. va_start(vargs, fmt);
  368. http_vlog(fmt, vargs);
  369. va_end(vargs);
  370. }
  371. static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
  372. {
  373. static int print_prefix = 1;
  374. AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
  375. if (level > av_log_get_level())
  376. return;
  377. if (print_prefix && avc)
  378. http_log("[%s @ %p]", avc->item_name(ptr), ptr);
  379. print_prefix = strstr(fmt, "\n") != NULL;
  380. http_vlog(fmt, vargs);
  381. }
  382. static void log_connection(HTTPContext *c)
  383. {
  384. if (c->suppress_log)
  385. return;
  386. http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
  387. inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
  388. c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
  389. }
  390. static void update_datarate(DataRateData *drd, int64_t count)
  391. {
  392. if (!drd->time1 && !drd->count1) {
  393. drd->time1 = drd->time2 = cur_time;
  394. drd->count1 = drd->count2 = count;
  395. } else if (cur_time - drd->time2 > 5000) {
  396. drd->time1 = drd->time2;
  397. drd->count1 = drd->count2;
  398. drd->time2 = cur_time;
  399. drd->count2 = count;
  400. }
  401. }
  402. /* In bytes per second */
  403. static int compute_datarate(DataRateData *drd, int64_t count)
  404. {
  405. if (cur_time == drd->time1)
  406. return 0;
  407. return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
  408. }
  409. static void start_children(FFServerStream *feed)
  410. {
  411. char *pathname;
  412. char *slash;
  413. int i;
  414. size_t cmd_length;
  415. if (no_launch)
  416. return;
  417. cmd_length = strlen(my_program_name);
  418. /**
  419. * FIXME: WIP Safeguard. Remove after clearing all harcoded
  420. * '1024' path lengths
  421. */
  422. if (cmd_length > PATH_LENGTH - 1) {
  423. http_log("Could not start children. Command line: '%s' exceeds "
  424. "path length limit (%d)\n", my_program_name, PATH_LENGTH);
  425. return;
  426. }
  427. pathname = av_strdup (my_program_name);
  428. if (!pathname) {
  429. http_log("Could not allocate memory for children cmd line\n");
  430. return;
  431. }
  432. /* replace "ffserver" with "ffmpeg" in the path of current
  433. * program. Ignore user provided path */
  434. slash = strrchr(pathname, '/');
  435. if (!slash)
  436. slash = pathname;
  437. else
  438. slash++;
  439. strcpy(slash, "ffmpeg");
  440. for (; feed; feed = feed->next) {
  441. if (!feed->child_argv || feed->pid)
  442. continue;
  443. feed->pid_start = time(0);
  444. feed->pid = fork();
  445. if (feed->pid < 0) {
  446. http_log("Unable to create children: %s\n", strerror(errno));
  447. av_free (pathname);
  448. exit(EXIT_FAILURE);
  449. }
  450. if (feed->pid)
  451. continue;
  452. /* In child */
  453. http_log("Launch command line: ");
  454. http_log("%s ", pathname);
  455. for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
  456. http_log("%s ", feed->child_argv[i]);
  457. http_log("\n");
  458. for (i = 3; i < 256; i++)
  459. close(i);
  460. if (!config.debug) {
  461. if (!freopen("/dev/null", "r", stdin))
  462. http_log("failed to redirect STDIN to /dev/null\n;");
  463. if (!freopen("/dev/null", "w", stdout))
  464. http_log("failed to redirect STDOUT to /dev/null\n;");
  465. if (!freopen("/dev/null", "w", stderr))
  466. http_log("failed to redirect STDERR to /dev/null\n;");
  467. }
  468. signal(SIGPIPE, SIG_DFL);
  469. execvp(pathname, feed->child_argv);
  470. av_free (pathname);
  471. _exit(1);
  472. }
  473. av_free (pathname);
  474. }
  475. /* open a listening socket */
  476. static int socket_open_listen(struct sockaddr_in *my_addr)
  477. {
  478. int server_fd, tmp;
  479. server_fd = socket(AF_INET,SOCK_STREAM,0);
  480. if (server_fd < 0) {
  481. perror ("socket");
  482. return -1;
  483. }
  484. tmp = 1;
  485. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
  486. av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
  487. my_addr->sin_family = AF_INET;
  488. if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
  489. char bindmsg[32];
  490. snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
  491. ntohs(my_addr->sin_port));
  492. perror (bindmsg);
  493. goto fail;
  494. }
  495. if (listen (server_fd, 5) < 0) {
  496. perror ("listen");
  497. goto fail;
  498. }
  499. if (ff_socket_nonblock(server_fd, 1) < 0)
  500. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  501. return server_fd;
  502. fail:
  503. closesocket(server_fd);
  504. return -1;
  505. }
  506. /* start all multicast streams */
  507. static void start_multicast(void)
  508. {
  509. FFServerStream *stream;
  510. char session_id[32];
  511. HTTPContext *rtp_c;
  512. struct sockaddr_in dest_addr = {0};
  513. int default_port, stream_index;
  514. unsigned int random0, random1;
  515. default_port = 6000;
  516. for(stream = config.first_stream; stream; stream = stream->next) {
  517. if (!stream->is_multicast)
  518. continue;
  519. random0 = av_lfg_get(&random_state);
  520. random1 = av_lfg_get(&random_state);
  521. /* open the RTP connection */
  522. snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
  523. /* choose a port if none given */
  524. if (stream->multicast_port == 0) {
  525. stream->multicast_port = default_port;
  526. default_port += 100;
  527. }
  528. dest_addr.sin_family = AF_INET;
  529. dest_addr.sin_addr = stream->multicast_ip;
  530. dest_addr.sin_port = htons(stream->multicast_port);
  531. rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
  532. RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  533. if (!rtp_c)
  534. continue;
  535. if (open_input_stream(rtp_c, "") < 0) {
  536. http_log("Could not open input stream for stream '%s'\n",
  537. stream->filename);
  538. continue;
  539. }
  540. /* open each RTP stream */
  541. for(stream_index = 0; stream_index < stream->nb_streams;
  542. stream_index++) {
  543. dest_addr.sin_port = htons(stream->multicast_port +
  544. 2 * stream_index);
  545. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
  546. continue;
  547. http_log("Could not open output stream '%s/streamid=%d'\n",
  548. stream->filename, stream_index);
  549. exit(1);
  550. }
  551. rtp_c->state = HTTPSTATE_SEND_DATA;
  552. }
  553. }
  554. /* main loop of the HTTP server */
  555. static int http_server(void)
  556. {
  557. int server_fd = 0, rtsp_server_fd = 0;
  558. int ret, delay;
  559. struct pollfd *poll_table, *poll_entry;
  560. HTTPContext *c, *c_next;
  561. poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
  562. sizeof(*poll_table));
  563. if(!poll_table) {
  564. http_log("Impossible to allocate a poll table handling %d "
  565. "connections.\n", config.nb_max_http_connections);
  566. return -1;
  567. }
  568. if (config.http_addr.sin_port) {
  569. server_fd = socket_open_listen(&config.http_addr);
  570. if (server_fd < 0)
  571. goto quit;
  572. }
  573. if (config.rtsp_addr.sin_port) {
  574. rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
  575. if (rtsp_server_fd < 0) {
  576. closesocket(server_fd);
  577. goto quit;
  578. }
  579. }
  580. if (!rtsp_server_fd && !server_fd) {
  581. http_log("HTTP and RTSP disabled.\n");
  582. goto quit;
  583. }
  584. http_log("FFserver started.\n");
  585. start_children(config.first_feed);
  586. start_multicast();
  587. for(;;) {
  588. poll_entry = poll_table;
  589. if (server_fd) {
  590. poll_entry->fd = server_fd;
  591. poll_entry->events = POLLIN;
  592. poll_entry++;
  593. }
  594. if (rtsp_server_fd) {
  595. poll_entry->fd = rtsp_server_fd;
  596. poll_entry->events = POLLIN;
  597. poll_entry++;
  598. }
  599. /* wait for events on each HTTP handle */
  600. c = first_http_ctx;
  601. delay = 1000;
  602. while (c) {
  603. int fd;
  604. fd = c->fd;
  605. switch(c->state) {
  606. case HTTPSTATE_SEND_HEADER:
  607. case RTSPSTATE_SEND_REPLY:
  608. case RTSPSTATE_SEND_PACKET:
  609. c->poll_entry = poll_entry;
  610. poll_entry->fd = fd;
  611. poll_entry->events = POLLOUT;
  612. poll_entry++;
  613. break;
  614. case HTTPSTATE_SEND_DATA_HEADER:
  615. case HTTPSTATE_SEND_DATA:
  616. case HTTPSTATE_SEND_DATA_TRAILER:
  617. if (!c->is_packetized) {
  618. /* for TCP, we output as much as we can
  619. * (may need to put a limit) */
  620. c->poll_entry = poll_entry;
  621. poll_entry->fd = fd;
  622. poll_entry->events = POLLOUT;
  623. poll_entry++;
  624. } else {
  625. /* when ffserver is doing the timing, we work by
  626. * looking at which packet needs to be sent every
  627. * 10 ms (one tick wait XXX: 10 ms assumed) */
  628. if (delay > 10)
  629. delay = 10;
  630. }
  631. break;
  632. case HTTPSTATE_WAIT_REQUEST:
  633. case HTTPSTATE_RECEIVE_DATA:
  634. case HTTPSTATE_WAIT_FEED:
  635. case RTSPSTATE_WAIT_REQUEST:
  636. /* need to catch errors */
  637. c->poll_entry = poll_entry;
  638. poll_entry->fd = fd;
  639. poll_entry->events = POLLIN;/* Maybe this will work */
  640. poll_entry++;
  641. break;
  642. default:
  643. c->poll_entry = NULL;
  644. break;
  645. }
  646. c = c->next;
  647. }
  648. /* wait for an event on one connection. We poll at least every
  649. * second to handle timeouts */
  650. do {
  651. ret = poll(poll_table, poll_entry - poll_table, delay);
  652. if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
  653. ff_neterrno() != AVERROR(EINTR)) {
  654. goto quit;
  655. }
  656. } while (ret < 0);
  657. cur_time = av_gettime() / 1000;
  658. if (need_to_start_children) {
  659. need_to_start_children = 0;
  660. start_children(config.first_feed);
  661. }
  662. /* now handle the events */
  663. for(c = first_http_ctx; c; c = c_next) {
  664. c_next = c->next;
  665. if (handle_connection(c) < 0) {
  666. log_connection(c);
  667. /* close and free the connection */
  668. close_connection(c);
  669. }
  670. }
  671. poll_entry = poll_table;
  672. if (server_fd) {
  673. /* new HTTP connection request ? */
  674. if (poll_entry->revents & POLLIN)
  675. new_connection(server_fd, 0);
  676. poll_entry++;
  677. }
  678. if (rtsp_server_fd) {
  679. /* new RTSP connection request ? */
  680. if (poll_entry->revents & POLLIN)
  681. new_connection(rtsp_server_fd, 1);
  682. }
  683. }
  684. quit:
  685. av_free(poll_table);
  686. return -1;
  687. }
  688. /* start waiting for a new HTTP/RTSP request */
  689. static void start_wait_request(HTTPContext *c, int is_rtsp)
  690. {
  691. c->buffer_ptr = c->buffer;
  692. c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
  693. c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
  694. c->timeout = cur_time +
  695. (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
  696. }
  697. static void http_send_too_busy_reply(int fd)
  698. {
  699. char buffer[400];
  700. int len = snprintf(buffer, sizeof(buffer),
  701. "HTTP/1.0 503 Server too busy\r\n"
  702. "Content-type: text/html\r\n"
  703. "\r\n"
  704. "<!DOCTYPE html>\n"
  705. "<html><head><title>Too busy</title></head><body>\r\n"
  706. "<p>The server is too busy to serve your request at "
  707. "this time.</p>\r\n"
  708. "<p>The number of current connections is %u, and this "
  709. "exceeds the limit of %u.</p>\r\n"
  710. "</body></html>\r\n",
  711. nb_connections, config.nb_max_connections);
  712. av_assert0(len < sizeof(buffer));
  713. if (send(fd, buffer, len, 0) < len)
  714. av_log(NULL, AV_LOG_WARNING,
  715. "Could not send too-busy reply, send() failed\n");
  716. }
  717. static void new_connection(int server_fd, int is_rtsp)
  718. {
  719. struct sockaddr_in from_addr;
  720. socklen_t len;
  721. int fd;
  722. HTTPContext *c = NULL;
  723. len = sizeof(from_addr);
  724. fd = accept(server_fd, (struct sockaddr *)&from_addr,
  725. &len);
  726. if (fd < 0) {
  727. http_log("error during accept %s\n", strerror(errno));
  728. return;
  729. }
  730. if (ff_socket_nonblock(fd, 1) < 0)
  731. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  732. if (nb_connections >= config.nb_max_connections) {
  733. http_send_too_busy_reply(fd);
  734. goto fail;
  735. }
  736. /* add a new connection */
  737. c = av_mallocz(sizeof(HTTPContext));
  738. if (!c)
  739. goto fail;
  740. c->fd = fd;
  741. c->poll_entry = NULL;
  742. c->from_addr = from_addr;
  743. c->buffer_size = IOBUFFER_INIT_SIZE;
  744. c->buffer = av_malloc(c->buffer_size);
  745. if (!c->buffer)
  746. goto fail;
  747. c->next = first_http_ctx;
  748. first_http_ctx = c;
  749. nb_connections++;
  750. start_wait_request(c, is_rtsp);
  751. return;
  752. fail:
  753. if (c) {
  754. av_freep(&c->buffer);
  755. av_free(c);
  756. }
  757. closesocket(fd);
  758. }
  759. static void close_connection(HTTPContext *c)
  760. {
  761. HTTPContext **cp, *c1;
  762. int i, nb_streams;
  763. AVFormatContext *ctx;
  764. AVStream *st;
  765. /* remove connection from list */
  766. cp = &first_http_ctx;
  767. while (*cp) {
  768. c1 = *cp;
  769. if (c1 == c)
  770. *cp = c->next;
  771. else
  772. cp = &c1->next;
  773. }
  774. /* remove references, if any (XXX: do it faster) */
  775. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  776. if (c1->rtsp_c == c)
  777. c1->rtsp_c = NULL;
  778. }
  779. /* remove connection associated resources */
  780. if (c->fd >= 0)
  781. closesocket(c->fd);
  782. if (c->fmt_in) {
  783. /* close each frame parser */
  784. for(i=0;i<c->fmt_in->nb_streams;i++) {
  785. st = c->fmt_in->streams[i];
  786. if (st->codec->codec)
  787. avcodec_close(st->codec);
  788. }
  789. avformat_close_input(&c->fmt_in);
  790. }
  791. /* free RTP output streams if any */
  792. nb_streams = 0;
  793. if (c->stream)
  794. nb_streams = c->stream->nb_streams;
  795. for(i=0;i<nb_streams;i++) {
  796. ctx = c->rtp_ctx[i];
  797. if (ctx) {
  798. av_write_trailer(ctx);
  799. av_dict_free(&ctx->metadata);
  800. av_freep(&ctx->streams[0]);
  801. av_freep(&ctx);
  802. }
  803. ffurl_close(c->rtp_handles[i]);
  804. }
  805. ctx = c->pfmt_ctx;
  806. if (ctx) {
  807. if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
  808. /* prepare header */
  809. if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
  810. av_write_trailer(ctx);
  811. av_freep(&c->pb_buffer);
  812. avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  813. }
  814. }
  815. for(i=0; i<ctx->nb_streams; i++)
  816. av_freep(&ctx->streams[i]);
  817. av_freep(&ctx->streams);
  818. av_freep(&ctx->priv_data);
  819. }
  820. if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
  821. current_bandwidth -= c->stream->bandwidth;
  822. /* signal that there is no feed if we are the feeder socket */
  823. if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
  824. c->stream->feed_opened = 0;
  825. close(c->feed_fd);
  826. }
  827. av_freep(&c->pb_buffer);
  828. av_freep(&c->packet_buffer);
  829. av_freep(&c->buffer);
  830. av_free(c);
  831. nb_connections--;
  832. }
  833. static int handle_connection(HTTPContext *c)
  834. {
  835. int len, ret;
  836. uint8_t *ptr;
  837. switch(c->state) {
  838. case HTTPSTATE_WAIT_REQUEST:
  839. case RTSPSTATE_WAIT_REQUEST:
  840. /* timeout ? */
  841. if ((c->timeout - cur_time) < 0)
  842. return -1;
  843. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  844. return -1;
  845. /* no need to read if no events */
  846. if (!(c->poll_entry->revents & POLLIN))
  847. return 0;
  848. /* read the data */
  849. read_loop:
  850. if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
  851. return -1;
  852. if (len < 0) {
  853. if (ff_neterrno() != AVERROR(EAGAIN) &&
  854. ff_neterrno() != AVERROR(EINTR))
  855. return -1;
  856. break;
  857. }
  858. /* search for end of request. */
  859. c->buffer_ptr += len;
  860. ptr = c->buffer_ptr;
  861. if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
  862. (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
  863. /* request found : parse it and reply */
  864. if (c->state == HTTPSTATE_WAIT_REQUEST)
  865. ret = http_parse_request(c);
  866. else
  867. ret = rtsp_parse_request(c);
  868. if (ret < 0)
  869. return -1;
  870. } else if (ptr >= c->buffer_end) {
  871. /* request too long: cannot do anything */
  872. return -1;
  873. } else goto read_loop;
  874. break;
  875. case HTTPSTATE_SEND_HEADER:
  876. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  877. return -1;
  878. /* no need to write if no events */
  879. if (!(c->poll_entry->revents & POLLOUT))
  880. return 0;
  881. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  882. if (len < 0) {
  883. if (ff_neterrno() != AVERROR(EAGAIN) &&
  884. ff_neterrno() != AVERROR(EINTR)) {
  885. goto close_connection;
  886. }
  887. break;
  888. }
  889. c->buffer_ptr += len;
  890. if (c->stream)
  891. c->stream->bytes_served += len;
  892. c->data_count += len;
  893. if (c->buffer_ptr >= c->buffer_end) {
  894. av_freep(&c->pb_buffer);
  895. /* if error, exit */
  896. if (c->http_error)
  897. return -1;
  898. /* all the buffer was sent : synchronize to the incoming
  899. * stream */
  900. c->state = HTTPSTATE_SEND_DATA_HEADER;
  901. c->buffer_ptr = c->buffer_end = c->buffer;
  902. }
  903. break;
  904. case HTTPSTATE_SEND_DATA:
  905. case HTTPSTATE_SEND_DATA_HEADER:
  906. case HTTPSTATE_SEND_DATA_TRAILER:
  907. /* for packetized output, we consider we can always write (the
  908. * input streams set the speed). It may be better to verify
  909. * that we do not rely too much on the kernel queues */
  910. if (!c->is_packetized) {
  911. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  912. return -1;
  913. /* no need to read if no events */
  914. if (!(c->poll_entry->revents & POLLOUT))
  915. return 0;
  916. }
  917. if (http_send_data(c) < 0)
  918. return -1;
  919. /* close connection if trailer sent */
  920. if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
  921. return -1;
  922. /* Check if it is a single jpeg frame 123 */
  923. if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
  924. close_connection(c);
  925. }
  926. break;
  927. case HTTPSTATE_RECEIVE_DATA:
  928. /* no need to read if no events */
  929. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  930. return -1;
  931. if (!(c->poll_entry->revents & POLLIN))
  932. return 0;
  933. if (http_receive_data(c) < 0)
  934. return -1;
  935. break;
  936. case HTTPSTATE_WAIT_FEED:
  937. /* no need to read if no events */
  938. if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
  939. return -1;
  940. /* nothing to do, we'll be waken up by incoming feed packets */
  941. break;
  942. case RTSPSTATE_SEND_REPLY:
  943. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  944. goto close_connection;
  945. /* no need to write if no events */
  946. if (!(c->poll_entry->revents & POLLOUT))
  947. return 0;
  948. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  949. if (len < 0) {
  950. if (ff_neterrno() != AVERROR(EAGAIN) &&
  951. ff_neterrno() != AVERROR(EINTR)) {
  952. goto close_connection;
  953. }
  954. break;
  955. }
  956. c->buffer_ptr += len;
  957. c->data_count += len;
  958. if (c->buffer_ptr >= c->buffer_end) {
  959. /* all the buffer was sent : wait for a new request */
  960. av_freep(&c->pb_buffer);
  961. start_wait_request(c, 1);
  962. }
  963. break;
  964. case RTSPSTATE_SEND_PACKET:
  965. if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
  966. av_freep(&c->packet_buffer);
  967. return -1;
  968. }
  969. /* no need to write if no events */
  970. if (!(c->poll_entry->revents & POLLOUT))
  971. return 0;
  972. len = send(c->fd, c->packet_buffer_ptr,
  973. c->packet_buffer_end - c->packet_buffer_ptr, 0);
  974. if (len < 0) {
  975. if (ff_neterrno() != AVERROR(EAGAIN) &&
  976. ff_neterrno() != AVERROR(EINTR)) {
  977. /* error : close connection */
  978. av_freep(&c->packet_buffer);
  979. return -1;
  980. }
  981. break;
  982. }
  983. c->packet_buffer_ptr += len;
  984. if (c->packet_buffer_ptr >= c->packet_buffer_end) {
  985. /* all the buffer was sent : wait for a new request */
  986. av_freep(&c->packet_buffer);
  987. c->state = RTSPSTATE_WAIT_REQUEST;
  988. }
  989. break;
  990. case HTTPSTATE_READY:
  991. /* nothing to do */
  992. break;
  993. default:
  994. return -1;
  995. }
  996. return 0;
  997. close_connection:
  998. av_freep(&c->pb_buffer);
  999. return -1;
  1000. }
  1001. static int extract_rates(char *rates, int ratelen, const char *request)
  1002. {
  1003. const char *p;
  1004. for (p = request; *p && *p != '\r' && *p != '\n'; ) {
  1005. if (av_strncasecmp(p, "Pragma:", 7) == 0) {
  1006. const char *q = p + 7;
  1007. while (*q && *q != '\n' && av_isspace(*q))
  1008. q++;
  1009. if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
  1010. int stream_no;
  1011. int rate_no;
  1012. q += 20;
  1013. memset(rates, 0xff, ratelen);
  1014. while (1) {
  1015. while (*q && *q != '\n' && *q != ':')
  1016. q++;
  1017. if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
  1018. break;
  1019. stream_no--;
  1020. if (stream_no < ratelen && stream_no >= 0)
  1021. rates[stream_no] = rate_no;
  1022. while (*q && *q != '\n' && !av_isspace(*q))
  1023. q++;
  1024. }
  1025. return 1;
  1026. }
  1027. }
  1028. p = strchr(p, '\n');
  1029. if (!p)
  1030. break;
  1031. p++;
  1032. }
  1033. return 0;
  1034. }
  1035. static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
  1036. int bit_rate)
  1037. {
  1038. int i;
  1039. int best_bitrate = 100000000;
  1040. int best = -1;
  1041. for (i = 0; i < feed->nb_streams; i++) {
  1042. AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
  1043. if (feed_codec->codec_id != codec->codec_id ||
  1044. feed_codec->sample_rate != codec->sample_rate ||
  1045. feed_codec->width != codec->width ||
  1046. feed_codec->height != codec->height)
  1047. continue;
  1048. /* Potential stream */
  1049. /* We want the fastest stream less than bit_rate, or the slowest
  1050. * faster than bit_rate
  1051. */
  1052. if (feed_codec->bit_rate <= bit_rate) {
  1053. if (best_bitrate > bit_rate ||
  1054. feed_codec->bit_rate > best_bitrate) {
  1055. best_bitrate = feed_codec->bit_rate;
  1056. best = i;
  1057. }
  1058. continue;
  1059. }
  1060. if (feed_codec->bit_rate < best_bitrate) {
  1061. best_bitrate = feed_codec->bit_rate;
  1062. best = i;
  1063. }
  1064. }
  1065. return best;
  1066. }
  1067. static int modify_current_stream(HTTPContext *c, char *rates)
  1068. {
  1069. int i;
  1070. FFServerStream *req = c->stream;
  1071. int action_required = 0;
  1072. /* Not much we can do for a feed */
  1073. if (!req->feed)
  1074. return 0;
  1075. for (i = 0; i < req->nb_streams; i++) {
  1076. AVCodecParameters *codec = req->streams[i]->codecpar;
  1077. switch(rates[i]) {
  1078. case 0:
  1079. c->switch_feed_streams[i] = req->feed_streams[i];
  1080. break;
  1081. case 1:
  1082. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
  1083. break;
  1084. case 2:
  1085. /* Wants off or slow */
  1086. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
  1087. #ifdef WANTS_OFF
  1088. /* This doesn't work well when it turns off the only stream! */
  1089. c->switch_feed_streams[i] = -2;
  1090. c->feed_streams[i] = -2;
  1091. #endif
  1092. break;
  1093. }
  1094. if (c->switch_feed_streams[i] >= 0 &&
  1095. c->switch_feed_streams[i] != c->feed_streams[i]) {
  1096. action_required = 1;
  1097. }
  1098. }
  1099. return action_required;
  1100. }
  1101. static void get_word(char *buf, int buf_size, const char **pp)
  1102. {
  1103. const char *p;
  1104. char *q;
  1105. #define SPACE_CHARS " \t\r\n"
  1106. p = *pp;
  1107. p += strspn(p, SPACE_CHARS);
  1108. q = buf;
  1109. while (!av_isspace(*p) && *p != '\0') {
  1110. if ((q - buf) < buf_size - 1)
  1111. *q++ = *p;
  1112. p++;
  1113. }
  1114. if (buf_size > 0)
  1115. *q = '\0';
  1116. *pp = p;
  1117. }
  1118. static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
  1119. HTTPContext *c)
  1120. {
  1121. FILE* f;
  1122. char line[1024];
  1123. char cmd[1024];
  1124. FFServerIPAddressACL *acl = NULL;
  1125. int line_num = 0;
  1126. const char *p;
  1127. f = fopen(stream->dynamic_acl, "r");
  1128. if (!f) {
  1129. perror(stream->dynamic_acl);
  1130. return NULL;
  1131. }
  1132. acl = av_mallocz(sizeof(FFServerIPAddressACL));
  1133. if (!acl) {
  1134. fclose(f);
  1135. return NULL;
  1136. }
  1137. /* Build ACL */
  1138. while (fgets(line, sizeof(line), f)) {
  1139. line_num++;
  1140. p = line;
  1141. while (av_isspace(*p))
  1142. p++;
  1143. if (*p == '\0' || *p == '#')
  1144. continue;
  1145. ffserver_get_arg(cmd, sizeof(cmd), &p);
  1146. if (!av_strcasecmp(cmd, "ACL"))
  1147. ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
  1148. line_num);
  1149. }
  1150. fclose(f);
  1151. return acl;
  1152. }
  1153. static void free_acl_list(FFServerIPAddressACL *in_acl)
  1154. {
  1155. FFServerIPAddressACL *pacl, *pacl2;
  1156. pacl = in_acl;
  1157. while(pacl) {
  1158. pacl2 = pacl;
  1159. pacl = pacl->next;
  1160. av_freep(pacl2);
  1161. }
  1162. }
  1163. static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
  1164. {
  1165. enum FFServerIPAddressAction last_action = IP_DENY;
  1166. FFServerIPAddressACL *acl;
  1167. struct in_addr *src = &c->from_addr.sin_addr;
  1168. unsigned long src_addr = src->s_addr;
  1169. for (acl = in_acl; acl; acl = acl->next) {
  1170. if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
  1171. return (acl->action == IP_ALLOW) ? 1 : 0;
  1172. last_action = acl->action;
  1173. }
  1174. /* Nothing matched, so return not the last action */
  1175. return (last_action == IP_DENY) ? 1 : 0;
  1176. }
  1177. static int validate_acl(FFServerStream *stream, HTTPContext *c)
  1178. {
  1179. int ret = 0;
  1180. FFServerIPAddressACL *acl;
  1181. /* if stream->acl is null validate_acl_list will return 1 */
  1182. ret = validate_acl_list(stream->acl, c);
  1183. if (stream->dynamic_acl[0]) {
  1184. acl = parse_dynamic_acl(stream, c);
  1185. ret = validate_acl_list(acl, c);
  1186. free_acl_list(acl);
  1187. }
  1188. return ret;
  1189. }
  1190. /**
  1191. * compute the real filename of a file by matching it without its
  1192. * extensions to all the stream's filenames
  1193. */
  1194. static void compute_real_filename(char *filename, int max_size)
  1195. {
  1196. char file1[1024];
  1197. char file2[1024];
  1198. char *p;
  1199. FFServerStream *stream;
  1200. av_strlcpy(file1, filename, sizeof(file1));
  1201. p = strrchr(file1, '.');
  1202. if (p)
  1203. *p = '\0';
  1204. for(stream = config.first_stream; stream; stream = stream->next) {
  1205. av_strlcpy(file2, stream->filename, sizeof(file2));
  1206. p = strrchr(file2, '.');
  1207. if (p)
  1208. *p = '\0';
  1209. if (!strcmp(file1, file2)) {
  1210. av_strlcpy(filename, stream->filename, max_size);
  1211. break;
  1212. }
  1213. }
  1214. }
  1215. enum RedirType {
  1216. REDIR_NONE,
  1217. REDIR_ASX,
  1218. REDIR_RAM,
  1219. REDIR_ASF,
  1220. REDIR_RTSP,
  1221. REDIR_SDP,
  1222. };
  1223. /* parse HTTP request and prepare header */
  1224. static int http_parse_request(HTTPContext *c)
  1225. {
  1226. const char *p;
  1227. char *p1;
  1228. enum RedirType redir_type;
  1229. char cmd[32];
  1230. char info[1024], filename[1024];
  1231. char url[1024], *q;
  1232. char protocol[32];
  1233. char msg[1024];
  1234. char *encoded_msg = NULL;
  1235. const char *mime_type;
  1236. FFServerStream *stream;
  1237. int i;
  1238. char ratebuf[32];
  1239. const char *useragent = 0;
  1240. p = c->buffer;
  1241. get_word(cmd, sizeof(cmd), &p);
  1242. av_strlcpy(c->method, cmd, sizeof(c->method));
  1243. if (!strcmp(cmd, "GET"))
  1244. c->post = 0;
  1245. else if (!strcmp(cmd, "POST"))
  1246. c->post = 1;
  1247. else
  1248. return -1;
  1249. get_word(url, sizeof(url), &p);
  1250. av_strlcpy(c->url, url, sizeof(c->url));
  1251. get_word(protocol, sizeof(protocol), (const char **)&p);
  1252. if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
  1253. return -1;
  1254. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  1255. if (config.debug)
  1256. http_log("%s - - New connection: %s %s\n",
  1257. inet_ntoa(c->from_addr.sin_addr), cmd, url);
  1258. /* find the filename and the optional info string in the request */
  1259. p1 = strchr(url, '?');
  1260. if (p1) {
  1261. av_strlcpy(info, p1, sizeof(info));
  1262. *p1 = '\0';
  1263. } else
  1264. info[0] = '\0';
  1265. av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
  1266. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1267. if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
  1268. useragent = p + 11;
  1269. if (*useragent && *useragent != '\n' && av_isspace(*useragent))
  1270. useragent++;
  1271. break;
  1272. }
  1273. p = strchr(p, '\n');
  1274. if (!p)
  1275. break;
  1276. p++;
  1277. }
  1278. redir_type = REDIR_NONE;
  1279. if (av_match_ext(filename, "asx")) {
  1280. redir_type = REDIR_ASX;
  1281. filename[strlen(filename)-1] = 'f';
  1282. } else if (av_match_ext(filename, "asf") &&
  1283. (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
  1284. /* if this isn't WMP or lookalike, return the redirector file */
  1285. redir_type = REDIR_ASF;
  1286. } else if (av_match_ext(filename, "rpm,ram")) {
  1287. redir_type = REDIR_RAM;
  1288. strcpy(filename + strlen(filename)-2, "m");
  1289. } else if (av_match_ext(filename, "rtsp")) {
  1290. redir_type = REDIR_RTSP;
  1291. compute_real_filename(filename, sizeof(filename) - 1);
  1292. } else if (av_match_ext(filename, "sdp")) {
  1293. redir_type = REDIR_SDP;
  1294. compute_real_filename(filename, sizeof(filename) - 1);
  1295. }
  1296. /* "redirect" request to index.html */
  1297. if (!strlen(filename))
  1298. av_strlcpy(filename, "index.html", sizeof(filename) - 1);
  1299. stream = config.first_stream;
  1300. while (stream) {
  1301. if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
  1302. break;
  1303. stream = stream->next;
  1304. }
  1305. if (!stream) {
  1306. snprintf(msg, sizeof(msg), "File '%s' not found", url);
  1307. http_log("File '%s' not found\n", url);
  1308. goto send_error;
  1309. }
  1310. c->stream = stream;
  1311. memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
  1312. memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
  1313. if (stream->stream_type == STREAM_TYPE_REDIRECT) {
  1314. c->http_error = 301;
  1315. q = c->buffer;
  1316. snprintf(q, c->buffer_size,
  1317. "HTTP/1.0 301 Moved\r\n"
  1318. "Location: %s\r\n"
  1319. "Content-type: text/html\r\n"
  1320. "\r\n"
  1321. "<!DOCTYPE html>\n"
  1322. "<html><head><title>Moved</title></head><body>\r\n"
  1323. "You should be <a href=\"%s\">redirected</a>.\r\n"
  1324. "</body></html>\r\n",
  1325. stream->feed_filename, stream->feed_filename);
  1326. q += strlen(q);
  1327. /* prepare output buffer */
  1328. c->buffer_ptr = c->buffer;
  1329. c->buffer_end = q;
  1330. c->state = HTTPSTATE_SEND_HEADER;
  1331. return 0;
  1332. }
  1333. /* If this is WMP, get the rate information */
  1334. if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1335. if (modify_current_stream(c, ratebuf)) {
  1336. for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
  1337. if (c->switch_feed_streams[i] >= 0)
  1338. c->switch_feed_streams[i] = -1;
  1339. }
  1340. }
  1341. }
  1342. if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
  1343. current_bandwidth += stream->bandwidth;
  1344. /* If already streaming this feed, do not let another feeder start */
  1345. if (stream->feed_opened) {
  1346. snprintf(msg, sizeof(msg), "This feed is already being received.");
  1347. http_log("Feed '%s' already being received\n", stream->feed_filename);
  1348. goto send_error;
  1349. }
  1350. if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
  1351. c->http_error = 503;
  1352. q = c->buffer;
  1353. snprintf(q, c->buffer_size,
  1354. "HTTP/1.0 503 Server too busy\r\n"
  1355. "Content-type: text/html\r\n"
  1356. "\r\n"
  1357. "<!DOCTYPE html>\n"
  1358. "<html><head><title>Too busy</title></head><body>\r\n"
  1359. "<p>The server is too busy to serve your request at "
  1360. "this time.</p>\r\n"
  1361. "<p>The bandwidth being served (including your stream) "
  1362. "is %"PRIu64"kbit/s, and this exceeds the limit of "
  1363. "%"PRIu64"kbit/s.</p>\r\n"
  1364. "</body></html>\r\n",
  1365. current_bandwidth, config.max_bandwidth);
  1366. q += strlen(q);
  1367. /* prepare output buffer */
  1368. c->buffer_ptr = c->buffer;
  1369. c->buffer_end = q;
  1370. c->state = HTTPSTATE_SEND_HEADER;
  1371. return 0;
  1372. }
  1373. if (redir_type != REDIR_NONE) {
  1374. const char *hostinfo = 0;
  1375. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1376. if (av_strncasecmp(p, "Host:", 5) == 0) {
  1377. hostinfo = p + 5;
  1378. break;
  1379. }
  1380. p = strchr(p, '\n');
  1381. if (!p)
  1382. break;
  1383. p++;
  1384. }
  1385. if (hostinfo) {
  1386. char *eoh;
  1387. char hostbuf[260];
  1388. while (av_isspace(*hostinfo))
  1389. hostinfo++;
  1390. eoh = strchr(hostinfo, '\n');
  1391. if (eoh) {
  1392. if (eoh[-1] == '\r')
  1393. eoh--;
  1394. if (eoh - hostinfo < sizeof(hostbuf) - 1) {
  1395. memcpy(hostbuf, hostinfo, eoh - hostinfo);
  1396. hostbuf[eoh - hostinfo] = 0;
  1397. c->http_error = 200;
  1398. q = c->buffer;
  1399. switch(redir_type) {
  1400. case REDIR_ASX:
  1401. snprintf(q, c->buffer_size,
  1402. "HTTP/1.0 200 ASX Follows\r\n"
  1403. "Content-type: video/x-ms-asf\r\n"
  1404. "\r\n"
  1405. "<ASX Version=\"3\">\r\n"
  1406. //"<!-- Autogenerated by ffserver -->\r\n"
  1407. "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
  1408. "</ASX>\r\n", hostbuf, filename, info);
  1409. q += strlen(q);
  1410. break;
  1411. case REDIR_RAM:
  1412. snprintf(q, c->buffer_size,
  1413. "HTTP/1.0 200 RAM Follows\r\n"
  1414. "Content-type: audio/x-pn-realaudio\r\n"
  1415. "\r\n"
  1416. "# Autogenerated by ffserver\r\n"
  1417. "http://%s/%s%s\r\n", hostbuf, filename, info);
  1418. q += strlen(q);
  1419. break;
  1420. case REDIR_ASF:
  1421. snprintf(q, c->buffer_size,
  1422. "HTTP/1.0 200 ASF Redirect follows\r\n"
  1423. "Content-type: video/x-ms-asf\r\n"
  1424. "\r\n"
  1425. "[Reference]\r\n"
  1426. "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
  1427. q += strlen(q);
  1428. break;
  1429. case REDIR_RTSP:
  1430. {
  1431. char hostname[256], *p;
  1432. /* extract only hostname */
  1433. av_strlcpy(hostname, hostbuf, sizeof(hostname));
  1434. p = strrchr(hostname, ':');
  1435. if (p)
  1436. *p = '\0';
  1437. snprintf(q, c->buffer_size,
  1438. "HTTP/1.0 200 RTSP Redirect follows\r\n"
  1439. /* XXX: incorrect MIME type ? */
  1440. "Content-type: application/x-rtsp\r\n"
  1441. "\r\n"
  1442. "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
  1443. q += strlen(q);
  1444. }
  1445. break;
  1446. case REDIR_SDP:
  1447. {
  1448. uint8_t *sdp_data;
  1449. int sdp_data_size;
  1450. socklen_t len;
  1451. struct sockaddr_in my_addr;
  1452. snprintf(q, c->buffer_size,
  1453. "HTTP/1.0 200 OK\r\n"
  1454. "Content-type: application/sdp\r\n"
  1455. "\r\n");
  1456. q += strlen(q);
  1457. len = sizeof(my_addr);
  1458. /* XXX: Should probably fail? */
  1459. if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
  1460. http_log("getsockname() failed\n");
  1461. /* XXX: should use a dynamic buffer */
  1462. sdp_data_size = prepare_sdp_description(stream,
  1463. &sdp_data,
  1464. my_addr.sin_addr);
  1465. if (sdp_data_size > 0) {
  1466. memcpy(q, sdp_data, sdp_data_size);
  1467. q += sdp_data_size;
  1468. *q = '\0';
  1469. av_freep(&sdp_data);
  1470. }
  1471. }
  1472. break;
  1473. default:
  1474. abort();
  1475. break;
  1476. }
  1477. /* prepare output buffer */
  1478. c->buffer_ptr = c->buffer;
  1479. c->buffer_end = q;
  1480. c->state = HTTPSTATE_SEND_HEADER;
  1481. return 0;
  1482. }
  1483. }
  1484. }
  1485. snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
  1486. goto send_error;
  1487. }
  1488. stream->conns_served++;
  1489. /* XXX: add there authenticate and IP match */
  1490. if (c->post) {
  1491. /* if post, it means a feed is being sent */
  1492. if (!stream->is_feed) {
  1493. /* However it might be a status report from WMP! Let us log the
  1494. * data as it might come handy one day. */
  1495. const char *logline = 0;
  1496. int client_id = 0;
  1497. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1498. if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
  1499. logline = p;
  1500. break;
  1501. }
  1502. if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
  1503. client_id = strtol(p + 18, 0, 10);
  1504. p = strchr(p, '\n');
  1505. if (!p)
  1506. break;
  1507. p++;
  1508. }
  1509. if (logline) {
  1510. char *eol = strchr(logline, '\n');
  1511. logline += 17;
  1512. if (eol) {
  1513. if (eol[-1] == '\r')
  1514. eol--;
  1515. http_log("%.*s\n", (int) (eol - logline), logline);
  1516. c->suppress_log = 1;
  1517. }
  1518. }
  1519. #ifdef DEBUG
  1520. http_log("\nGot request:\n%s\n", c->buffer);
  1521. #endif
  1522. if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1523. HTTPContext *wmpc;
  1524. /* Now we have to find the client_id */
  1525. for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
  1526. if (wmpc->wmp_client_id == client_id)
  1527. break;
  1528. }
  1529. if (wmpc && modify_current_stream(wmpc, ratebuf))
  1530. wmpc->switch_pending = 1;
  1531. }
  1532. snprintf(msg, sizeof(msg), "POST command not handled");
  1533. c->stream = 0;
  1534. goto send_error;
  1535. }
  1536. if (http_start_receive_data(c) < 0) {
  1537. snprintf(msg, sizeof(msg), "could not open feed");
  1538. goto send_error;
  1539. }
  1540. c->http_error = 0;
  1541. c->state = HTTPSTATE_RECEIVE_DATA;
  1542. return 0;
  1543. }
  1544. #ifdef DEBUG
  1545. if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
  1546. http_log("\nGot request:\n%s\n", c->buffer);
  1547. #endif
  1548. if (c->stream->stream_type == STREAM_TYPE_STATUS)
  1549. goto send_status;
  1550. /* open input stream */
  1551. if (open_input_stream(c, info) < 0) {
  1552. snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
  1553. goto send_error;
  1554. }
  1555. /* prepare HTTP header */
  1556. c->buffer[0] = 0;
  1557. av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
  1558. mime_type = c->stream->fmt->mime_type;
  1559. if (!mime_type)
  1560. mime_type = "application/x-octet-stream";
  1561. av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
  1562. /* for asf, we need extra headers */
  1563. if (!strcmp(c->stream->fmt->name,"asf_stream")) {
  1564. /* Need to allocate a client id */
  1565. c->wmp_client_id = av_lfg_get(&random_state);
  1566. av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);
  1567. }
  1568. av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
  1569. av_strlcatf(c->buffer, c->buffer_size, "\r\n");
  1570. q = c->buffer + strlen(c->buffer);
  1571. /* prepare output buffer */
  1572. c->http_error = 0;
  1573. c->buffer_ptr = c->buffer;
  1574. c->buffer_end = q;
  1575. c->state = HTTPSTATE_SEND_HEADER;
  1576. return 0;
  1577. send_error:
  1578. c->http_error = 404;
  1579. q = c->buffer;
  1580. if (!htmlencode(msg, &encoded_msg)) {
  1581. http_log("Could not encode filename '%s' as HTML\n", msg);
  1582. }
  1583. snprintf(q, c->buffer_size,
  1584. "HTTP/1.0 404 Not Found\r\n"
  1585. "Content-type: text/html\r\n"
  1586. "\r\n"
  1587. "<!DOCTYPE html>\n"
  1588. "<html>\n"
  1589. "<head>\n"
  1590. "<meta charset=\"UTF-8\">\n"
  1591. "<title>404 Not Found</title>\n"
  1592. "</head>\n"
  1593. "<body>%s</body>\n"
  1594. "</html>\n", encoded_msg? encoded_msg : "File not found");
  1595. q += strlen(q);
  1596. /* prepare output buffer */
  1597. c->buffer_ptr = c->buffer;
  1598. c->buffer_end = q;
  1599. c->state = HTTPSTATE_SEND_HEADER;
  1600. av_freep(&encoded_msg);
  1601. return 0;
  1602. send_status:
  1603. compute_status(c);
  1604. /* horrible: we use this value to avoid
  1605. * going to the send data state */
  1606. c->http_error = 200;
  1607. c->state = HTTPSTATE_SEND_HEADER;
  1608. return 0;
  1609. }
  1610. static void fmt_bytecount(AVIOContext *pb, int64_t count)
  1611. {
  1612. static const char suffix[] = " kMGTP";
  1613. const char *s;
  1614. for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
  1615. avio_printf(pb, "%"PRId64"%c", count, *s);
  1616. }
  1617. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
  1618. {
  1619. int i, stream_no;
  1620. const char *type = "unknown";
  1621. char parameters[64];
  1622. LayeredAVStream *st;
  1623. AVCodec *codec;
  1624. stream_no = stream->nb_streams;
  1625. avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
  1626. "type<th>kbit/s<th align=left>codec<th align=left>"
  1627. "Parameters\n");
  1628. for (i = 0; i < stream_no; i++) {
  1629. st = stream->streams[i];
  1630. codec = avcodec_find_encoder(st->codecpar->codec_id);
  1631. parameters[0] = 0;
  1632. switch(st->codecpar->codec_type) {
  1633. case AVMEDIA_TYPE_AUDIO:
  1634. type = "audio";
  1635. snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
  1636. st->codecpar->channels, st->codecpar->sample_rate);
  1637. break;
  1638. case AVMEDIA_TYPE_VIDEO:
  1639. type = "video";
  1640. snprintf(parameters, sizeof(parameters),
  1641. "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
  1642. st->codecpar->height, st->codec->qmin, st->codec->qmax,
  1643. st->time_base.den / st->time_base.num);
  1644. break;
  1645. default:
  1646. abort();
  1647. }
  1648. avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
  1649. "<td>%s<td>%s\n",
  1650. i, type, (int64_t)st->codecpar->bit_rate/1000,
  1651. codec ? codec->name : "", parameters);
  1652. }
  1653. avio_printf(pb, "</table>\n");
  1654. }
  1655. static void clean_html(char *clean, int clean_len, char *dirty)
  1656. {
  1657. int i, o;
  1658. for (o = i = 0; o+10 < clean_len && dirty[i];) {
  1659. int len = strspn(dirty+i, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*(),?/ :;%");
  1660. if (len) {
  1661. if (o + len >= clean_len)
  1662. break;
  1663. memcpy(clean + o, dirty + i, len);
  1664. i += len;
  1665. o += len;
  1666. } else {
  1667. int c = dirty[i++];
  1668. switch (c) {
  1669. case '&': av_strlcat(clean+o, "&amp;" , clean_len - o); break;
  1670. case '<': av_strlcat(clean+o, "&lt;" , clean_len - o); break;
  1671. case '>': av_strlcat(clean+o, "&gt;" , clean_len - o); break;
  1672. case '\'': av_strlcat(clean+o, "&apos;" , clean_len - o); break;
  1673. case '\"': av_strlcat(clean+o, "&quot;" , clean_len - o); break;
  1674. default: av_strlcat(clean+o, "&#9785;", clean_len - o); break;
  1675. }
  1676. o += strlen(clean+o);
  1677. }
  1678. }
  1679. clean[o] = 0;
  1680. }
  1681. static void compute_status(HTTPContext *c)
  1682. {
  1683. HTTPContext *c1;
  1684. FFServerStream *stream;
  1685. char *p;
  1686. time_t ti;
  1687. int i, len;
  1688. AVIOContext *pb;
  1689. if (avio_open_dyn_buf(&pb) < 0) {
  1690. /* XXX: return an error ? */
  1691. c->buffer_ptr = c->buffer;
  1692. c->buffer_end = c->buffer;
  1693. return;
  1694. }
  1695. avio_printf(pb, "HTTP/1.0 200 OK\r\n");
  1696. avio_printf(pb, "Content-type: text/html\r\n");
  1697. avio_printf(pb, "Pragma: no-cache\r\n");
  1698. avio_printf(pb, "\r\n");
  1699. avio_printf(pb, "<!DOCTYPE html>\n");
  1700. avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
  1701. if (c->stream->feed_filename[0])
  1702. avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
  1703. c->stream->feed_filename);
  1704. avio_printf(pb, "</head>\n<body>");
  1705. avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
  1706. /* format status */
  1707. avio_printf(pb, "<h2>Available Streams</h2>\n");
  1708. avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
  1709. avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbit/s<th align=left>Video<br>kbit/s<th><br>Codec<th align=left>Audio<br>kbit/s<th><br>Codec<th align=left valign=top>Feed\n");
  1710. stream = config.first_stream;
  1711. while (stream) {
  1712. char sfilename[1024];
  1713. char *eosf;
  1714. if (stream->feed == stream) {
  1715. stream = stream->next;
  1716. continue;
  1717. }
  1718. av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
  1719. eosf = sfilename + strlen(sfilename);
  1720. if (eosf - sfilename >= 4) {
  1721. if (strcmp(eosf - 4, ".asf") == 0)
  1722. strcpy(eosf - 4, ".asx");
  1723. else if (strcmp(eosf - 3, ".rm") == 0)
  1724. strcpy(eosf - 3, ".ram");
  1725. else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
  1726. /* generate a sample RTSP director if
  1727. * unicast. Generate an SDP redirector if
  1728. * multicast */
  1729. eosf = strrchr(sfilename, '.');
  1730. if (!eosf)
  1731. eosf = sfilename + strlen(sfilename);
  1732. if (stream->is_multicast)
  1733. strcpy(eosf, ".sdp");
  1734. else
  1735. strcpy(eosf, ".rtsp");
  1736. }
  1737. }
  1738. avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
  1739. sfilename, stream->filename);
  1740. avio_printf(pb, "<td align=right> %d <td align=right> ",
  1741. stream->conns_served);
  1742. // TODO: Investigate if we can make http bitexact so it always produces the same count of bytes
  1743. if (!config.bitexact)
  1744. fmt_bytecount(pb, stream->bytes_served);
  1745. switch(stream->stream_type) {
  1746. case STREAM_TYPE_LIVE: {
  1747. int audio_bit_rate = 0;
  1748. int video_bit_rate = 0;
  1749. const char *audio_codec_name = "";
  1750. const char *video_codec_name = "";
  1751. const char *audio_codec_name_extra = "";
  1752. const char *video_codec_name_extra = "";
  1753. for(i=0;i<stream->nb_streams;i++) {
  1754. LayeredAVStream *st = stream->streams[i];
  1755. AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
  1756. switch(st->codecpar->codec_type) {
  1757. case AVMEDIA_TYPE_AUDIO:
  1758. audio_bit_rate += st->codecpar->bit_rate;
  1759. if (codec) {
  1760. if (*audio_codec_name)
  1761. audio_codec_name_extra = "...";
  1762. audio_codec_name = codec->name;
  1763. }
  1764. break;
  1765. case AVMEDIA_TYPE_VIDEO:
  1766. video_bit_rate += st->codecpar->bit_rate;
  1767. if (codec) {
  1768. if (*video_codec_name)
  1769. video_codec_name_extra = "...";
  1770. video_codec_name = codec->name;
  1771. }
  1772. break;
  1773. case AVMEDIA_TYPE_DATA:
  1774. video_bit_rate += st->codecpar->bit_rate;
  1775. break;
  1776. default:
  1777. abort();
  1778. }
  1779. }
  1780. avio_printf(pb, "<td align=center> %s <td align=right> %d "
  1781. "<td align=right> %d <td> %s %s <td align=right> "
  1782. "%d <td> %s %s",
  1783. stream->fmt->name, stream->bandwidth,
  1784. video_bit_rate / 1000, video_codec_name,
  1785. video_codec_name_extra, audio_bit_rate / 1000,
  1786. audio_codec_name, audio_codec_name_extra);
  1787. if (stream->feed)
  1788. avio_printf(pb, "<td>%s", stream->feed->filename);
  1789. else
  1790. avio_printf(pb, "<td>%s", stream->feed_filename);
  1791. avio_printf(pb, "\n");
  1792. }
  1793. break;
  1794. default:
  1795. avio_printf(pb, "<td align=center> - <td align=right> - "
  1796. "<td align=right> - <td><td align=right> - <td>\n");
  1797. break;
  1798. }
  1799. stream = stream->next;
  1800. }
  1801. avio_printf(pb, "</table>\n");
  1802. stream = config.first_stream;
  1803. while (stream) {
  1804. if (stream->feed != stream) {
  1805. stream = stream->next;
  1806. continue;
  1807. }
  1808. avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
  1809. if (stream->pid) {
  1810. avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
  1811. #if defined(linux)
  1812. {
  1813. FILE *pid_stat;
  1814. char ps_cmd[64];
  1815. /* This is somewhat linux specific I guess */
  1816. snprintf(ps_cmd, sizeof(ps_cmd),
  1817. "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
  1818. (int64_t) stream->pid);
  1819. pid_stat = popen(ps_cmd, "r");
  1820. if (pid_stat) {
  1821. char cpuperc[10];
  1822. char cpuused[64];
  1823. if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
  1824. avio_printf(pb, "Currently using %s%% of the cpu. "
  1825. "Total time used %s.\n",
  1826. cpuperc, cpuused);
  1827. }
  1828. fclose(pid_stat);
  1829. }
  1830. }
  1831. #endif
  1832. avio_printf(pb, "<p>");
  1833. }
  1834. print_stream_params(pb, stream);
  1835. stream = stream->next;
  1836. }
  1837. /* connection status */
  1838. avio_printf(pb, "<h2>Connection Status</h2>\n");
  1839. avio_printf(pb, "Number of connections: %d / %d<br>\n",
  1840. nb_connections, config.nb_max_connections);
  1841. avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
  1842. current_bandwidth, config.max_bandwidth);
  1843. avio_printf(pb, "<table>\n");
  1844. avio_printf(pb, "<tr><th>#<th>File<th>IP<th>URL<th>Proto<th>State<th>Target "
  1845. "bit/s<th>Actual bit/s<th>Bytes transferred\n");
  1846. c1 = first_http_ctx;
  1847. i = 0;
  1848. while (c1) {
  1849. int bitrate;
  1850. int j;
  1851. bitrate = 0;
  1852. if (c1->stream) {
  1853. for (j = 0; j < c1->stream->nb_streams; j++) {
  1854. if (!c1->stream->feed)
  1855. bitrate += c1->stream->streams[j]->codecpar->bit_rate;
  1856. else if (c1->feed_streams[j] >= 0)
  1857. bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
  1858. }
  1859. }
  1860. i++;
  1861. p = inet_ntoa(c1->from_addr.sin_addr);
  1862. clean_html(c1->clean_url, sizeof(c1->clean_url), c1->url);
  1863. avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td>%s"
  1864. "<td align=right>",
  1865. i, c1->stream ? c1->stream->filename : "",
  1866. c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
  1867. p,
  1868. c1->clean_url,
  1869. c1->protocol, http_state[c1->state]);
  1870. fmt_bytecount(pb, bitrate);
  1871. avio_printf(pb, "<td align=right>");
  1872. fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
  1873. avio_printf(pb, "<td align=right>");
  1874. fmt_bytecount(pb, c1->data_count);
  1875. avio_printf(pb, "\n");
  1876. c1 = c1->next;
  1877. }
  1878. avio_printf(pb, "</table>\n");
  1879. if (!config.bitexact) {
  1880. /* date */
  1881. ti = time(NULL);
  1882. p = ctime(&ti);
  1883. avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
  1884. }
  1885. avio_printf(pb, "</body>\n</html>\n");
  1886. len = avio_close_dyn_buf(pb, &c->pb_buffer);
  1887. c->buffer_ptr = c->pb_buffer;
  1888. c->buffer_end = c->pb_buffer + len;
  1889. }
  1890. static int open_input_stream(HTTPContext *c, const char *info)
  1891. {
  1892. char buf[128];
  1893. char input_filename[1024];
  1894. AVFormatContext *s = NULL;
  1895. int buf_size, i, ret;
  1896. int64_t stream_pos;
  1897. /* find file name */
  1898. if (c->stream->feed) {
  1899. strcpy(input_filename, c->stream->feed->feed_filename);
  1900. buf_size = FFM_PACKET_SIZE;
  1901. /* compute position (absolute time) */
  1902. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1903. if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
  1904. http_log("Invalid date specification '%s' for stream\n", buf);
  1905. return ret;
  1906. }
  1907. } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
  1908. int prebuffer = strtol(buf, 0, 10);
  1909. stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
  1910. } else
  1911. stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
  1912. } else {
  1913. strcpy(input_filename, c->stream->feed_filename);
  1914. buf_size = 0;
  1915. /* compute position (relative time) */
  1916. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1917. if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
  1918. http_log("Invalid date specification '%s' for stream\n", buf);
  1919. return ret;
  1920. }
  1921. } else
  1922. stream_pos = 0;
  1923. }
  1924. if (!input_filename[0]) {
  1925. http_log("No filename was specified for stream\n");
  1926. return AVERROR(EINVAL);
  1927. }
  1928. /* open stream */
  1929. ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
  1930. &c->stream->in_opts);
  1931. if (ret < 0) {
  1932. http_log("Could not open input '%s': %s\n",
  1933. input_filename, av_err2str(ret));
  1934. return ret;
  1935. }
  1936. /* set buffer size */
  1937. if (buf_size > 0) {
  1938. ret = ffio_set_buf_size(s->pb, buf_size);
  1939. if (ret < 0) {
  1940. http_log("Failed to set buffer size\n");
  1941. return ret;
  1942. }
  1943. }
  1944. s->flags |= AVFMT_FLAG_GENPTS;
  1945. c->fmt_in = s;
  1946. if (strcmp(s->iformat->name, "ffm") &&
  1947. (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
  1948. http_log("Could not find stream info for input '%s'\n", input_filename);
  1949. avformat_close_input(&s);
  1950. return ret;
  1951. }
  1952. /* choose stream as clock source (we favor the video stream if
  1953. * present) for packet sending */
  1954. c->pts_stream_index = 0;
  1955. for(i=0;i<c->stream->nb_streams;i++) {
  1956. if (c->pts_stream_index == 0 &&
  1957. c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1958. c->pts_stream_index = i;
  1959. }
  1960. }
  1961. if (c->fmt_in->iformat->read_seek)
  1962. av_seek_frame(c->fmt_in, -1, stream_pos, 0);
  1963. /* set the start time (needed for maxtime and RTP packet timing) */
  1964. c->start_time = cur_time;
  1965. c->first_pts = AV_NOPTS_VALUE;
  1966. return 0;
  1967. }
  1968. /* return the server clock (in us) */
  1969. static int64_t get_server_clock(HTTPContext *c)
  1970. {
  1971. /* compute current pts value from system time */
  1972. return (cur_time - c->start_time) * 1000;
  1973. }
  1974. /* return the estimated time (in us) at which the current packet must be sent */
  1975. static int64_t get_packet_send_clock(HTTPContext *c)
  1976. {
  1977. int bytes_left, bytes_sent, frame_bytes;
  1978. frame_bytes = c->cur_frame_bytes;
  1979. if (frame_bytes <= 0)
  1980. return c->cur_pts;
  1981. bytes_left = c->buffer_end - c->buffer_ptr;
  1982. bytes_sent = frame_bytes - bytes_left;
  1983. return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
  1984. }
  1985. static int http_prepare_data(HTTPContext *c)
  1986. {
  1987. int i, len, ret;
  1988. AVFormatContext *ctx;
  1989. av_freep(&c->pb_buffer);
  1990. switch(c->state) {
  1991. case HTTPSTATE_SEND_DATA_HEADER:
  1992. ctx = avformat_alloc_context();
  1993. if (!ctx)
  1994. return AVERROR(ENOMEM);
  1995. c->pfmt_ctx = ctx;
  1996. av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
  1997. for(i=0;i<c->stream->nb_streams;i++) {
  1998. LayeredAVStream *src;
  1999. AVStream *st = avformat_new_stream(c->pfmt_ctx, NULL);
  2000. if (!st)
  2001. return AVERROR(ENOMEM);
  2002. /* if file or feed, then just take streams from FFServerStream
  2003. * struct */
  2004. if (!c->stream->feed ||
  2005. c->stream->feed == c->stream)
  2006. src = c->stream->streams[i];
  2007. else
  2008. src = c->stream->feed->streams[c->stream->feed_streams[i]];
  2009. unlayer_stream(c->pfmt_ctx->streams[i], src); //TODO we no longer copy st->internal, does this matter?
  2010. av_assert0(!c->pfmt_ctx->streams[i]->priv_data);
  2011. }
  2012. /* set output format parameters */
  2013. c->pfmt_ctx->oformat = c->stream->fmt;
  2014. av_assert0(c->pfmt_ctx->nb_streams == c->stream->nb_streams);
  2015. c->got_key_frame = 0;
  2016. /* prepare header and save header data in a stream */
  2017. if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
  2018. /* XXX: potential leak */
  2019. return -1;
  2020. }
  2021. c->pfmt_ctx->pb->seekable = 0;
  2022. /*
  2023. * HACK to avoid MPEG-PS muxer to spit many underflow errors
  2024. * Default value from FFmpeg
  2025. * Try to set it using configuration option
  2026. */
  2027. c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
  2028. if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
  2029. http_log("Error writing output header for stream '%s': %s\n",
  2030. c->stream->filename, av_err2str(ret));
  2031. return ret;
  2032. }
  2033. av_dict_free(&c->pfmt_ctx->metadata);
  2034. len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
  2035. c->buffer_ptr = c->pb_buffer;
  2036. c->buffer_end = c->pb_buffer + len;
  2037. c->state = HTTPSTATE_SEND_DATA;
  2038. c->last_packet_sent = 0;
  2039. break;
  2040. case HTTPSTATE_SEND_DATA:
  2041. /* find a new packet */
  2042. /* read a packet from the input stream */
  2043. if (c->stream->feed)
  2044. ffm_set_write_index(c->fmt_in,
  2045. c->stream->feed->feed_write_index,
  2046. c->stream->feed->feed_size);
  2047. if (c->stream->max_time &&
  2048. c->stream->max_time + c->start_time - cur_time < 0)
  2049. /* We have timed out */
  2050. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2051. else {
  2052. AVPacket pkt;
  2053. redo:
  2054. ret = av_read_frame(c->fmt_in, &pkt);
  2055. if (ret < 0) {
  2056. if (c->stream->feed) {
  2057. /* if coming from feed, it means we reached the end of the
  2058. * ffm file, so must wait for more data */
  2059. c->state = HTTPSTATE_WAIT_FEED;
  2060. return 1; /* state changed */
  2061. }
  2062. if (ret == AVERROR(EAGAIN)) {
  2063. /* input not ready, come back later */
  2064. return 0;
  2065. }
  2066. if (c->stream->loop) {
  2067. avformat_close_input(&c->fmt_in);
  2068. if (open_input_stream(c, "") < 0)
  2069. goto no_loop;
  2070. goto redo;
  2071. } else {
  2072. no_loop:
  2073. /* must send trailer now because EOF or error */
  2074. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2075. }
  2076. } else {
  2077. int source_index = pkt.stream_index;
  2078. /* update first pts if needed */
  2079. if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
  2080. c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
  2081. c->start_time = cur_time;
  2082. }
  2083. /* send it to the appropriate stream */
  2084. if (c->stream->feed) {
  2085. /* if coming from a feed, select the right stream */
  2086. if (c->switch_pending) {
  2087. c->switch_pending = 0;
  2088. for(i=0;i<c->stream->nb_streams;i++) {
  2089. if (c->switch_feed_streams[i] == pkt.stream_index)
  2090. if (pkt.flags & AV_PKT_FLAG_KEY)
  2091. c->switch_feed_streams[i] = -1;
  2092. if (c->switch_feed_streams[i] >= 0)
  2093. c->switch_pending = 1;
  2094. }
  2095. }
  2096. for(i=0;i<c->stream->nb_streams;i++) {
  2097. if (c->stream->feed_streams[i] == pkt.stream_index) {
  2098. AVStream *st = c->fmt_in->streams[source_index];
  2099. pkt.stream_index = i;
  2100. if (pkt.flags & AV_PKT_FLAG_KEY &&
  2101. (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  2102. c->stream->nb_streams == 1))
  2103. c->got_key_frame = 1;
  2104. if (!c->stream->send_on_key || c->got_key_frame)
  2105. goto send_it;
  2106. }
  2107. }
  2108. } else {
  2109. AVStream *ist, *ost;
  2110. send_it:
  2111. ist = c->fmt_in->streams[source_index];
  2112. /* specific handling for RTP: we use several
  2113. * output streams (one for each RTP connection).
  2114. * XXX: need more abstract handling */
  2115. if (c->is_packetized) {
  2116. /* compute send time and duration */
  2117. if (pkt.dts != AV_NOPTS_VALUE) {
  2118. c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
  2119. c->cur_pts -= c->first_pts;
  2120. }
  2121. c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
  2122. /* find RTP context */
  2123. c->packet_stream_index = pkt.stream_index;
  2124. ctx = c->rtp_ctx[c->packet_stream_index];
  2125. if(!ctx) {
  2126. av_packet_unref(&pkt);
  2127. break;
  2128. }
  2129. /* only one stream per RTP connection */
  2130. pkt.stream_index = 0;
  2131. } else {
  2132. ctx = c->pfmt_ctx;
  2133. /* Fudge here */
  2134. }
  2135. if (c->is_packetized) {
  2136. int max_packet_size;
  2137. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
  2138. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  2139. else
  2140. max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
  2141. ret = ffio_open_dyn_packet_buf(&ctx->pb,
  2142. max_packet_size);
  2143. } else
  2144. ret = avio_open_dyn_buf(&ctx->pb);
  2145. if (ret < 0) {
  2146. /* XXX: potential leak */
  2147. return -1;
  2148. }
  2149. ost = ctx->streams[pkt.stream_index];
  2150. ctx->pb->seekable = 0;
  2151. if (pkt.dts != AV_NOPTS_VALUE)
  2152. pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
  2153. ost->time_base);
  2154. if (pkt.pts != AV_NOPTS_VALUE)
  2155. pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
  2156. ost->time_base);
  2157. pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
  2158. ost->time_base);
  2159. if ((ret = av_write_frame(ctx, &pkt)) < 0) {
  2160. http_log("Error writing frame to output for stream '%s': %s\n",
  2161. c->stream->filename, av_err2str(ret));
  2162. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2163. }
  2164. av_freep(&c->pb_buffer);
  2165. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2166. ctx->pb = NULL;
  2167. c->cur_frame_bytes = len;
  2168. c->buffer_ptr = c->pb_buffer;
  2169. c->buffer_end = c->pb_buffer + len;
  2170. if (len == 0) {
  2171. av_packet_unref(&pkt);
  2172. goto redo;
  2173. }
  2174. }
  2175. av_packet_unref(&pkt);
  2176. }
  2177. }
  2178. break;
  2179. default:
  2180. case HTTPSTATE_SEND_DATA_TRAILER:
  2181. /* last packet test ? */
  2182. if (c->last_packet_sent || c->is_packetized)
  2183. return -1;
  2184. ctx = c->pfmt_ctx;
  2185. /* prepare header */
  2186. if (avio_open_dyn_buf(&ctx->pb) < 0) {
  2187. /* XXX: potential leak */
  2188. return -1;
  2189. }
  2190. c->pfmt_ctx->pb->seekable = 0;
  2191. av_write_trailer(ctx);
  2192. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2193. c->buffer_ptr = c->pb_buffer;
  2194. c->buffer_end = c->pb_buffer + len;
  2195. c->last_packet_sent = 1;
  2196. break;
  2197. }
  2198. return 0;
  2199. }
  2200. /* should convert the format at the same time */
  2201. /* send data starting at c->buffer_ptr to the output connection
  2202. * (either UDP or TCP)
  2203. */
  2204. static int http_send_data(HTTPContext *c)
  2205. {
  2206. int len, ret;
  2207. for(;;) {
  2208. if (c->buffer_ptr >= c->buffer_end) {
  2209. ret = http_prepare_data(c);
  2210. if (ret < 0)
  2211. return -1;
  2212. else if (ret)
  2213. /* state change requested */
  2214. break;
  2215. } else {
  2216. if (c->is_packetized) {
  2217. /* RTP data output */
  2218. len = c->buffer_end - c->buffer_ptr;
  2219. if (len < 4) {
  2220. /* fail safe - should never happen */
  2221. fail1:
  2222. c->buffer_ptr = c->buffer_end;
  2223. return 0;
  2224. }
  2225. len = (c->buffer_ptr[0] << 24) |
  2226. (c->buffer_ptr[1] << 16) |
  2227. (c->buffer_ptr[2] << 8) |
  2228. (c->buffer_ptr[3]);
  2229. if (len > (c->buffer_end - c->buffer_ptr))
  2230. goto fail1;
  2231. if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
  2232. /* nothing to send yet: we can wait */
  2233. return 0;
  2234. }
  2235. c->data_count += len;
  2236. update_datarate(&c->datarate, c->data_count);
  2237. if (c->stream)
  2238. c->stream->bytes_served += len;
  2239. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
  2240. /* RTP packets are sent inside the RTSP TCP connection */
  2241. AVIOContext *pb;
  2242. int interleaved_index, size;
  2243. uint8_t header[4];
  2244. HTTPContext *rtsp_c;
  2245. rtsp_c = c->rtsp_c;
  2246. /* if no RTSP connection left, error */
  2247. if (!rtsp_c)
  2248. return -1;
  2249. /* if already sending something, then wait. */
  2250. if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
  2251. break;
  2252. if (avio_open_dyn_buf(&pb) < 0)
  2253. goto fail1;
  2254. interleaved_index = c->packet_stream_index * 2;
  2255. /* RTCP packets are sent at odd indexes */
  2256. if (c->buffer_ptr[1] == 200)
  2257. interleaved_index++;
  2258. /* write RTSP TCP header */
  2259. header[0] = '$';
  2260. header[1] = interleaved_index;
  2261. header[2] = len >> 8;
  2262. header[3] = len;
  2263. avio_write(pb, header, 4);
  2264. /* write RTP packet data */
  2265. c->buffer_ptr += 4;
  2266. avio_write(pb, c->buffer_ptr, len);
  2267. size = avio_close_dyn_buf(pb, &c->packet_buffer);
  2268. /* prepare asynchronous TCP sending */
  2269. rtsp_c->packet_buffer_ptr = c->packet_buffer;
  2270. rtsp_c->packet_buffer_end = c->packet_buffer + size;
  2271. c->buffer_ptr += len;
  2272. /* send everything we can NOW */
  2273. len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
  2274. rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
  2275. if (len > 0)
  2276. rtsp_c->packet_buffer_ptr += len;
  2277. if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
  2278. /* if we could not send all the data, we will
  2279. * send it later, so a new state is needed to
  2280. * "lock" the RTSP TCP connection */
  2281. rtsp_c->state = RTSPSTATE_SEND_PACKET;
  2282. break;
  2283. } else
  2284. /* all data has been sent */
  2285. av_freep(&c->packet_buffer);
  2286. } else {
  2287. /* send RTP packet directly in UDP */
  2288. c->buffer_ptr += 4;
  2289. ffurl_write(c->rtp_handles[c->packet_stream_index],
  2290. c->buffer_ptr, len);
  2291. c->buffer_ptr += len;
  2292. /* here we continue as we can send several packets
  2293. * per 10 ms slot */
  2294. }
  2295. } else {
  2296. /* TCP data output */
  2297. len = send(c->fd, c->buffer_ptr,
  2298. c->buffer_end - c->buffer_ptr, 0);
  2299. if (len < 0) {
  2300. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2301. ff_neterrno() != AVERROR(EINTR))
  2302. /* error : close connection */
  2303. return -1;
  2304. else
  2305. return 0;
  2306. }
  2307. c->buffer_ptr += len;
  2308. c->data_count += len;
  2309. update_datarate(&c->datarate, c->data_count);
  2310. if (c->stream)
  2311. c->stream->bytes_served += len;
  2312. break;
  2313. }
  2314. }
  2315. } /* for(;;) */
  2316. return 0;
  2317. }
  2318. static int http_start_receive_data(HTTPContext *c)
  2319. {
  2320. int fd;
  2321. int ret;
  2322. int64_t ret64;
  2323. if (c->stream->feed_opened) {
  2324. http_log("Stream feed '%s' was not opened\n",
  2325. c->stream->feed_filename);
  2326. return AVERROR(EINVAL);
  2327. }
  2328. /* Don't permit writing to this one */
  2329. if (c->stream->readonly) {
  2330. http_log("Cannot write to read-only file '%s'\n",
  2331. c->stream->feed_filename);
  2332. return AVERROR(EINVAL);
  2333. }
  2334. /* open feed */
  2335. fd = open(c->stream->feed_filename, O_RDWR);
  2336. if (fd < 0) {
  2337. ret = AVERROR(errno);
  2338. http_log("Could not open feed file '%s': %s\n",
  2339. c->stream->feed_filename, strerror(errno));
  2340. return ret;
  2341. }
  2342. c->feed_fd = fd;
  2343. if (c->stream->truncate) {
  2344. /* truncate feed file */
  2345. ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
  2346. http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
  2347. if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
  2348. ret = AVERROR(errno);
  2349. http_log("Error truncating feed file '%s': %s\n",
  2350. c->stream->feed_filename, strerror(errno));
  2351. return ret;
  2352. }
  2353. } else {
  2354. ret64 = ffm_read_write_index(fd);
  2355. if (ret64 < 0) {
  2356. http_log("Error reading write index from feed file '%s': %s\n",
  2357. c->stream->feed_filename, strerror(errno));
  2358. return ret64;
  2359. }
  2360. c->stream->feed_write_index = ret64;
  2361. }
  2362. c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
  2363. FFM_PACKET_SIZE);
  2364. c->stream->feed_size = lseek(fd, 0, SEEK_END);
  2365. lseek(fd, 0, SEEK_SET);
  2366. /* init buffer input */
  2367. c->buffer_ptr = c->buffer;
  2368. c->buffer_end = c->buffer + FFM_PACKET_SIZE;
  2369. c->stream->feed_opened = 1;
  2370. c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
  2371. return 0;
  2372. }
  2373. static int http_receive_data(HTTPContext *c)
  2374. {
  2375. HTTPContext *c1;
  2376. int len, loop_run = 0;
  2377. while (c->chunked_encoding && !c->chunk_size &&
  2378. c->buffer_end > c->buffer_ptr) {
  2379. /* read chunk header, if present */
  2380. len = recv(c->fd, c->buffer_ptr, 1, 0);
  2381. if (len < 0) {
  2382. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2383. ff_neterrno() != AVERROR(EINTR))
  2384. /* error : close connection */
  2385. goto fail;
  2386. return 0;
  2387. } else if (len == 0) {
  2388. /* end of connection : close it */
  2389. goto fail;
  2390. } else if (c->buffer_ptr - c->buffer >= 2 &&
  2391. !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
  2392. c->chunk_size = strtol(c->buffer, 0, 16);
  2393. if (c->chunk_size == 0) // end of stream
  2394. goto fail;
  2395. c->buffer_ptr = c->buffer;
  2396. break;
  2397. } else if (++loop_run > 10)
  2398. /* no chunk header, abort */
  2399. goto fail;
  2400. else
  2401. c->buffer_ptr++;
  2402. }
  2403. if (c->buffer_end > c->buffer_ptr) {
  2404. len = recv(c->fd, c->buffer_ptr,
  2405. FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
  2406. if (len < 0) {
  2407. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2408. ff_neterrno() != AVERROR(EINTR))
  2409. /* error : close connection */
  2410. goto fail;
  2411. } else if (len == 0)
  2412. /* end of connection : close it */
  2413. goto fail;
  2414. else {
  2415. c->chunk_size -= len;
  2416. c->buffer_ptr += len;
  2417. c->data_count += len;
  2418. update_datarate(&c->datarate, c->data_count);
  2419. }
  2420. }
  2421. if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
  2422. if (c->buffer[0] != 'f' ||
  2423. c->buffer[1] != 'm') {
  2424. http_log("Feed stream has become desynchronized -- disconnecting\n");
  2425. goto fail;
  2426. }
  2427. }
  2428. if (c->buffer_ptr >= c->buffer_end) {
  2429. FFServerStream *feed = c->stream;
  2430. /* a packet has been received : write it in the store, except
  2431. * if header */
  2432. if (c->data_count > FFM_PACKET_SIZE) {
  2433. /* XXX: use llseek or url_seek
  2434. * XXX: Should probably fail? */
  2435. if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
  2436. http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
  2437. if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
  2438. http_log("Error writing to feed file: %s\n", strerror(errno));
  2439. goto fail;
  2440. }
  2441. feed->feed_write_index += FFM_PACKET_SIZE;
  2442. /* update file size */
  2443. if (feed->feed_write_index > c->stream->feed_size)
  2444. feed->feed_size = feed->feed_write_index;
  2445. /* handle wrap around if max file size reached */
  2446. if (c->stream->feed_max_size &&
  2447. feed->feed_write_index >= c->stream->feed_max_size)
  2448. feed->feed_write_index = FFM_PACKET_SIZE;
  2449. /* write index */
  2450. if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
  2451. http_log("Error writing index to feed file: %s\n",
  2452. strerror(errno));
  2453. goto fail;
  2454. }
  2455. /* wake up any waiting connections */
  2456. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2457. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2458. c1->stream->feed == c->stream->feed)
  2459. c1->state = HTTPSTATE_SEND_DATA;
  2460. }
  2461. } else {
  2462. /* We have a header in our hands that contains useful data */
  2463. AVFormatContext *s = avformat_alloc_context();
  2464. AVIOContext *pb;
  2465. AVInputFormat *fmt_in;
  2466. int i;
  2467. if (!s)
  2468. goto fail;
  2469. /* use feed output format name to find corresponding input format */
  2470. fmt_in = av_find_input_format(feed->fmt->name);
  2471. if (!fmt_in)
  2472. goto fail;
  2473. pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
  2474. 0, NULL, NULL, NULL, NULL);
  2475. if (!pb)
  2476. goto fail;
  2477. pb->seekable = 0;
  2478. s->pb = pb;
  2479. if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
  2480. av_freep(&pb);
  2481. goto fail;
  2482. }
  2483. /* Now we have the actual streams */
  2484. if (s->nb_streams != feed->nb_streams) {
  2485. avformat_close_input(&s);
  2486. av_freep(&pb);
  2487. http_log("Feed '%s' stream number does not match registered feed\n",
  2488. c->stream->feed_filename);
  2489. goto fail;
  2490. }
  2491. for (i = 0; i < s->nb_streams; i++) {
  2492. LayeredAVStream *fst = feed->streams[i];
  2493. AVStream *st = s->streams[i];
  2494. avcodec_copy_context(fst->codec, st->codec);
  2495. }
  2496. avformat_close_input(&s);
  2497. av_freep(&pb);
  2498. }
  2499. c->buffer_ptr = c->buffer;
  2500. }
  2501. return 0;
  2502. fail:
  2503. c->stream->feed_opened = 0;
  2504. close(c->feed_fd);
  2505. /* wake up any waiting connections to stop waiting for feed */
  2506. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2507. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2508. c1->stream->feed == c->stream->feed)
  2509. c1->state = HTTPSTATE_SEND_DATA_TRAILER;
  2510. }
  2511. return -1;
  2512. }
  2513. /********************************************************************/
  2514. /* RTSP handling */
  2515. static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
  2516. {
  2517. const char *str;
  2518. time_t ti;
  2519. struct tm *tm;
  2520. char buf2[32];
  2521. str = RTSP_STATUS_CODE2STRING(error_number);
  2522. if (!str)
  2523. str = "Unknown Error";
  2524. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
  2525. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2526. /* output GMT time */
  2527. ti = time(NULL);
  2528. tm = gmtime(&ti);
  2529. strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
  2530. avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
  2531. }
  2532. static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
  2533. {
  2534. rtsp_reply_header(c, error_number);
  2535. avio_printf(c->pb, "\r\n");
  2536. }
  2537. static int rtsp_parse_request(HTTPContext *c)
  2538. {
  2539. const char *p, *p1, *p2;
  2540. char cmd[32];
  2541. char url[1024];
  2542. char protocol[32];
  2543. char line[1024];
  2544. int len;
  2545. RTSPMessageHeader header1 = { 0 }, *header = &header1;
  2546. c->buffer_ptr[0] = '\0';
  2547. p = c->buffer;
  2548. get_word(cmd, sizeof(cmd), &p);
  2549. get_word(url, sizeof(url), &p);
  2550. get_word(protocol, sizeof(protocol), &p);
  2551. av_strlcpy(c->method, cmd, sizeof(c->method));
  2552. av_strlcpy(c->url, url, sizeof(c->url));
  2553. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  2554. if (avio_open_dyn_buf(&c->pb) < 0) {
  2555. /* XXX: cannot do more */
  2556. c->pb = NULL; /* safety */
  2557. return -1;
  2558. }
  2559. /* check version name */
  2560. if (strcmp(protocol, "RTSP/1.0")) {
  2561. rtsp_reply_error(c, RTSP_STATUS_VERSION);
  2562. goto the_end;
  2563. }
  2564. /* parse each header line */
  2565. /* skip to next line */
  2566. while (*p != '\n' && *p != '\0')
  2567. p++;
  2568. if (*p == '\n')
  2569. p++;
  2570. while (*p != '\0') {
  2571. p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
  2572. if (!p1)
  2573. break;
  2574. p2 = p1;
  2575. if (p2 > p && p2[-1] == '\r')
  2576. p2--;
  2577. /* skip empty line */
  2578. if (p2 == p)
  2579. break;
  2580. len = p2 - p;
  2581. if (len > sizeof(line) - 1)
  2582. len = sizeof(line) - 1;
  2583. memcpy(line, p, len);
  2584. line[len] = '\0';
  2585. ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
  2586. p = p1 + 1;
  2587. }
  2588. /* handle sequence number */
  2589. c->seq = header->seq;
  2590. if (!strcmp(cmd, "DESCRIBE"))
  2591. rtsp_cmd_describe(c, url);
  2592. else if (!strcmp(cmd, "OPTIONS"))
  2593. rtsp_cmd_options(c, url);
  2594. else if (!strcmp(cmd, "SETUP"))
  2595. rtsp_cmd_setup(c, url, header);
  2596. else if (!strcmp(cmd, "PLAY"))
  2597. rtsp_cmd_play(c, url, header);
  2598. else if (!strcmp(cmd, "PAUSE"))
  2599. rtsp_cmd_interrupt(c, url, header, 1);
  2600. else if (!strcmp(cmd, "TEARDOWN"))
  2601. rtsp_cmd_interrupt(c, url, header, 0);
  2602. else
  2603. rtsp_reply_error(c, RTSP_STATUS_METHOD);
  2604. the_end:
  2605. len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
  2606. c->pb = NULL; /* safety */
  2607. if (len < 0)
  2608. /* XXX: cannot do more */
  2609. return -1;
  2610. c->buffer_ptr = c->pb_buffer;
  2611. c->buffer_end = c->pb_buffer + len;
  2612. c->state = RTSPSTATE_SEND_REPLY;
  2613. return 0;
  2614. }
  2615. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  2616. struct in_addr my_ip)
  2617. {
  2618. AVFormatContext *avc;
  2619. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  2620. AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
  2621. int i;
  2622. *pbuffer = NULL;
  2623. avc = avformat_alloc_context();
  2624. if (!avc || !rtp_format)
  2625. return -1;
  2626. avc->oformat = rtp_format;
  2627. av_dict_set(&avc->metadata, "title",
  2628. entry ? entry->value : "No Title", 0);
  2629. if (stream->is_multicast) {
  2630. snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
  2631. inet_ntoa(stream->multicast_ip),
  2632. stream->multicast_port, stream->multicast_ttl);
  2633. } else
  2634. snprintf(avc->filename, 1024, "rtp://0.0.0.0");
  2635. for(i = 0; i < stream->nb_streams; i++) {
  2636. AVStream *st = avformat_new_stream(avc, NULL);
  2637. if (!st)
  2638. goto sdp_done;
  2639. avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
  2640. unlayer_stream(st, stream->streams[i]);
  2641. }
  2642. #define PBUFFER_SIZE 2048
  2643. *pbuffer = av_mallocz(PBUFFER_SIZE);
  2644. if (!*pbuffer)
  2645. goto sdp_done;
  2646. av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
  2647. sdp_done:
  2648. av_freep(&avc->streams);
  2649. av_dict_free(&avc->metadata);
  2650. av_free(avc);
  2651. return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
  2652. }
  2653. static void rtsp_cmd_options(HTTPContext *c, const char *url)
  2654. {
  2655. /* rtsp_reply_header(c, RTSP_STATUS_OK); */
  2656. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
  2657. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2658. avio_printf(c->pb, "Public: %s\r\n",
  2659. "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
  2660. avio_printf(c->pb, "\r\n");
  2661. }
  2662. static void rtsp_cmd_describe(HTTPContext *c, const char *url)
  2663. {
  2664. FFServerStream *stream;
  2665. char path1[1024];
  2666. const char *path;
  2667. uint8_t *content;
  2668. int content_length;
  2669. socklen_t len;
  2670. struct sockaddr_in my_addr;
  2671. /* find which URL is asked */
  2672. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2673. path = path1;
  2674. if (*path == '/')
  2675. path++;
  2676. for(stream = config.first_stream; stream; stream = stream->next) {
  2677. if (!stream->is_feed &&
  2678. stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
  2679. !strcmp(path, stream->filename)) {
  2680. goto found;
  2681. }
  2682. }
  2683. /* no stream found */
  2684. rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
  2685. return;
  2686. found:
  2687. /* prepare the media description in SDP format */
  2688. /* get the host IP */
  2689. len = sizeof(my_addr);
  2690. getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
  2691. content_length = prepare_sdp_description(stream, &content,
  2692. my_addr.sin_addr);
  2693. if (content_length < 0) {
  2694. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2695. return;
  2696. }
  2697. rtsp_reply_header(c, RTSP_STATUS_OK);
  2698. avio_printf(c->pb, "Content-Base: %s/\r\n", url);
  2699. avio_printf(c->pb, "Content-Type: application/sdp\r\n");
  2700. avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
  2701. avio_printf(c->pb, "\r\n");
  2702. avio_write(c->pb, content, content_length);
  2703. av_free(content);
  2704. }
  2705. static HTTPContext *find_rtp_session(const char *session_id)
  2706. {
  2707. HTTPContext *c;
  2708. if (session_id[0] == '\0')
  2709. return NULL;
  2710. for(c = first_http_ctx; c; c = c->next) {
  2711. if (!strcmp(c->session_id, session_id))
  2712. return c;
  2713. }
  2714. return NULL;
  2715. }
  2716. static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
  2717. {
  2718. RTSPTransportField *th;
  2719. int i;
  2720. for(i=0;i<h->nb_transports;i++) {
  2721. th = &h->transports[i];
  2722. if (th->lower_transport == lower_transport)
  2723. return th;
  2724. }
  2725. return NULL;
  2726. }
  2727. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  2728. RTSPMessageHeader *h)
  2729. {
  2730. FFServerStream *stream;
  2731. int stream_index, rtp_port, rtcp_port;
  2732. char buf[1024];
  2733. char path1[1024];
  2734. const char *path;
  2735. HTTPContext *rtp_c;
  2736. RTSPTransportField *th;
  2737. struct sockaddr_in dest_addr;
  2738. RTSPActionServerSetup setup;
  2739. /* find which URL is asked */
  2740. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2741. path = path1;
  2742. if (*path == '/')
  2743. path++;
  2744. /* now check each stream */
  2745. for(stream = config.first_stream; stream; stream = stream->next) {
  2746. if (stream->is_feed || !stream->fmt ||
  2747. strcmp(stream->fmt->name, "rtp")) {
  2748. continue;
  2749. }
  2750. /* accept aggregate filenames only if single stream */
  2751. if (!strcmp(path, stream->filename)) {
  2752. if (stream->nb_streams != 1) {
  2753. rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
  2754. return;
  2755. }
  2756. stream_index = 0;
  2757. goto found;
  2758. }
  2759. for(stream_index = 0; stream_index < stream->nb_streams;
  2760. stream_index++) {
  2761. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2762. stream->filename, stream_index);
  2763. if (!strcmp(path, buf))
  2764. goto found;
  2765. }
  2766. }
  2767. /* no stream found */
  2768. rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
  2769. return;
  2770. found:
  2771. /* generate session id if needed */
  2772. if (h->session_id[0] == '\0') {
  2773. unsigned random0 = av_lfg_get(&random_state);
  2774. unsigned random1 = av_lfg_get(&random_state);
  2775. snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
  2776. random0, random1);
  2777. }
  2778. /* find RTP session, and create it if none found */
  2779. rtp_c = find_rtp_session(h->session_id);
  2780. if (!rtp_c) {
  2781. /* always prefer UDP */
  2782. th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
  2783. if (!th) {
  2784. th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
  2785. if (!th) {
  2786. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2787. return;
  2788. }
  2789. }
  2790. rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
  2791. th->lower_transport);
  2792. if (!rtp_c) {
  2793. rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
  2794. return;
  2795. }
  2796. /* open input stream */
  2797. if (open_input_stream(rtp_c, "") < 0) {
  2798. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2799. return;
  2800. }
  2801. }
  2802. /* test if stream is OK (test needed because several SETUP needs
  2803. * to be done for a given file) */
  2804. if (rtp_c->stream != stream) {
  2805. rtsp_reply_error(c, RTSP_STATUS_SERVICE);
  2806. return;
  2807. }
  2808. /* test if stream is already set up */
  2809. if (rtp_c->rtp_ctx[stream_index]) {
  2810. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2811. return;
  2812. }
  2813. /* check transport */
  2814. th = find_transport(h, rtp_c->rtp_protocol);
  2815. if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  2816. th->client_port_min <= 0)) {
  2817. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2818. return;
  2819. }
  2820. /* setup default options */
  2821. setup.transport_option[0] = '\0';
  2822. dest_addr = rtp_c->from_addr;
  2823. dest_addr.sin_port = htons(th->client_port_min);
  2824. /* setup stream */
  2825. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
  2826. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2827. return;
  2828. }
  2829. /* now everything is OK, so we can send the connection parameters */
  2830. rtsp_reply_header(c, RTSP_STATUS_OK);
  2831. /* session ID */
  2832. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2833. switch(rtp_c->rtp_protocol) {
  2834. case RTSP_LOWER_TRANSPORT_UDP:
  2835. rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
  2836. rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
  2837. avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
  2838. "client_port=%d-%d;server_port=%d-%d",
  2839. th->client_port_min, th->client_port_max,
  2840. rtp_port, rtcp_port);
  2841. break;
  2842. case RTSP_LOWER_TRANSPORT_TCP:
  2843. avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
  2844. stream_index * 2, stream_index * 2 + 1);
  2845. break;
  2846. default:
  2847. break;
  2848. }
  2849. if (setup.transport_option[0] != '\0')
  2850. avio_printf(c->pb, ";%s", setup.transport_option);
  2851. avio_printf(c->pb, "\r\n");
  2852. avio_printf(c->pb, "\r\n");
  2853. }
  2854. /**
  2855. * find an RTP connection by using the session ID. Check consistency
  2856. * with filename
  2857. */
  2858. static HTTPContext *find_rtp_session_with_url(const char *url,
  2859. const char *session_id)
  2860. {
  2861. HTTPContext *rtp_c;
  2862. char path1[1024];
  2863. const char *path;
  2864. char buf[1024];
  2865. int s, len;
  2866. rtp_c = find_rtp_session(session_id);
  2867. if (!rtp_c)
  2868. return NULL;
  2869. /* find which URL is asked */
  2870. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2871. path = path1;
  2872. if (*path == '/')
  2873. path++;
  2874. if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
  2875. for(s=0; s<rtp_c->stream->nb_streams; ++s) {
  2876. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2877. rtp_c->stream->filename, s);
  2878. if(!strncmp(path, buf, sizeof(buf)))
  2879. /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
  2880. * if nb_streams>1? */
  2881. return rtp_c;
  2882. }
  2883. len = strlen(path);
  2884. if (len > 0 && path[len - 1] == '/' &&
  2885. !strncmp(path, rtp_c->stream->filename, len - 1))
  2886. return rtp_c;
  2887. return NULL;
  2888. }
  2889. static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
  2890. {
  2891. HTTPContext *rtp_c;
  2892. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2893. if (!rtp_c) {
  2894. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2895. return;
  2896. }
  2897. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2898. rtp_c->state != HTTPSTATE_WAIT_FEED &&
  2899. rtp_c->state != HTTPSTATE_READY) {
  2900. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2901. return;
  2902. }
  2903. rtp_c->state = HTTPSTATE_SEND_DATA;
  2904. /* now everything is OK, so we can send the connection parameters */
  2905. rtsp_reply_header(c, RTSP_STATUS_OK);
  2906. /* session ID */
  2907. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2908. avio_printf(c->pb, "\r\n");
  2909. }
  2910. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  2911. RTSPMessageHeader *h, int pause_only)
  2912. {
  2913. HTTPContext *rtp_c;
  2914. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2915. if (!rtp_c) {
  2916. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2917. return;
  2918. }
  2919. if (pause_only) {
  2920. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2921. rtp_c->state != HTTPSTATE_WAIT_FEED) {
  2922. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2923. return;
  2924. }
  2925. rtp_c->state = HTTPSTATE_READY;
  2926. rtp_c->first_pts = AV_NOPTS_VALUE;
  2927. }
  2928. /* now everything is OK, so we can send the connection parameters */
  2929. rtsp_reply_header(c, RTSP_STATUS_OK);
  2930. /* session ID */
  2931. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2932. avio_printf(c->pb, "\r\n");
  2933. if (!pause_only)
  2934. close_connection(rtp_c);
  2935. }
  2936. /********************************************************************/
  2937. /* RTP handling */
  2938. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  2939. FFServerStream *stream,
  2940. const char *session_id,
  2941. enum RTSPLowerTransport rtp_protocol)
  2942. {
  2943. HTTPContext *c = NULL;
  2944. const char *proto_str;
  2945. /* XXX: should output a warning page when coming
  2946. * close to the connection limit */
  2947. if (nb_connections >= config.nb_max_connections)
  2948. goto fail;
  2949. /* add a new connection */
  2950. c = av_mallocz(sizeof(HTTPContext));
  2951. if (!c)
  2952. goto fail;
  2953. c->fd = -1;
  2954. c->poll_entry = NULL;
  2955. c->from_addr = *from_addr;
  2956. c->buffer_size = IOBUFFER_INIT_SIZE;
  2957. c->buffer = av_malloc(c->buffer_size);
  2958. if (!c->buffer)
  2959. goto fail;
  2960. nb_connections++;
  2961. c->stream = stream;
  2962. av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
  2963. c->state = HTTPSTATE_READY;
  2964. c->is_packetized = 1;
  2965. c->rtp_protocol = rtp_protocol;
  2966. /* protocol is shown in statistics */
  2967. switch(c->rtp_protocol) {
  2968. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  2969. proto_str = "MCAST";
  2970. break;
  2971. case RTSP_LOWER_TRANSPORT_UDP:
  2972. proto_str = "UDP";
  2973. break;
  2974. case RTSP_LOWER_TRANSPORT_TCP:
  2975. proto_str = "TCP";
  2976. break;
  2977. default:
  2978. proto_str = "???";
  2979. break;
  2980. }
  2981. av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
  2982. av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
  2983. current_bandwidth += stream->bandwidth;
  2984. c->next = first_http_ctx;
  2985. first_http_ctx = c;
  2986. return c;
  2987. fail:
  2988. if (c) {
  2989. av_freep(&c->buffer);
  2990. av_free(c);
  2991. }
  2992. return NULL;
  2993. }
  2994. /**
  2995. * add a new RTP stream in an RTP connection (used in RTSP SETUP
  2996. * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
  2997. * used.
  2998. */
  2999. static int rtp_new_av_stream(HTTPContext *c,
  3000. int stream_index, struct sockaddr_in *dest_addr,
  3001. HTTPContext *rtsp_c)
  3002. {
  3003. AVFormatContext *ctx;
  3004. AVStream *st;
  3005. char *ipaddr;
  3006. URLContext *h = NULL;
  3007. uint8_t *dummy_buf;
  3008. int max_packet_size;
  3009. void *st_internal;
  3010. /* now we can open the relevant output stream */
  3011. ctx = avformat_alloc_context();
  3012. if (!ctx)
  3013. return -1;
  3014. ctx->oformat = av_guess_format("rtp", NULL, NULL);
  3015. st = avformat_new_stream(ctx, NULL);
  3016. if (!st)
  3017. goto fail;
  3018. st_internal = st->internal;
  3019. if (!c->stream->feed ||
  3020. c->stream->feed == c->stream)
  3021. unlayer_stream(st, c->stream->streams[stream_index]);
  3022. else
  3023. unlayer_stream(st,
  3024. c->stream->feed->streams[c->stream->feed_streams[stream_index]]);
  3025. av_assert0(st->priv_data == NULL);
  3026. av_assert0(st->internal == st_internal);
  3027. /* build destination RTP address */
  3028. ipaddr = inet_ntoa(dest_addr->sin_addr);
  3029. switch(c->rtp_protocol) {
  3030. case RTSP_LOWER_TRANSPORT_UDP:
  3031. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  3032. /* RTP/UDP case */
  3033. /* XXX: also pass as parameter to function ? */
  3034. if (c->stream->is_multicast) {
  3035. int ttl;
  3036. ttl = c->stream->multicast_ttl;
  3037. if (!ttl)
  3038. ttl = 16;
  3039. snprintf(ctx->filename, sizeof(ctx->filename),
  3040. "rtp://%s:%d?multicast=1&ttl=%d",
  3041. ipaddr, ntohs(dest_addr->sin_port), ttl);
  3042. } else {
  3043. snprintf(ctx->filename, sizeof(ctx->filename),
  3044. "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
  3045. }
  3046. if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
  3047. goto fail;
  3048. c->rtp_handles[stream_index] = h;
  3049. max_packet_size = h->max_packet_size;
  3050. break;
  3051. case RTSP_LOWER_TRANSPORT_TCP:
  3052. /* RTP/TCP case */
  3053. c->rtsp_c = rtsp_c;
  3054. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  3055. break;
  3056. default:
  3057. goto fail;
  3058. }
  3059. http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
  3060. ipaddr, ntohs(dest_addr->sin_port),
  3061. c->stream->filename, stream_index, c->protocol);
  3062. /* normally, no packets should be output here, but the packet size may
  3063. * be checked */
  3064. if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
  3065. /* XXX: close stream */
  3066. goto fail;
  3067. if (avformat_write_header(ctx, NULL) < 0) {
  3068. fail:
  3069. if (h)
  3070. ffurl_close(h);
  3071. av_free(st);
  3072. av_free(ctx);
  3073. return -1;
  3074. }
  3075. avio_close_dyn_buf(ctx->pb, &dummy_buf);
  3076. ctx->pb = NULL;
  3077. av_free(dummy_buf);
  3078. c->rtp_ctx[stream_index] = ctx;
  3079. return 0;
  3080. }
  3081. /********************************************************************/
  3082. /* ffserver initialization */
  3083. /* FIXME: This code should use avformat_new_stream() */
  3084. static LayeredAVStream *add_av_stream1(FFServerStream *stream,
  3085. AVCodecContext *codec, int copy)
  3086. {
  3087. LayeredAVStream *fst;
  3088. if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
  3089. return NULL;
  3090. fst = av_mallocz(sizeof(*fst));
  3091. if (!fst)
  3092. return NULL;
  3093. if (copy) {
  3094. fst->codec = avcodec_alloc_context3(codec->codec);
  3095. if (!fst->codec) {
  3096. av_free(fst);
  3097. return NULL;
  3098. }
  3099. avcodec_copy_context(fst->codec, codec);
  3100. } else
  3101. /* live streams must use the actual feed's codec since it may be
  3102. * updated later to carry extradata needed by them.
  3103. */
  3104. fst->codec = codec;
  3105. //NOTE we previously allocated internal & internal->avctx, these seemed uneeded though
  3106. fst->codecpar = avcodec_parameters_alloc();
  3107. fst->index = stream->nb_streams;
  3108. fst->time_base = (AVRational) {1, 90000};
  3109. fst->pts_wrap_bits = 33;
  3110. fst->sample_aspect_ratio = codec->sample_aspect_ratio;
  3111. stream->streams[stream->nb_streams++] = fst;
  3112. return fst;
  3113. }
  3114. /* return the stream number in the feed */
  3115. static int add_av_stream(FFServerStream *feed, LayeredAVStream *st)
  3116. {
  3117. LayeredAVStream *fst;
  3118. AVCodecContext *av, *av1;
  3119. int i;
  3120. av = st->codec;
  3121. for(i=0;i<feed->nb_streams;i++) {
  3122. av1 = feed->streams[i]->codec;
  3123. if (av1->codec_id == av->codec_id &&
  3124. av1->codec_type == av->codec_type &&
  3125. av1->bit_rate == av->bit_rate) {
  3126. switch(av->codec_type) {
  3127. case AVMEDIA_TYPE_AUDIO:
  3128. if (av1->channels == av->channels &&
  3129. av1->sample_rate == av->sample_rate)
  3130. return i;
  3131. break;
  3132. case AVMEDIA_TYPE_VIDEO:
  3133. if (av1->width == av->width &&
  3134. av1->height == av->height &&
  3135. av1->time_base.den == av->time_base.den &&
  3136. av1->time_base.num == av->time_base.num &&
  3137. av1->gop_size == av->gop_size)
  3138. return i;
  3139. break;
  3140. default:
  3141. abort();
  3142. }
  3143. }
  3144. }
  3145. fst = add_av_stream1(feed, av, 0);
  3146. if (!fst)
  3147. return -1;
  3148. if (st->recommended_encoder_configuration)
  3149. fst->recommended_encoder_configuration =
  3150. av_strdup(st->recommended_encoder_configuration);
  3151. return feed->nb_streams - 1;
  3152. }
  3153. static void remove_stream(FFServerStream *stream)
  3154. {
  3155. FFServerStream **ps;
  3156. ps = &config.first_stream;
  3157. while (*ps) {
  3158. if (*ps == stream)
  3159. *ps = (*ps)->next;
  3160. else
  3161. ps = &(*ps)->next;
  3162. }
  3163. }
  3164. /* compute the needed AVStream for each file */
  3165. static void build_file_streams(void)
  3166. {
  3167. FFServerStream *stream;
  3168. AVFormatContext *infile;
  3169. int i, ret;
  3170. /* gather all streams */
  3171. for(stream = config.first_stream; stream; stream = stream->next) {
  3172. infile = NULL;
  3173. if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
  3174. continue;
  3175. /* the stream comes from a file */
  3176. /* try to open the file */
  3177. /* open stream */
  3178. /* specific case: if transport stream output to RTP,
  3179. * we use a raw transport stream reader */
  3180. if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
  3181. av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
  3182. if (!stream->feed_filename[0]) {
  3183. http_log("Unspecified feed file for stream '%s'\n",
  3184. stream->filename);
  3185. goto fail;
  3186. }
  3187. http_log("Opening feed file '%s' for stream '%s'\n",
  3188. stream->feed_filename, stream->filename);
  3189. ret = avformat_open_input(&infile, stream->feed_filename,
  3190. stream->ifmt, &stream->in_opts);
  3191. if (ret < 0) {
  3192. http_log("Could not open '%s': %s\n", stream->feed_filename,
  3193. av_err2str(ret));
  3194. /* remove stream (no need to spend more time on it) */
  3195. fail:
  3196. remove_stream(stream);
  3197. } else {
  3198. /* find all the AVStreams inside and reference them in
  3199. * 'stream' */
  3200. if (avformat_find_stream_info(infile, NULL) < 0) {
  3201. http_log("Could not find codec parameters from '%s'\n",
  3202. stream->feed_filename);
  3203. avformat_close_input(&infile);
  3204. goto fail;
  3205. }
  3206. for(i=0;i<infile->nb_streams;i++)
  3207. add_av_stream1(stream, infile->streams[i]->codec, 1);
  3208. avformat_close_input(&infile);
  3209. }
  3210. }
  3211. }
  3212. static inline
  3213. int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream)
  3214. {
  3215. int matches = 1;
  3216. /* FIXME: Missed check on AVCodecContext.flags */
  3217. #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
  3218. if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
  3219. http_log("Codecs do not match for stream %d\n", stream);
  3220. matches = 0;
  3221. } else if (CHECK_CODEC(bit_rate)) {
  3222. http_log("Codec bitrates do not match for stream %d\n", stream);
  3223. matches = 0;
  3224. } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3225. if (av_cmp_q(ccf->time_base, ccs->time_base) ||
  3226. CHECK_CODEC(width) || CHECK_CODEC(height)) {
  3227. http_log("Codec width, height or framerate do not match for stream %d\n", stream);
  3228. matches = 0;
  3229. }
  3230. } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  3231. if (CHECK_CODEC(sample_rate) ||
  3232. CHECK_CODEC(channels) ||
  3233. CHECK_CODEC(frame_size)) {
  3234. http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
  3235. matches = 0;
  3236. }
  3237. } else {
  3238. http_log("Unknown codec type for stream %d\n", stream);
  3239. matches = 0;
  3240. }
  3241. return matches;
  3242. }
  3243. /* compute the needed AVStream for each feed */
  3244. static int build_feed_streams(void)
  3245. {
  3246. FFServerStream *stream, *feed;
  3247. int i, fd;
  3248. /* gather all streams */
  3249. for(stream = config.first_stream; stream; stream = stream->next) {
  3250. feed = stream->feed;
  3251. if (!feed)
  3252. continue;
  3253. if (stream->is_feed) {
  3254. for(i=0;i<stream->nb_streams;i++)
  3255. stream->feed_streams[i] = i;
  3256. continue;
  3257. }
  3258. /* we handle a stream coming from a feed */
  3259. for(i=0;i<stream->nb_streams;i++)
  3260. stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
  3261. }
  3262. /* create feed files if needed */
  3263. for(feed = config.first_feed; feed; feed = feed->next_feed) {
  3264. if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
  3265. AVFormatContext *s = NULL;
  3266. int matches = 0;
  3267. /* See if it matches */
  3268. if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
  3269. http_log("Deleting feed file '%s' as it appears "
  3270. "to be corrupt\n",
  3271. feed->feed_filename);
  3272. goto drop;
  3273. }
  3274. /* set buffer size */
  3275. if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
  3276. http_log("Failed to set buffer size\n");
  3277. avformat_close_input(&s);
  3278. goto bail;
  3279. }
  3280. /* Now see if it matches */
  3281. if (s->nb_streams != feed->nb_streams) {
  3282. http_log("Deleting feed file '%s' as stream counts "
  3283. "differ (%d != %d)\n",
  3284. feed->feed_filename, s->nb_streams, feed->nb_streams);
  3285. goto drop;
  3286. }
  3287. matches = 1;
  3288. for(i=0;i<s->nb_streams;i++) {
  3289. AVStream *ss;
  3290. LayeredAVStream *sf;
  3291. sf = feed->streams[i];
  3292. ss = s->streams[i];
  3293. if (sf->index != ss->index || sf->id != ss->id) {
  3294. http_log("Index & Id do not match for stream %d (%s)\n",
  3295. i, feed->feed_filename);
  3296. matches = 0;
  3297. break;
  3298. }
  3299. matches = check_codec_match (sf, ss, i);
  3300. if (!matches)
  3301. break;
  3302. }
  3303. drop:
  3304. if (s)
  3305. avformat_close_input(&s);
  3306. if (!matches) {
  3307. if (feed->readonly) {
  3308. http_log("Unable to delete read-only feed file '%s'\n",
  3309. feed->feed_filename);
  3310. goto bail;
  3311. }
  3312. unlink(feed->feed_filename);
  3313. }
  3314. }
  3315. if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
  3316. AVFormatContext *s = avformat_alloc_context();
  3317. if (!s) {
  3318. http_log("Failed to allocate context\n");
  3319. goto bail;
  3320. }
  3321. if (feed->readonly) {
  3322. http_log("Unable to create feed file '%s' as it is "
  3323. "marked readonly\n",
  3324. feed->feed_filename);
  3325. avformat_free_context(s);
  3326. goto bail;
  3327. }
  3328. /* only write the header of the ffm file */
  3329. if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
  3330. http_log("Could not open output feed file '%s'\n",
  3331. feed->feed_filename);
  3332. avformat_free_context(s);
  3333. goto bail;
  3334. }
  3335. s->oformat = feed->fmt;
  3336. for (i = 0; i<feed->nb_streams; i++) {
  3337. AVStream *st = avformat_new_stream(s, NULL); // FIXME free this
  3338. if (!st) {
  3339. http_log("Failed to allocate stream\n");
  3340. goto bail;
  3341. }
  3342. unlayer_stream(st, feed->streams[i]);
  3343. }
  3344. if (avformat_write_header(s, NULL) < 0) {
  3345. http_log("Container doesn't support the required parameters\n");
  3346. avio_closep(&s->pb);
  3347. s->streams = NULL;
  3348. s->nb_streams = 0;
  3349. avformat_free_context(s);
  3350. goto bail;
  3351. }
  3352. /* XXX: need better API */
  3353. av_freep(&s->priv_data);
  3354. avio_closep(&s->pb);
  3355. s->streams = NULL;
  3356. s->nb_streams = 0;
  3357. avformat_free_context(s);
  3358. }
  3359. /* get feed size and write index */
  3360. fd = open(feed->feed_filename, O_RDONLY);
  3361. if (fd < 0) {
  3362. http_log("Could not open output feed file '%s'\n",
  3363. feed->feed_filename);
  3364. goto bail;
  3365. }
  3366. feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
  3367. FFM_PACKET_SIZE);
  3368. feed->feed_size = lseek(fd, 0, SEEK_END);
  3369. /* ensure that we do not wrap before the end of file */
  3370. if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
  3371. feed->feed_max_size = feed->feed_size;
  3372. close(fd);
  3373. }
  3374. return 0;
  3375. bail:
  3376. return -1;
  3377. }
  3378. /* compute the bandwidth used by each stream */
  3379. static void compute_bandwidth(void)
  3380. {
  3381. unsigned bandwidth;
  3382. int i;
  3383. FFServerStream *stream;
  3384. for(stream = config.first_stream; stream; stream = stream->next) {
  3385. bandwidth = 0;
  3386. for(i=0;i<stream->nb_streams;i++) {
  3387. LayeredAVStream *st = stream->streams[i];
  3388. switch(st->codec->codec_type) {
  3389. case AVMEDIA_TYPE_AUDIO:
  3390. case AVMEDIA_TYPE_VIDEO:
  3391. bandwidth += st->codec->bit_rate;
  3392. break;
  3393. default:
  3394. break;
  3395. }
  3396. }
  3397. stream->bandwidth = (bandwidth + 999) / 1000;
  3398. }
  3399. }
  3400. static void handle_child_exit(int sig)
  3401. {
  3402. pid_t pid;
  3403. int status;
  3404. time_t uptime;
  3405. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  3406. FFServerStream *feed;
  3407. for (feed = config.first_feed; feed; feed = feed->next) {
  3408. if (feed->pid != pid)
  3409. continue;
  3410. uptime = time(0) - feed->pid_start;
  3411. feed->pid = 0;
  3412. fprintf(stderr,
  3413. "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
  3414. "seconds\n",
  3415. feed->filename, (int64_t) pid, status, (int64_t)uptime);
  3416. if (uptime < 30)
  3417. /* Turn off any more restarts */
  3418. ffserver_free_child_args(&feed->child_argv);
  3419. }
  3420. }
  3421. need_to_start_children = 1;
  3422. }
  3423. static void opt_debug(void)
  3424. {
  3425. config.debug = 1;
  3426. snprintf(config.logfilename, sizeof(config.logfilename), "-");
  3427. }
  3428. void show_help_default(const char *opt, const char *arg)
  3429. {
  3430. printf("usage: ffserver [options]\n"
  3431. "Hyper fast multi format Audio/Video streaming server\n");
  3432. printf("\n");
  3433. show_help_options(options, "Main options:", 0, 0, 0);
  3434. }
  3435. static const OptionDef options[] = {
  3436. #include "cmdutils_common_opts.h"
  3437. { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
  3438. { "d", 0, {(void*)opt_debug}, "enable debug mode" },
  3439. { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
  3440. { NULL },
  3441. };
  3442. int main(int argc, char **argv)
  3443. {
  3444. struct sigaction sigact = { { 0 } };
  3445. int cfg_parsed;
  3446. int ret = EXIT_FAILURE;
  3447. init_dynload();
  3448. config.filename = av_strdup("/etc/ffserver.conf");
  3449. parse_loglevel(argc, argv, options);
  3450. av_register_all();
  3451. avformat_network_init();
  3452. show_banner(argc, argv, options);
  3453. my_program_name = argv[0];
  3454. parse_options(NULL, argc, argv, options, NULL);
  3455. unsetenv("http_proxy"); /* Kill the http_proxy */
  3456. av_lfg_init(&random_state, av_get_random_seed());
  3457. sigact.sa_handler = handle_child_exit;
  3458. sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  3459. sigaction(SIGCHLD, &sigact, 0);
  3460. if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
  3461. fprintf(stderr, "Error reading configuration file '%s': %s\n",
  3462. config.filename, av_err2str(cfg_parsed));
  3463. goto bail;
  3464. }
  3465. /* open log file if needed */
  3466. if (config.logfilename[0] != '\0') {
  3467. if (!strcmp(config.logfilename, "-"))
  3468. logfile = stdout;
  3469. else
  3470. logfile = fopen(config.logfilename, "a");
  3471. av_log_set_callback(http_av_log);
  3472. }
  3473. build_file_streams();
  3474. if (build_feed_streams() < 0) {
  3475. http_log("Could not setup feed streams\n");
  3476. goto bail;
  3477. }
  3478. compute_bandwidth();
  3479. /* signal init */
  3480. signal(SIGPIPE, SIG_IGN);
  3481. if (http_server() < 0) {
  3482. http_log("Could not start server\n");
  3483. goto bail;
  3484. }
  3485. ret=EXIT_SUCCESS;
  3486. bail:
  3487. av_freep (&config.filename);
  3488. avformat_network_deinit();
  3489. return ret;
  3490. }